sqlite3.c revision 176bf03af2edfb2a45b66dcb5daf822cc50c499e
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.0.  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 Android Add
29#define fdatasync fsync
30#undef __APPLE__
31// End Android Add
32/************** Begin file sqliteInt.h ***************************************/
33/*
34** 2001 September 15
35**
36** The author disclaims copyright to this source code.  In place of
37** a legal notice, here is a blessing:
38**
39**    May you do good and not evil.
40**    May you find forgiveness for yourself and forgive others.
41**    May you share freely, never taking more than you give.
42**
43*************************************************************************
44** Internal interface definitions for SQLite.
45**
46*/
47#ifndef _SQLITEINT_H_
48#define _SQLITEINT_H_
49
50/*
51** These #defines should enable >2GB file support on POSIX if the
52** underlying operating system supports it.  If the OS lacks
53** large file support, or if the OS is windows, these should be no-ops.
54**
55** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
56** system #includes.  Hence, this block of code must be the very first
57** code in all source files.
58**
59** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
60** on the compiler command line.  This is necessary if you are compiling
61** on a recent machine (ex: Red Hat 7.2) but you want your code to work
62** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
63** without this option, LFS is enable.  But LFS does not exist in the kernel
64** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
65** portability you should omit LFS.
66**
67** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
68*/
69#ifndef SQLITE_DISABLE_LFS
70# define _LARGE_FILE       1
71# ifndef _FILE_OFFSET_BITS
72#   define _FILE_OFFSET_BITS 64
73# endif
74# define _LARGEFILE_SOURCE 1
75#endif
76
77/*
78** Include the configuration header output by 'configure' if we're using the
79** autoconf-based build
80*/
81#ifdef _HAVE_SQLITE_CONFIG_H
82#include "config.h"
83#endif
84
85/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
86/************** Begin file sqliteLimit.h *************************************/
87/*
88** 2007 May 7
89**
90** The author disclaims copyright to this source code.  In place of
91** a legal notice, here is a blessing:
92**
93**    May you do good and not evil.
94**    May you find forgiveness for yourself and forgive others.
95**    May you share freely, never taking more than you give.
96**
97*************************************************************************
98**
99** This file defines various limits of what SQLite can process.
100*/
101
102/*
103** The maximum length of a TEXT or BLOB in bytes.   This also
104** limits the size of a row in a table or index.
105**
106** The hard limit is the ability of a 32-bit signed integer
107** to count the size: 2^31-1 or 2147483647.
108*/
109#ifndef SQLITE_MAX_LENGTH
110# define SQLITE_MAX_LENGTH 1000000000
111#endif
112
113/*
114** This is the maximum number of
115**
116**    * Columns in a table
117**    * Columns in an index
118**    * Columns in a view
119**    * Terms in the SET clause of an UPDATE statement
120**    * Terms in the result set of a SELECT statement
121**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
122**    * Terms in the VALUES clause of an INSERT statement
123**
124** The hard upper limit here is 32676.  Most database people will
125** tell you that in a well-normalized database, you usually should
126** not have more than a dozen or so columns in any table.  And if
127** that is the case, there is no point in having more than a few
128** dozen values in any of the other situations described above.
129*/
130#ifndef SQLITE_MAX_COLUMN
131# define SQLITE_MAX_COLUMN 2000
132#endif
133
134/*
135** The maximum length of a single SQL statement in bytes.
136**
137** It used to be the case that setting this value to zero would
138** turn the limit off.  That is no longer true.  It is not possible
139** to turn this limit off.
140*/
141#ifndef SQLITE_MAX_SQL_LENGTH
142# define SQLITE_MAX_SQL_LENGTH 1000000000
143#endif
144
145/*
146** The maximum depth of an expression tree. This is limited to
147** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
148** want to place more severe limits on the complexity of an
149** expression.
150**
151** A value of 0 used to mean that the limit was not enforced.
152** But that is no longer true.  The limit is now strictly enforced
153** at all times.
154*/
155#ifndef SQLITE_MAX_EXPR_DEPTH
156# define SQLITE_MAX_EXPR_DEPTH 1000
157#endif
158
159/*
160** The maximum number of terms in a compound SELECT statement.
161** The code generator for compound SELECT statements does one
162** level of recursion for each term.  A stack overflow can result
163** if the number of terms is too large.  In practice, most SQL
164** never has more than 3 or 4 terms.  Use a value of 0 to disable
165** any limit on the number of terms in a compount SELECT.
166*/
167#ifndef SQLITE_MAX_COMPOUND_SELECT
168# define SQLITE_MAX_COMPOUND_SELECT 500
169#endif
170
171/*
172** The maximum number of opcodes in a VDBE program.
173** Not currently enforced.
174*/
175#ifndef SQLITE_MAX_VDBE_OP
176# define SQLITE_MAX_VDBE_OP 25000
177#endif
178
179/*
180** The maximum number of arguments to an SQL function.
181*/
182#ifndef SQLITE_MAX_FUNCTION_ARG
183# define SQLITE_MAX_FUNCTION_ARG 127
184#endif
185
186/*
187** The maximum number of in-memory pages to use for the main database
188** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
189*/
190#ifndef SQLITE_DEFAULT_CACHE_SIZE
191# define SQLITE_DEFAULT_CACHE_SIZE  2000
192#endif
193#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
194# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
195#endif
196
197/*
198** The default number of frames to accumulate in the log file before
199** checkpointing the database in WAL mode.
200*/
201#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
202# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
203#endif
204
205/*
206** The maximum number of attached databases.  This must be between 0
207** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
208** is used internally to track attached databases.
209*/
210#ifndef SQLITE_MAX_ATTACHED
211# define SQLITE_MAX_ATTACHED 10
212#endif
213
214
215/*
216** The maximum value of a ?nnn wildcard that the parser will accept.
217*/
218#ifndef SQLITE_MAX_VARIABLE_NUMBER
219# define SQLITE_MAX_VARIABLE_NUMBER 999
220#endif
221
222/* Maximum page size.  The upper bound on this value is 32768.  This a limit
223** imposed by the necessity of storing the value in a 2-byte unsigned integer
224** and the fact that the page size must be a power of 2.
225**
226** If this limit is changed, then the compiled library is technically
227** incompatible with an SQLite library compiled with a different limit. If
228** a process operating on a database with a page-size of 65536 bytes
229** crashes, then an instance of SQLite compiled with the default page-size
230** limit will not be able to rollback the aborted transaction. This could
231** lead to database corruption.
232*/
233#ifndef SQLITE_MAX_PAGE_SIZE
234# define SQLITE_MAX_PAGE_SIZE 32768
235#endif
236
237
238/*
239** The default size of a database page.
240*/
241#ifndef SQLITE_DEFAULT_PAGE_SIZE
242# define SQLITE_DEFAULT_PAGE_SIZE 1024
243#endif
244#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
245# undef SQLITE_DEFAULT_PAGE_SIZE
246# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
247#endif
248
249/*
250** Ordinarily, if no value is explicitly provided, SQLite creates databases
251** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
252** device characteristics (sector-size and atomic write() support),
253** SQLite may choose a larger value. This constant is the maximum value
254** SQLite will choose on its own.
255*/
256#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
257# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
258#endif
259#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
260# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
261# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
262#endif
263
264
265/*
266** Maximum number of pages in one database file.
267**
268** This is really just the default value for the max_page_count pragma.
269** This value can be lowered (or raised) at run-time using that the
270** max_page_count macro.
271*/
272#ifndef SQLITE_MAX_PAGE_COUNT
273# define SQLITE_MAX_PAGE_COUNT 1073741823
274#endif
275
276/*
277** Maximum length (in bytes) of the pattern in a LIKE or GLOB
278** operator.
279*/
280#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
281# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
282#endif
283
284/*
285** Maximum depth of recursion for triggers.
286**
287** A value of 1 means that a trigger program will not be able to itself
288** fire any triggers. A value of 0 means that no trigger programs at all
289** may be executed.
290*/
291#ifndef SQLITE_MAX_TRIGGER_DEPTH
292# define SQLITE_MAX_TRIGGER_DEPTH 1000
293#endif
294
295/************** End of sqliteLimit.h *****************************************/
296/************** Continuing where we left off in sqliteInt.h ******************/
297
298/* Disable nuisance warnings on Borland compilers */
299#if defined(__BORLANDC__)
300#pragma warn -rch /* unreachable code */
301#pragma warn -ccc /* Condition is always true or false */
302#pragma warn -aus /* Assigned value is never used */
303#pragma warn -csu /* Comparing signed and unsigned */
304#pragma warn -spa /* Suspicious pointer arithmetic */
305#endif
306
307/* Needed for various definitions... */
308#ifndef _GNU_SOURCE
309# define _GNU_SOURCE
310#endif
311
312/*
313** Include standard header files as necessary
314*/
315#ifdef HAVE_STDINT_H
316#include <stdint.h>
317#endif
318#ifdef HAVE_INTTYPES_H
319#include <inttypes.h>
320#endif
321
322/*
323** The number of samples of an index that SQLite takes in order to
324** construct a histogram of the table content when running ANALYZE
325** and with SQLITE_ENABLE_STAT2
326*/
327#define SQLITE_INDEX_SAMPLES 10
328
329/*
330** The following macros are used to cast pointers to integers and
331** integers to pointers.  The way you do this varies from one compiler
332** to the next, so we have developed the following set of #if statements
333** to generate appropriate macros for a wide range of compilers.
334**
335** The correct "ANSI" way to do this is to use the intptr_t type.
336** Unfortunately, that typedef is not available on all compilers, or
337** if it is available, it requires an #include of specific headers
338** that vary from one machine to the next.
339**
340** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
341** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
342** So we have to define the macros in different ways depending on the
343** compiler.
344*/
345#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
346# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
347# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
348#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
349# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
350# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
351#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
352# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
353# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
354#else                          /* Generates a warning - but it always works */
355# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
356# define SQLITE_PTR_TO_INT(X)  ((int)(X))
357#endif
358
359/*
360** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
361** Older versions of SQLite used an optional THREADSAFE macro.
362** We support that for legacy
363*/
364#if !defined(SQLITE_THREADSAFE)
365#if defined(THREADSAFE)
366# define SQLITE_THREADSAFE THREADSAFE
367#else
368# define SQLITE_THREADSAFE 1
369#endif
370#endif
371
372/*
373** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
374** It determines whether or not the features related to
375** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
376** be overridden at runtime using the sqlite3_config() API.
377*/
378#if !defined(SQLITE_DEFAULT_MEMSTATUS)
379# define SQLITE_DEFAULT_MEMSTATUS 1
380#endif
381
382/*
383** Exactly one of the following macros must be defined in order to
384** specify which memory allocation subsystem to use.
385**
386**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
387**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
388**
389** (Historical note:  There used to be several other options, but we've
390** pared it down to just these two.)
391**
392** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
393** the default.
394*/
395#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
396# error "At most one of the following compile-time configuration options\
397 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
398#endif
399#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
400# define SQLITE_SYSTEM_MALLOC 1
401#endif
402
403/*
404** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
405** sizes of memory allocations below this value where possible.
406*/
407#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
408# define SQLITE_MALLOC_SOFT_LIMIT 1024
409#endif
410
411/*
412** We need to define _XOPEN_SOURCE as follows in order to enable
413** recursive mutexes on most Unix systems.  But Mac OS X is different.
414** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
415** so it is omitted there.  See ticket #2673.
416**
417** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
418** implemented on some systems.  So we avoid defining it at all
419** if it is already defined or if it is unneeded because we are
420** not doing a threadsafe build.  Ticket #2681.
421**
422** See also ticket #2741.
423*/
424#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
425#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
426#endif
427
428/*
429** The TCL headers are only needed when compiling the TCL bindings.
430*/
431#if defined(SQLITE_TCL) || defined(TCLSH)
432# include <tcl.h>
433#endif
434
435/*
436** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
437** Setting NDEBUG makes the code smaller and run faster.  So the following
438** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
439** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
440** feature.
441*/
442#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
443# define NDEBUG 1
444#endif
445
446/*
447** The testcase() macro is used to aid in coverage testing.  When
448** doing coverage testing, the condition inside the argument to
449** testcase() must be evaluated both true and false in order to
450** get full branch coverage.  The testcase() macro is inserted
451** to help ensure adequate test coverage in places where simple
452** condition/decision coverage is inadequate.  For example, testcase()
453** can be used to make sure boundary values are tested.  For
454** bitmask tests, testcase() can be used to make sure each bit
455** is significant and used at least once.  On switch statements
456** where multiple cases go to the same block of code, testcase()
457** can insure that all cases are evaluated.
458**
459*/
460#ifdef SQLITE_COVERAGE_TEST
461SQLITE_PRIVATE   void sqlite3Coverage(int);
462# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
463#else
464# define testcase(X)
465#endif
466
467/*
468** The TESTONLY macro is used to enclose variable declarations or
469** other bits of code that are needed to support the arguments
470** within testcase() and assert() macros.
471*/
472#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
473# define TESTONLY(X)  X
474#else
475# define TESTONLY(X)
476#endif
477
478/*
479** Sometimes we need a small amount of code such as a variable initialization
480** to setup for a later assert() statement.  We do not want this code to
481** appear when assert() is disabled.  The following macro is therefore
482** used to contain that setup code.  The "VVA" acronym stands for
483** "Verification, Validation, and Accreditation".  In other words, the
484** code within VVA_ONLY() will only run during verification processes.
485*/
486#ifndef NDEBUG
487# define VVA_ONLY(X)  X
488#else
489# define VVA_ONLY(X)
490#endif
491
492/*
493** The ALWAYS and NEVER macros surround boolean expressions which
494** are intended to always be true or false, respectively.  Such
495** expressions could be omitted from the code completely.  But they
496** are included in a few cases in order to enhance the resilience
497** of SQLite to unexpected behavior - to make the code "self-healing"
498** or "ductile" rather than being "brittle" and crashing at the first
499** hint of unplanned behavior.
500**
501** In other words, ALWAYS and NEVER are added for defensive code.
502**
503** When doing coverage testing ALWAYS and NEVER are hard-coded to
504** be true and false so that the unreachable code then specify will
505** not be counted as untested code.
506*/
507#if defined(SQLITE_COVERAGE_TEST)
508# define ALWAYS(X)      (1)
509# define NEVER(X)       (0)
510#elif !defined(NDEBUG)
511# define ALWAYS(X)      ((X)?1:(assert(0),0))
512# define NEVER(X)       ((X)?(assert(0),1):0)
513#else
514# define ALWAYS(X)      (X)
515# define NEVER(X)       (X)
516#endif
517
518/*
519** The macro unlikely() is a hint that surrounds a boolean
520** expression that is usually false.  Macro likely() surrounds
521** a boolean expression that is usually true.  GCC is able to
522** use these hints to generate better code, sometimes.
523*/
524#if defined(__GNUC__) && 0
525# define likely(X)    __builtin_expect((X),1)
526# define unlikely(X)  __builtin_expect((X),0)
527#else
528# define likely(X)    !!(X)
529# define unlikely(X)  !!(X)
530#endif
531
532/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
533/************** Begin file sqlite3.h *****************************************/
534/*
535** 2001 September 15
536**
537** The author disclaims copyright to this source code.  In place of
538** a legal notice, here is a blessing:
539**
540**    May you do good and not evil.
541**    May you find forgiveness for yourself and forgive others.
542**    May you share freely, never taking more than you give.
543**
544*************************************************************************
545** This header file defines the interface that the SQLite library
546** presents to client programs.  If a C-function, structure, datatype,
547** or constant definition does not appear in this file, then it is
548** not a published API of SQLite, is subject to change without
549** notice, and should not be referenced by programs that use SQLite.
550**
551** Some of the definitions that are in this file are marked as
552** "experimental".  Experimental interfaces are normally new
553** features recently added to SQLite.  We do not anticipate changes
554** to experimental interfaces but reserve the right to make minor changes
555** if experience from use "in the wild" suggest such changes are prudent.
556**
557** The official C-language API documentation for SQLite is derived
558** from comments in this file.  This file is the authoritative source
559** on how SQLite interfaces are suppose to operate.
560**
561** The name of this file under configuration management is "sqlite.h.in".
562** The makefile makes some minor changes to this file (such as inserting
563** the version number) and changes its name to "sqlite3.h" as
564** part of the build process.
565*/
566#ifndef _SQLITE3_H_
567#define _SQLITE3_H_
568#include <stdarg.h>     /* Needed for the definition of va_list */
569
570/*
571** Make sure we can call this stuff from C++.
572*/
573#if 0
574extern "C" {
575#endif
576
577
578/*
579** Add the ability to override 'extern'
580*/
581#ifndef SQLITE_EXTERN
582# define SQLITE_EXTERN extern
583#endif
584
585#ifndef SQLITE_API
586# define SQLITE_API
587#endif
588
589
590/*
591** These no-op macros are used in front of interfaces to mark those
592** interfaces as either deprecated or experimental.  New applications
593** should not use deprecated interfaces - they are support for backwards
594** compatibility only.  Application writers should be aware that
595** experimental interfaces are subject to change in point releases.
596**
597** These macros used to resolve to various kinds of compiler magic that
598** would generate warning messages when they were used.  But that
599** compiler magic ended up generating such a flurry of bug reports
600** that we have taken it all out and gone back to using simple
601** noop macros.
602*/
603#define SQLITE_DEPRECATED
604#define SQLITE_EXPERIMENTAL
605
606/*
607** Ensure these symbols were not defined by some previous header file.
608*/
609#ifdef SQLITE_VERSION
610# undef SQLITE_VERSION
611#endif
612#ifdef SQLITE_VERSION_NUMBER
613# undef SQLITE_VERSION_NUMBER
614#endif
615
616/*
617** CAPI3REF: Compile-Time Library Version Numbers
618**
619** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
620** evaluates to a string literal that is the SQLite version in the
621** format "X.Y.Z" where X is the major version number (always 3 for
622** SQLite3) and Y is the minor version number and Z is the release number.)^
623** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
624** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
625** numbers used in [SQLITE_VERSION].)^
626** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
627** be larger than the release from which it is derived.  Either Y will
628** be held constant and Z will be incremented or else Y will be incremented
629** and Z will be reset to zero.
630**
631** Since version 3.6.18, SQLite source code has been stored in the
632** <a href="http://www.fossil-scm.org/">Fossil configuration management
633** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
634** a string which identifies a particular check-in of SQLite
635** within its configuration management system.  ^The SQLITE_SOURCE_ID
636** string contains the date and time of the check-in (UTC) and an SHA1
637** hash of the entire source tree.
638**
639** See also: [sqlite3_libversion()],
640** [sqlite3_libversion_number()], [sqlite3_sourceid()],
641** [sqlite_version()] and [sqlite_source_id()].
642*/
643#define SQLITE_VERSION        "3.7.0"
644#define SQLITE_VERSION_NUMBER 3007000
645#define SQLITE_SOURCE_ID      "2010-06-28 10:15:20 4932f22848b3d15a2b6dc5fa2cd69ce19182e2a4"
646
647/*
648** CAPI3REF: Run-Time Library Version Numbers
649** KEYWORDS: sqlite3_version, sqlite3_sourceid
650**
651** These interfaces provide the same information as the [SQLITE_VERSION],
652** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
653** but are associated with the library instead of the header file.  ^(Cautious
654** programmers might include assert() statements in their application to
655** verify that values returned by these interfaces match the macros in
656** the header, and thus insure that the application is
657** compiled with matching library and header files.
658**
659** <blockquote><pre>
660** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
661** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
662** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
663** </pre></blockquote>)^
664**
665** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
666** macro.  ^The sqlite3_libversion() function returns a pointer to the
667** to the sqlite3_version[] string constant.  The sqlite3_libversion()
668** function is provided for use in DLLs since DLL users usually do not have
669** direct access to string constants within the DLL.  ^The
670** sqlite3_libversion_number() function returns an integer equal to
671** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
672** a pointer to a string constant whose value is the same as the
673** [SQLITE_SOURCE_ID] C preprocessor macro.
674**
675** See also: [sqlite_version()] and [sqlite_source_id()].
676*/
677SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
678SQLITE_API const char *sqlite3_libversion(void);
679SQLITE_API const char *sqlite3_sourceid(void);
680SQLITE_API int sqlite3_libversion_number(void);
681
682/*
683** CAPI3REF: Run-Time Library Compilation Options Diagnostics
684**
685** ^The sqlite3_compileoption_used() function returns 0 or 1
686** indicating whether the specified option was defined at
687** compile time.  ^The SQLITE_ prefix may be omitted from the
688** option name passed to sqlite3_compileoption_used().
689**
690** ^The sqlite3_compileoption_get() function allows interating
691** over the list of options that were defined at compile time by
692** returning the N-th compile time option string.  ^If N is out of range,
693** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
694** prefix is omitted from any strings returned by
695** sqlite3_compileoption_get().
696**
697** ^Support for the diagnostic functions sqlite3_compileoption_used()
698** and sqlite3_compileoption_get() may be omitted by specifing the
699** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
700**
701** See also: SQL functions [sqlite_compileoption_used()] and
702** [sqlite_compileoption_get()] and the [compile_options pragma].
703*/
704#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
705SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
706SQLITE_API const char *sqlite3_compileoption_get(int N);
707#endif
708
709/*
710** CAPI3REF: Test To See If The Library Is Threadsafe
711**
712** ^The sqlite3_threadsafe() function returns zero if and only if
713** SQLite was compiled mutexing code omitted due to the
714** [SQLITE_THREADSAFE] compile-time option being set to 0.
715**
716** SQLite can be compiled with or without mutexes.  When
717** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
718** are enabled and SQLite is threadsafe.  When the
719** [SQLITE_THREADSAFE] macro is 0,
720** the mutexes are omitted.  Without the mutexes, it is not safe
721** to use SQLite concurrently from more than one thread.
722**
723** Enabling mutexes incurs a measurable performance penalty.
724** So if speed is of utmost importance, it makes sense to disable
725** the mutexes.  But for maximum safety, mutexes should be enabled.
726** ^The default behavior is for mutexes to be enabled.
727**
728** This interface can be used by an application to make sure that the
729** version of SQLite that it is linking against was compiled with
730** the desired setting of the [SQLITE_THREADSAFE] macro.
731**
732** This interface only reports on the compile-time mutex setting
733** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
734** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
735** can be fully or partially disabled using a call to [sqlite3_config()]
736** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
737** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
738** sqlite3_threadsafe() function shows only the compile-time setting of
739** thread safety, not any run-time changes to that setting made by
740** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
741** is unchanged by calls to sqlite3_config().)^
742**
743** See the [threading mode] documentation for additional information.
744*/
745SQLITE_API int sqlite3_threadsafe(void);
746
747/*
748** CAPI3REF: Database Connection Handle
749** KEYWORDS: {database connection} {database connections}
750**
751** Each open SQLite database is represented by a pointer to an instance of
752** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
753** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
754** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
755** is its destructor.  There are many other interfaces (such as
756** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
757** [sqlite3_busy_timeout()] to name but three) that are methods on an
758** sqlite3 object.
759*/
760typedef struct sqlite3 sqlite3;
761
762/*
763** CAPI3REF: 64-Bit Integer Types
764** KEYWORDS: sqlite_int64 sqlite_uint64
765**
766** Because there is no cross-platform way to specify 64-bit integer types
767** SQLite includes typedefs for 64-bit signed and unsigned integers.
768**
769** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
770** The sqlite_int64 and sqlite_uint64 types are supported for backwards
771** compatibility only.
772**
773** ^The sqlite3_int64 and sqlite_int64 types can store integer values
774** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
775** sqlite3_uint64 and sqlite_uint64 types can store integer values
776** between 0 and +18446744073709551615 inclusive.
777*/
778#ifdef SQLITE_INT64_TYPE
779  typedef SQLITE_INT64_TYPE sqlite_int64;
780  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
781#elif defined(_MSC_VER) || defined(__BORLANDC__)
782  typedef __int64 sqlite_int64;
783  typedef unsigned __int64 sqlite_uint64;
784#else
785  typedef long long int sqlite_int64;
786  typedef unsigned long long int sqlite_uint64;
787#endif
788typedef sqlite_int64 sqlite3_int64;
789typedef sqlite_uint64 sqlite3_uint64;
790
791/*
792** If compiling for a processor that lacks floating point support,
793** substitute integer for floating-point.
794*/
795#ifdef SQLITE_OMIT_FLOATING_POINT
796# define double sqlite3_int64
797#endif
798
799/*
800** CAPI3REF: Closing A Database Connection
801**
802** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
803** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
804** successfullly destroyed and all associated resources are deallocated.
805**
806** Applications must [sqlite3_finalize | finalize] all [prepared statements]
807** and [sqlite3_blob_close | close] all [BLOB handles] associated with
808** the [sqlite3] object prior to attempting to close the object.  ^If
809** sqlite3_close() is called on a [database connection] that still has
810** outstanding [prepared statements] or [BLOB handles], then it returns
811** SQLITE_BUSY.
812**
813** ^If [sqlite3_close()] is invoked while a transaction is open,
814** the transaction is automatically rolled back.
815**
816** The C parameter to [sqlite3_close(C)] must be either a NULL
817** pointer or an [sqlite3] object pointer obtained
818** from [sqlite3_open()], [sqlite3_open16()], or
819** [sqlite3_open_v2()], and not previously closed.
820** ^Calling sqlite3_close() with a NULL pointer argument is a
821** harmless no-op.
822*/
823SQLITE_API int sqlite3_close(sqlite3 *);
824
825/*
826** The type for a callback function.
827** This is legacy and deprecated.  It is included for historical
828** compatibility and is not documented.
829*/
830typedef int (*sqlite3_callback)(void*,int,char**, char**);
831
832/*
833** CAPI3REF: One-Step Query Execution Interface
834**
835** The sqlite3_exec() interface is a convenience wrapper around
836** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
837** that allows an application to run multiple statements of SQL
838** without having to use a lot of C code.
839**
840** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
841** semicolon-separate SQL statements passed into its 2nd argument,
842** in the context of the [database connection] passed in as its 1st
843** argument.  ^If the callback function of the 3rd argument to
844** sqlite3_exec() is not NULL, then it is invoked for each result row
845** coming out of the evaluated SQL statements.  ^The 4th argument to
846** to sqlite3_exec() is relayed through to the 1st argument of each
847** callback invocation.  ^If the callback pointer to sqlite3_exec()
848** is NULL, then no callback is ever invoked and result rows are
849** ignored.
850**
851** ^If an error occurs while evaluating the SQL statements passed into
852** sqlite3_exec(), then execution of the current statement stops and
853** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
854** is not NULL then any error message is written into memory obtained
855** from [sqlite3_malloc()] and passed back through the 5th parameter.
856** To avoid memory leaks, the application should invoke [sqlite3_free()]
857** on error message strings returned through the 5th parameter of
858** of sqlite3_exec() after the error message string is no longer needed.
859** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
860** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
861** NULL before returning.
862**
863** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
864** routine returns SQLITE_ABORT without invoking the callback again and
865** without running any subsequent SQL statements.
866**
867** ^The 2nd argument to the sqlite3_exec() callback function is the
868** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
869** callback is an array of pointers to strings obtained as if from
870** [sqlite3_column_text()], one for each column.  ^If an element of a
871** result row is NULL then the corresponding string pointer for the
872** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
873** sqlite3_exec() callback is an array of pointers to strings where each
874** entry represents the name of corresponding result column as obtained
875** from [sqlite3_column_name()].
876**
877** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
878** to an empty string, or a pointer that contains only whitespace and/or
879** SQL comments, then no SQL statements are evaluated and the database
880** is not changed.
881**
882** Restrictions:
883**
884** <ul>
885** <li> The application must insure that the 1st parameter to sqlite3_exec()
886**      is a valid and open [database connection].
887** <li> The application must not close [database connection] specified by
888**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
889** <li> The application must not modify the SQL statement text passed into
890**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
891** </ul>
892*/
893SQLITE_API int sqlite3_exec(
894  sqlite3*,                                  /* An open database */
895  const char *sql,                           /* SQL to be evaluated */
896  int (*callback)(void*,int,char**,char**),  /* Callback function */
897  void *,                                    /* 1st argument to callback */
898  char **errmsg                              /* Error msg written here */
899);
900
901/*
902** CAPI3REF: Result Codes
903** KEYWORDS: SQLITE_OK {error code} {error codes}
904** KEYWORDS: {result code} {result codes}
905**
906** Many SQLite functions return an integer result code from the set shown
907** here in order to indicates success or failure.
908**
909** New error codes may be added in future versions of SQLite.
910**
911** See also: [SQLITE_IOERR_READ | extended result codes]
912*/
913#define SQLITE_OK           0   /* Successful result */
914/* beginning-of-error-codes */
915#define SQLITE_ERROR        1   /* SQL error or missing database */
916#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
917#define SQLITE_PERM         3   /* Access permission denied */
918#define SQLITE_ABORT        4   /* Callback routine requested an abort */
919#define SQLITE_BUSY         5   /* The database file is locked */
920#define SQLITE_LOCKED       6   /* A table in the database is locked */
921#define SQLITE_NOMEM        7   /* A malloc() failed */
922#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
923#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
924#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
925#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
926#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
927#define SQLITE_FULL        13   /* Insertion failed because database is full */
928#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
929#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
930#define SQLITE_EMPTY       16   /* Database is empty */
931#define SQLITE_SCHEMA      17   /* The database schema changed */
932#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
933#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
934#define SQLITE_MISMATCH    20   /* Data type mismatch */
935#define SQLITE_MISUSE      21   /* Library used incorrectly */
936#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
937#define SQLITE_AUTH        23   /* Authorization denied */
938#define SQLITE_FORMAT      24   /* Auxiliary database format error */
939#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
940#define SQLITE_NOTADB      26   /* File opened that is not a database file */
941#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
942#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
943/* end-of-error-codes */
944
945/*
946** CAPI3REF: Extended Result Codes
947** KEYWORDS: {extended error code} {extended error codes}
948** KEYWORDS: {extended result code} {extended result codes}
949**
950** In its default configuration, SQLite API routines return one of 26 integer
951** [SQLITE_OK | result codes].  However, experience has shown that many of
952** these result codes are too coarse-grained.  They do not provide as
953** much information about problems as programmers might like.  In an effort to
954** address this, newer versions of SQLite (version 3.3.8 and later) include
955** support for additional result codes that provide more detailed information
956** about errors. The extended result codes are enabled or disabled
957** on a per database connection basis using the
958** [sqlite3_extended_result_codes()] API.
959**
960** Some of the available extended result codes are listed here.
961** One may expect the number of extended result codes will be expand
962** over time.  Software that uses extended result codes should expect
963** to see new result codes in future releases of SQLite.
964**
965** The SQLITE_OK result code will never be extended.  It will always
966** be exactly zero.
967*/
968#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
969#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
970#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
971#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
972#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
973#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
974#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
975#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
976#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
977#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
978#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
979#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
980#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
981#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
982#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
983#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
984#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
985#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
986#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
987#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
988#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
989#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
990#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
991
992/*
993** CAPI3REF: Flags For File Open Operations
994**
995** These bit values are intended for use in the
996** 3rd parameter to the [sqlite3_open_v2()] interface and
997** in the 4th parameter to the xOpen method of the
998** [sqlite3_vfs] object.
999*/
1000#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1001#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1002#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1003#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1004#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1005#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1006#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1007#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1008#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1009#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1010#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1011#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1012#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1013#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1014#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1015#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1016#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1017
1018/*
1019** CAPI3REF: Device Characteristics
1020**
1021** The xDeviceCapabilities method of the [sqlite3_io_methods]
1022** object returns an integer which is a vector of the these
1023** bit values expressing I/O characteristics of the mass storage
1024** device that holds the file that the [sqlite3_io_methods]
1025** refers to.
1026**
1027** The SQLITE_IOCAP_ATOMIC property means that all writes of
1028** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1029** mean that writes of blocks that are nnn bytes in size and
1030** are aligned to an address which is an integer multiple of
1031** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1032** that when data is appended to a file, the data is appended
1033** first then the size of the file is extended, never the other
1034** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1035** information is written to disk in the same order as calls
1036** to xWrite().
1037*/
1038#define SQLITE_IOCAP_ATOMIC                 0x00000001
1039#define SQLITE_IOCAP_ATOMIC512              0x00000002
1040#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1041#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1042#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1043#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1044#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1045#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1046#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1047#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1048#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1049#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1050
1051/*
1052** CAPI3REF: File Locking Levels
1053**
1054** SQLite uses one of these integer values as the second
1055** argument to calls it makes to the xLock() and xUnlock() methods
1056** of an [sqlite3_io_methods] object.
1057*/
1058#define SQLITE_LOCK_NONE          0
1059#define SQLITE_LOCK_SHARED        1
1060#define SQLITE_LOCK_RESERVED      2
1061#define SQLITE_LOCK_PENDING       3
1062#define SQLITE_LOCK_EXCLUSIVE     4
1063
1064/*
1065** CAPI3REF: Synchronization Type Flags
1066**
1067** When SQLite invokes the xSync() method of an
1068** [sqlite3_io_methods] object it uses a combination of
1069** these integer values as the second argument.
1070**
1071** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1072** sync operation only needs to flush data to mass storage.  Inode
1073** information need not be flushed. If the lower four bits of the flag
1074** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1075** If the lower four bits equal SQLITE_SYNC_FULL, that means
1076** to use Mac OS X style fullsync instead of fsync().
1077*/
1078#define SQLITE_SYNC_NORMAL        0x00002
1079#define SQLITE_SYNC_FULL          0x00003
1080#define SQLITE_SYNC_DATAONLY      0x00010
1081
1082/*
1083** CAPI3REF: OS Interface Open File Handle
1084**
1085** An [sqlite3_file] object represents an open file in the
1086** [sqlite3_vfs | OS interface layer].  Individual OS interface
1087** implementations will
1088** want to subclass this object by appending additional fields
1089** for their own use.  The pMethods entry is a pointer to an
1090** [sqlite3_io_methods] object that defines methods for performing
1091** I/O operations on the open file.
1092*/
1093typedef struct sqlite3_file sqlite3_file;
1094struct sqlite3_file {
1095  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1096};
1097
1098/*
1099** CAPI3REF: OS Interface File Virtual Methods Object
1100**
1101** Every file opened by the [sqlite3_vfs] xOpen method populates an
1102** [sqlite3_file] object (or, more commonly, a subclass of the
1103** [sqlite3_file] object) with a pointer to an instance of this object.
1104** This object defines the methods used to perform various operations
1105** against the open file represented by the [sqlite3_file] object.
1106**
1107** If the xOpen method sets the sqlite3_file.pMethods element
1108** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1109** may be invoked even if the xOpen reported that it failed.  The
1110** only way to prevent a call to xClose following a failed xOpen
1111** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1112**
1113** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1114** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1115** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1116** flag may be ORed in to indicate that only the data of the file
1117** and not its inode needs to be synced.
1118**
1119** The integer values to xLock() and xUnlock() are one of
1120** <ul>
1121** <li> [SQLITE_LOCK_NONE],
1122** <li> [SQLITE_LOCK_SHARED],
1123** <li> [SQLITE_LOCK_RESERVED],
1124** <li> [SQLITE_LOCK_PENDING], or
1125** <li> [SQLITE_LOCK_EXCLUSIVE].
1126** </ul>
1127** xLock() increases the lock. xUnlock() decreases the lock.
1128** The xCheckReservedLock() method checks whether any database connection,
1129** either in this process or in some other process, is holding a RESERVED,
1130** PENDING, or EXCLUSIVE lock on the file.  It returns true
1131** if such a lock exists and false otherwise.
1132**
1133** The xFileControl() method is a generic interface that allows custom
1134** VFS implementations to directly control an open file using the
1135** [sqlite3_file_control()] interface.  The second "op" argument is an
1136** integer opcode.  The third argument is a generic pointer intended to
1137** point to a structure that may contain arguments or space in which to
1138** write return values.  Potential uses for xFileControl() might be
1139** functions to enable blocking locks with timeouts, to change the
1140** locking strategy (for example to use dot-file locks), to inquire
1141** about the status of a lock, or to break stale locks.  The SQLite
1142** core reserves all opcodes less than 100 for its own use.
1143** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1144** Applications that define a custom xFileControl method should use opcodes
1145** greater than 100 to avoid conflicts.
1146**
1147** The xSectorSize() method returns the sector size of the
1148** device that underlies the file.  The sector size is the
1149** minimum write that can be performed without disturbing
1150** other bytes in the file.  The xDeviceCharacteristics()
1151** method returns a bit vector describing behaviors of the
1152** underlying device:
1153**
1154** <ul>
1155** <li> [SQLITE_IOCAP_ATOMIC]
1156** <li> [SQLITE_IOCAP_ATOMIC512]
1157** <li> [SQLITE_IOCAP_ATOMIC1K]
1158** <li> [SQLITE_IOCAP_ATOMIC2K]
1159** <li> [SQLITE_IOCAP_ATOMIC4K]
1160** <li> [SQLITE_IOCAP_ATOMIC8K]
1161** <li> [SQLITE_IOCAP_ATOMIC16K]
1162** <li> [SQLITE_IOCAP_ATOMIC32K]
1163** <li> [SQLITE_IOCAP_ATOMIC64K]
1164** <li> [SQLITE_IOCAP_SAFE_APPEND]
1165** <li> [SQLITE_IOCAP_SEQUENTIAL]
1166** </ul>
1167**
1168** The SQLITE_IOCAP_ATOMIC property means that all writes of
1169** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1170** mean that writes of blocks that are nnn bytes in size and
1171** are aligned to an address which is an integer multiple of
1172** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1173** that when data is appended to a file, the data is appended
1174** first then the size of the file is extended, never the other
1175** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1176** information is written to disk in the same order as calls
1177** to xWrite().
1178**
1179** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1180** in the unread portions of the buffer with zeros.  A VFS that
1181** fails to zero-fill short reads might seem to work.  However,
1182** failure to zero-fill short reads will eventually lead to
1183** database corruption.
1184*/
1185typedef struct sqlite3_io_methods sqlite3_io_methods;
1186struct sqlite3_io_methods {
1187  int iVersion;
1188  int (*xClose)(sqlite3_file*);
1189  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1190  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1191  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1192  int (*xSync)(sqlite3_file*, int flags);
1193  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1194  int (*xLock)(sqlite3_file*, int);
1195  int (*xUnlock)(sqlite3_file*, int);
1196  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1197  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1198  int (*xSectorSize)(sqlite3_file*);
1199  int (*xDeviceCharacteristics)(sqlite3_file*);
1200  /* Methods above are valid for version 1 */
1201  int (*xShmOpen)(sqlite3_file*);
1202  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1203  int (*xShmMap)(sqlite3_file*, int iPage, int pgsz, int, void volatile**);
1204  void (*xShmBarrier)(sqlite3_file*);
1205  int (*xShmClose)(sqlite3_file*, int deleteFlag);
1206  /* Methods above are valid for version 2 */
1207  /* Additional methods may be added in future releases */
1208};
1209
1210/*
1211** CAPI3REF: Standard File Control Opcodes
1212**
1213** These integer constants are opcodes for the xFileControl method
1214** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1215** interface.
1216**
1217** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1218** opcode causes the xFileControl method to write the current state of
1219** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1220** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1221** into an integer that the pArg argument points to. This capability
1222** is used during testing and only needs to be supported when SQLITE_TEST
1223** is defined.
1224**
1225** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1226** layer a hint of how large the database file will grow to be during the
1227** current transaction.  This hint is not guaranteed to be accurate but it
1228** is often close.  The underlying VFS might choose to preallocate database
1229** file space based on this hint in order to help writes to the database
1230** file run faster.
1231*/
1232#define SQLITE_FCNTL_LOCKSTATE        1
1233#define SQLITE_GET_LOCKPROXYFILE      2
1234#define SQLITE_SET_LOCKPROXYFILE      3
1235#define SQLITE_LAST_ERRNO             4
1236#define SQLITE_FCNTL_SIZE_HINT        5
1237
1238/*
1239** CAPI3REF: Mutex Handle
1240**
1241** The mutex module within SQLite defines [sqlite3_mutex] to be an
1242** abstract type for a mutex object.  The SQLite core never looks
1243** at the internal representation of an [sqlite3_mutex].  It only
1244** deals with pointers to the [sqlite3_mutex] object.
1245**
1246** Mutexes are created using [sqlite3_mutex_alloc()].
1247*/
1248typedef struct sqlite3_mutex sqlite3_mutex;
1249
1250/*
1251** CAPI3REF: OS Interface Object
1252**
1253** An instance of the sqlite3_vfs object defines the interface between
1254** the SQLite core and the underlying operating system.  The "vfs"
1255** in the name of the object stands for "virtual file system".
1256**
1257** The value of the iVersion field is initially 1 but may be larger in
1258** future versions of SQLite.  Additional fields may be appended to this
1259** object when the iVersion value is increased.  Note that the structure
1260** of the sqlite3_vfs object changes in the transaction between
1261** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1262** modified.
1263**
1264** The szOsFile field is the size of the subclassed [sqlite3_file]
1265** structure used by this VFS.  mxPathname is the maximum length of
1266** a pathname in this VFS.
1267**
1268** Registered sqlite3_vfs objects are kept on a linked list formed by
1269** the pNext pointer.  The [sqlite3_vfs_register()]
1270** and [sqlite3_vfs_unregister()] interfaces manage this list
1271** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1272** searches the list.  Neither the application code nor the VFS
1273** implementation should use the pNext pointer.
1274**
1275** The pNext field is the only field in the sqlite3_vfs
1276** structure that SQLite will ever modify.  SQLite will only access
1277** or modify this field while holding a particular static mutex.
1278** The application should never modify anything within the sqlite3_vfs
1279** object once the object has been registered.
1280**
1281** The zName field holds the name of the VFS module.  The name must
1282** be unique across all VFS modules.
1283**
1284** SQLite will guarantee that the zFilename parameter to xOpen
1285** is either a NULL pointer or string obtained
1286** from xFullPathname().  SQLite further guarantees that
1287** the string will be valid and unchanged until xClose() is
1288** called. Because of the previous sentence,
1289** the [sqlite3_file] can safely store a pointer to the
1290** filename if it needs to remember the filename for some reason.
1291** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1292** must invent its own temporary name for the file.  Whenever the
1293** xFilename parameter is NULL it will also be the case that the
1294** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1295**
1296** The flags argument to xOpen() includes all bits set in
1297** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1298** or [sqlite3_open16()] is used, then flags includes at least
1299** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1300** If xOpen() opens a file read-only then it sets *pOutFlags to
1301** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1302**
1303** SQLite will also add one of the following flags to the xOpen()
1304** call, depending on the object being opened:
1305**
1306** <ul>
1307** <li>  [SQLITE_OPEN_MAIN_DB]
1308** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1309** <li>  [SQLITE_OPEN_TEMP_DB]
1310** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1311** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1312** <li>  [SQLITE_OPEN_SUBJOURNAL]
1313** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1314** </ul>
1315**
1316** The file I/O implementation can use the object type flags to
1317** change the way it deals with files.  For example, an application
1318** that does not care about crash recovery or rollback might make
1319** the open of a journal file a no-op.  Writes to this journal would
1320** also be no-ops, and any attempt to read the journal would return
1321** SQLITE_IOERR.  Or the implementation might recognize that a database
1322** file will be doing page-aligned sector reads and writes in a random
1323** order and set up its I/O subsystem accordingly.
1324**
1325** SQLite might also add one of the following flags to the xOpen method:
1326**
1327** <ul>
1328** <li> [SQLITE_OPEN_DELETEONCLOSE]
1329** <li> [SQLITE_OPEN_EXCLUSIVE]
1330** </ul>
1331**
1332** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1333** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1334** will be set for TEMP  databases, journals and for subjournals.
1335**
1336** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1337** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1338** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1339** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1340** SQLITE_OPEN_CREATE, is used to indicate that file should always
1341** be created, and that it is an error if it already exists.
1342** It is <i>not</i> used to indicate the file should be opened
1343** for exclusive access.
1344**
1345** At least szOsFile bytes of memory are allocated by SQLite
1346** to hold the  [sqlite3_file] structure passed as the third
1347** argument to xOpen.  The xOpen method does not have to
1348** allocate the structure; it should just fill it in.  Note that
1349** the xOpen method must set the sqlite3_file.pMethods to either
1350** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1351** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1352** element will be valid after xOpen returns regardless of the success
1353** or failure of the xOpen call.
1354**
1355** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1356** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1357** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1358** to test whether a file is at least readable.   The file can be a
1359** directory.
1360**
1361** SQLite will always allocate at least mxPathname+1 bytes for the
1362** output buffer xFullPathname.  The exact size of the output buffer
1363** is also passed as a parameter to both  methods. If the output buffer
1364** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1365** handled as a fatal error by SQLite, vfs implementations should endeavor
1366** to prevent this by setting mxPathname to a sufficiently large value.
1367**
1368** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1369** are not strictly a part of the filesystem, but they are
1370** included in the VFS structure for completeness.
1371** The xRandomness() function attempts to return nBytes bytes
1372** of good-quality randomness into zOut.  The return value is
1373** the actual number of bytes of randomness obtained.
1374** The xSleep() method causes the calling thread to sleep for at
1375** least the number of microseconds given.  The xCurrentTime()
1376** method returns a Julian Day Number for the current date and time.
1377**
1378*/
1379typedef struct sqlite3_vfs sqlite3_vfs;
1380struct sqlite3_vfs {
1381  int iVersion;            /* Structure version number (currently 2) */
1382  int szOsFile;            /* Size of subclassed sqlite3_file */
1383  int mxPathname;          /* Maximum file pathname length */
1384  sqlite3_vfs *pNext;      /* Next registered VFS */
1385  const char *zName;       /* Name of this virtual file system */
1386  void *pAppData;          /* Pointer to application-specific data */
1387  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1388               int flags, int *pOutFlags);
1389  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1390  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1391  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1392  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1393  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1394  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1395  void (*xDlClose)(sqlite3_vfs*, void*);
1396  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1397  int (*xSleep)(sqlite3_vfs*, int microseconds);
1398  int (*xCurrentTime)(sqlite3_vfs*, double*);
1399  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1400  /*
1401  ** The methods above are in version 1 of the sqlite_vfs object
1402  ** definition.  Those that follow are added in version 2 or later
1403  */
1404  int (*xRename)(sqlite3_vfs*, const char *zOld, const char *zNew, int dirSync);
1405  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1406  /*
1407  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1408  ** New fields may be appended in figure versions.  The iVersion
1409  ** value will increment whenever this happens.
1410  */
1411};
1412
1413/*
1414** CAPI3REF: Flags for the xAccess VFS method
1415**
1416** These integer constants can be used as the third parameter to
1417** the xAccess method of an [sqlite3_vfs] object.  They determine
1418** what kind of permissions the xAccess method is looking for.
1419** With SQLITE_ACCESS_EXISTS, the xAccess method
1420** simply checks whether the file exists.
1421** With SQLITE_ACCESS_READWRITE, the xAccess method
1422** checks whether the file is both readable and writable.
1423** With SQLITE_ACCESS_READ, the xAccess method
1424** checks whether the file is readable.
1425*/
1426#define SQLITE_ACCESS_EXISTS    0
1427#define SQLITE_ACCESS_READWRITE 1
1428#define SQLITE_ACCESS_READ      2
1429
1430/*
1431** CAPI3REF: Flags for the xShmLock VFS method
1432**
1433** These integer constants define the various locking operations
1434** allowed by the xShmLock method of [sqlite3_io_methods].  The
1435** following are the only legal combinations of flags to the
1436** xShmLock method:
1437**
1438** <ul>
1439** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1440** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1441** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1442** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1443** </ul>
1444**
1445** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1446** was given no the corresponding lock.
1447**
1448** The xShmLock method can transition between unlocked and SHARED or
1449** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1450** and EXCLUSIVE.
1451*/
1452#define SQLITE_SHM_UNLOCK       1
1453#define SQLITE_SHM_LOCK         2
1454#define SQLITE_SHM_SHARED       4
1455#define SQLITE_SHM_EXCLUSIVE    8
1456
1457/*
1458** CAPI3REF: Maximum xShmLock index
1459**
1460** The xShmLock method on [sqlite3_io_methods] may use values
1461** between 0 and this upper bound as its "offset" argument.
1462** The SQLite core will never attempt to acquire or release a
1463** lock outside of this range
1464*/
1465#define SQLITE_SHM_NLOCK        8
1466
1467
1468/*
1469** CAPI3REF: Initialize The SQLite Library
1470**
1471** ^The sqlite3_initialize() routine initializes the
1472** SQLite library.  ^The sqlite3_shutdown() routine
1473** deallocates any resources that were allocated by sqlite3_initialize().
1474** These routines are designed to aid in process initialization and
1475** shutdown on embedded systems.  Workstation applications using
1476** SQLite normally do not need to invoke either of these routines.
1477**
1478** A call to sqlite3_initialize() is an "effective" call if it is
1479** the first time sqlite3_initialize() is invoked during the lifetime of
1480** the process, or if it is the first time sqlite3_initialize() is invoked
1481** following a call to sqlite3_shutdown().  ^(Only an effective call
1482** of sqlite3_initialize() does any initialization.  All other calls
1483** are harmless no-ops.)^
1484**
1485** A call to sqlite3_shutdown() is an "effective" call if it is the first
1486** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1487** an effective call to sqlite3_shutdown() does any deinitialization.
1488** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1489**
1490** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1491** is not.  The sqlite3_shutdown() interface must only be called from a
1492** single thread.  All open [database connections] must be closed and all
1493** other SQLite resources must be deallocated prior to invoking
1494** sqlite3_shutdown().
1495**
1496** Among other things, ^sqlite3_initialize() will invoke
1497** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1498** will invoke sqlite3_os_end().
1499**
1500** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1501** ^If for some reason, sqlite3_initialize() is unable to initialize
1502** the library (perhaps it is unable to allocate a needed resource such
1503** as a mutex) it returns an [error code] other than [SQLITE_OK].
1504**
1505** ^The sqlite3_initialize() routine is called internally by many other
1506** SQLite interfaces so that an application usually does not need to
1507** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1508** calls sqlite3_initialize() so the SQLite library will be automatically
1509** initialized when [sqlite3_open()] is called if it has not be initialized
1510** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1511** compile-time option, then the automatic calls to sqlite3_initialize()
1512** are omitted and the application must call sqlite3_initialize() directly
1513** prior to using any other SQLite interface.  For maximum portability,
1514** it is recommended that applications always invoke sqlite3_initialize()
1515** directly prior to using any other SQLite interface.  Future releases
1516** of SQLite may require this.  In other words, the behavior exhibited
1517** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1518** default behavior in some future release of SQLite.
1519**
1520** The sqlite3_os_init() routine does operating-system specific
1521** initialization of the SQLite library.  The sqlite3_os_end()
1522** routine undoes the effect of sqlite3_os_init().  Typical tasks
1523** performed by these routines include allocation or deallocation
1524** of static resources, initialization of global variables,
1525** setting up a default [sqlite3_vfs] module, or setting up
1526** a default configuration using [sqlite3_config()].
1527**
1528** The application should never invoke either sqlite3_os_init()
1529** or sqlite3_os_end() directly.  The application should only invoke
1530** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1531** interface is called automatically by sqlite3_initialize() and
1532** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1533** implementations for sqlite3_os_init() and sqlite3_os_end()
1534** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1535** When [custom builds | built for other platforms]
1536** (using the [SQLITE_OS_OTHER=1] compile-time
1537** option) the application must supply a suitable implementation for
1538** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1539** implementation of sqlite3_os_init() or sqlite3_os_end()
1540** must return [SQLITE_OK] on success and some other [error code] upon
1541** failure.
1542*/
1543SQLITE_API int sqlite3_initialize(void);
1544SQLITE_API int sqlite3_shutdown(void);
1545SQLITE_API int sqlite3_os_init(void);
1546SQLITE_API int sqlite3_os_end(void);
1547
1548/*
1549** CAPI3REF: Configuring The SQLite Library
1550**
1551** The sqlite3_config() interface is used to make global configuration
1552** changes to SQLite in order to tune SQLite to the specific needs of
1553** the application.  The default configuration is recommended for most
1554** applications and so this routine is usually not necessary.  It is
1555** provided to support rare applications with unusual needs.
1556**
1557** The sqlite3_config() interface is not threadsafe.  The application
1558** must insure that no other SQLite interfaces are invoked by other
1559** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1560** may only be invoked prior to library initialization using
1561** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1562** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1563** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1564** Note, however, that ^sqlite3_config() can be called as part of the
1565** implementation of an application-defined [sqlite3_os_init()].
1566**
1567** The first argument to sqlite3_config() is an integer
1568** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1569** what property of SQLite is to be configured.  Subsequent arguments
1570** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1571** in the first argument.
1572**
1573** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1574** ^If the option is unknown or SQLite is unable to set the option
1575** then this routine returns a non-zero [error code].
1576*/
1577SQLITE_API int sqlite3_config(int, ...);
1578
1579/*
1580** CAPI3REF: Configure database connections
1581**
1582** The sqlite3_db_config() interface is used to make configuration
1583** changes to a [database connection].  The interface is similar to
1584** [sqlite3_config()] except that the changes apply to a single
1585** [database connection] (specified in the first argument).  The
1586** sqlite3_db_config() interface should only be used immediately after
1587** the database connection is created using [sqlite3_open()],
1588** [sqlite3_open16()], or [sqlite3_open_v2()].
1589**
1590** The second argument to sqlite3_db_config(D,V,...)  is the
1591** configuration verb - an integer code that indicates what
1592** aspect of the [database connection] is being configured.
1593** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1594** New verbs are likely to be added in future releases of SQLite.
1595** Additional arguments depend on the verb.
1596**
1597** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1598** the call is considered successful.
1599*/
1600SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1601
1602/*
1603** CAPI3REF: Memory Allocation Routines
1604**
1605** An instance of this object defines the interface between SQLite
1606** and low-level memory allocation routines.
1607**
1608** This object is used in only one place in the SQLite interface.
1609** A pointer to an instance of this object is the argument to
1610** [sqlite3_config()] when the configuration option is
1611** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1612** By creating an instance of this object
1613** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1614** during configuration, an application can specify an alternative
1615** memory allocation subsystem for SQLite to use for all of its
1616** dynamic memory needs.
1617**
1618** Note that SQLite comes with several [built-in memory allocators]
1619** that are perfectly adequate for the overwhelming majority of applications
1620** and that this object is only useful to a tiny minority of applications
1621** with specialized memory allocation requirements.  This object is
1622** also used during testing of SQLite in order to specify an alternative
1623** memory allocator that simulates memory out-of-memory conditions in
1624** order to verify that SQLite recovers gracefully from such
1625** conditions.
1626**
1627** The xMalloc and xFree methods must work like the
1628** malloc() and free() functions from the standard C library.
1629** The xRealloc method must work like realloc() from the standard C library
1630** with the exception that if the second argument to xRealloc is zero,
1631** xRealloc must be a no-op - it must not perform any allocation or
1632** deallocation.  ^SQLite guarantees that the second argument to
1633** xRealloc is always a value returned by a prior call to xRoundup.
1634** And so in cases where xRoundup always returns a positive number,
1635** xRealloc can perform exactly as the standard library realloc() and
1636** still be in compliance with this specification.
1637**
1638** xSize should return the allocated size of a memory allocation
1639** previously obtained from xMalloc or xRealloc.  The allocated size
1640** is always at least as big as the requested size but may be larger.
1641**
1642** The xRoundup method returns what would be the allocated size of
1643** a memory allocation given a particular requested size.  Most memory
1644** allocators round up memory allocations at least to the next multiple
1645** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1646** Every memory allocation request coming in through [sqlite3_malloc()]
1647** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1648** that causes the corresponding memory allocation to fail.
1649**
1650** The xInit method initializes the memory allocator.  (For example,
1651** it might allocate any require mutexes or initialize internal data
1652** structures.  The xShutdown method is invoked (indirectly) by
1653** [sqlite3_shutdown()] and should deallocate any resources acquired
1654** by xInit.  The pAppData pointer is used as the only parameter to
1655** xInit and xShutdown.
1656**
1657** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1658** the xInit method, so the xInit method need not be threadsafe.  The
1659** xShutdown method is only called from [sqlite3_shutdown()] so it does
1660** not need to be threadsafe either.  For all other methods, SQLite
1661** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1662** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1663** it is by default) and so the methods are automatically serialized.
1664** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1665** methods must be threadsafe or else make their own arrangements for
1666** serialization.
1667**
1668** SQLite will never invoke xInit() more than once without an intervening
1669** call to xShutdown().
1670*/
1671typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1672struct sqlite3_mem_methods {
1673  void *(*xMalloc)(int);         /* Memory allocation function */
1674  void (*xFree)(void*);          /* Free a prior allocation */
1675  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1676  int (*xSize)(void*);           /* Return the size of an allocation */
1677  int (*xRoundup)(int);          /* Round up request size to allocation size */
1678  int (*xInit)(void*);           /* Initialize the memory allocator */
1679  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1680  void *pAppData;                /* Argument to xInit() and xShutdown() */
1681};
1682
1683/*
1684** CAPI3REF: Configuration Options
1685**
1686** These constants are the available integer configuration options that
1687** can be passed as the first argument to the [sqlite3_config()] interface.
1688**
1689** New configuration options may be added in future releases of SQLite.
1690** Existing configuration options might be discontinued.  Applications
1691** should check the return code from [sqlite3_config()] to make sure that
1692** the call worked.  The [sqlite3_config()] interface will return a
1693** non-zero [error code] if a discontinued or unsupported configuration option
1694** is invoked.
1695**
1696** <dl>
1697** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1698** <dd>There are no arguments to this option.  ^This option sets the
1699** [threading mode] to Single-thread.  In other words, it disables
1700** all mutexing and puts SQLite into a mode where it can only be used
1701** by a single thread.   ^If SQLite is compiled with
1702** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1703** it is not possible to change the [threading mode] from its default
1704** value of Single-thread and so [sqlite3_config()] will return
1705** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1706** configuration option.</dd>
1707**
1708** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1709** <dd>There are no arguments to this option.  ^This option sets the
1710** [threading mode] to Multi-thread.  In other words, it disables
1711** mutexing on [database connection] and [prepared statement] objects.
1712** The application is responsible for serializing access to
1713** [database connections] and [prepared statements].  But other mutexes
1714** are enabled so that SQLite will be safe to use in a multi-threaded
1715** environment as long as no two threads attempt to use the same
1716** [database connection] at the same time.  ^If SQLite is compiled with
1717** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1718** it is not possible to set the Multi-thread [threading mode] and
1719** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1720** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1721**
1722** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1723** <dd>There are no arguments to this option.  ^This option sets the
1724** [threading mode] to Serialized. In other words, this option enables
1725** all mutexes including the recursive
1726** mutexes on [database connection] and [prepared statement] objects.
1727** In this mode (which is the default when SQLite is compiled with
1728** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1729** to [database connections] and [prepared statements] so that the
1730** application is free to use the same [database connection] or the
1731** same [prepared statement] in different threads at the same time.
1732** ^If SQLite is compiled with
1733** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1734** it is not possible to set the Serialized [threading mode] and
1735** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1736** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1737**
1738** <dt>SQLITE_CONFIG_MALLOC</dt>
1739** <dd> ^(This option takes a single argument which is a pointer to an
1740** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1741** alternative low-level memory allocation routines to be used in place of
1742** the memory allocation routines built into SQLite.)^ ^SQLite makes
1743** its own private copy of the content of the [sqlite3_mem_methods] structure
1744** before the [sqlite3_config()] call returns.</dd>
1745**
1746** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1747** <dd> ^(This option takes a single argument which is a pointer to an
1748** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1749** structure is filled with the currently defined memory allocation routines.)^
1750** This option can be used to overload the default memory allocation
1751** routines with a wrapper that simulations memory allocation failure or
1752** tracks memory usage, for example. </dd>
1753**
1754** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1755** <dd> ^This option takes single argument of type int, interpreted as a
1756** boolean, which enables or disables the collection of memory allocation
1757** statistics. ^(When memory allocation statistics are disabled, the
1758** following SQLite interfaces become non-operational:
1759**   <ul>
1760**   <li> [sqlite3_memory_used()]
1761**   <li> [sqlite3_memory_highwater()]
1762**   <li> [sqlite3_soft_heap_limit()]
1763**   <li> [sqlite3_status()]
1764**   </ul>)^
1765** ^Memory allocation statistics are enabled by default unless SQLite is
1766** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1767** allocation statistics are disabled by default.
1768** </dd>
1769**
1770** <dt>SQLITE_CONFIG_SCRATCH</dt>
1771** <dd> ^This option specifies a static memory buffer that SQLite can use for
1772** scratch memory.  There are three arguments:  A pointer an 8-byte
1773** aligned memory buffer from which the scrach allocations will be
1774** drawn, the size of each scratch allocation (sz),
1775** and the maximum number of scratch allocations (N).  The sz
1776** argument must be a multiple of 16. The sz parameter should be a few bytes
1777** larger than the actual scratch space required due to internal overhead.
1778** The first argument must be a pointer to an 8-byte aligned buffer
1779** of at least sz*N bytes of memory.
1780** ^SQLite will use no more than one scratch buffer per thread.  So
1781** N should be set to the expected maximum number of threads.  ^SQLite will
1782** never require a scratch buffer that is more than 6 times the database
1783** page size. ^If SQLite needs needs additional scratch memory beyond
1784** what is provided by this configuration option, then
1785** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1786**
1787** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1788** <dd> ^This option specifies a static memory buffer that SQLite can use for
1789** the database page cache with the default page cache implemenation.
1790** This configuration should not be used if an application-define page
1791** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1792** There are three arguments to this option: A pointer to 8-byte aligned
1793** memory, the size of each page buffer (sz), and the number of pages (N).
1794** The sz argument should be the size of the largest database page
1795** (a power of two between 512 and 32768) plus a little extra for each
1796** page header.  ^The page header size is 20 to 40 bytes depending on
1797** the host architecture.  ^It is harmless, apart from the wasted memory,
1798** to make sz a little too large.  The first
1799** argument should point to an allocation of at least sz*N bytes of memory.
1800** ^SQLite will use the memory provided by the first argument to satisfy its
1801** memory needs for the first N pages that it adds to cache.  ^If additional
1802** page cache memory is needed beyond what is provided by this option, then
1803** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1804** ^The implementation might use one or more of the N buffers to hold
1805** memory accounting information. The pointer in the first argument must
1806** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1807** will be undefined.</dd>
1808**
1809** <dt>SQLITE_CONFIG_HEAP</dt>
1810** <dd> ^This option specifies a static memory buffer that SQLite will use
1811** for all of its dynamic memory allocation needs beyond those provided
1812** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1813** There are three arguments: An 8-byte aligned pointer to the memory,
1814** the number of bytes in the memory buffer, and the minimum allocation size.
1815** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1816** to using its default memory allocator (the system malloc() implementation),
1817** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1818** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1819** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1820** allocator is engaged to handle all of SQLites memory allocation needs.
1821** The first pointer (the memory pointer) must be aligned to an 8-byte
1822** boundary or subsequent behavior of SQLite will be undefined.</dd>
1823**
1824** <dt>SQLITE_CONFIG_MUTEX</dt>
1825** <dd> ^(This option takes a single argument which is a pointer to an
1826** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1827** alternative low-level mutex routines to be used in place
1828** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1829** content of the [sqlite3_mutex_methods] structure before the call to
1830** [sqlite3_config()] returns. ^If SQLite is compiled with
1831** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1832** the entire mutexing subsystem is omitted from the build and hence calls to
1833** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1834** return [SQLITE_ERROR].</dd>
1835**
1836** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1837** <dd> ^(This option takes a single argument which is a pointer to an
1838** instance of the [sqlite3_mutex_methods] structure.  The
1839** [sqlite3_mutex_methods]
1840** structure is filled with the currently defined mutex routines.)^
1841** This option can be used to overload the default mutex allocation
1842** routines with a wrapper used to track mutex usage for performance
1843** profiling or testing, for example.   ^If SQLite is compiled with
1844** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1845** the entire mutexing subsystem is omitted from the build and hence calls to
1846** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1847** return [SQLITE_ERROR].</dd>
1848**
1849** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1850** <dd> ^(This option takes two arguments that determine the default
1851** memory allocation for the lookaside memory allocator on each
1852** [database connection].  The first argument is the
1853** size of each lookaside buffer slot and the second is the number of
1854** slots allocated to each database connection.)^  ^(This option sets the
1855** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1856** verb to [sqlite3_db_config()] can be used to change the lookaside
1857** configuration on individual connections.)^ </dd>
1858**
1859** <dt>SQLITE_CONFIG_PCACHE</dt>
1860** <dd> ^(This option takes a single argument which is a pointer to
1861** an [sqlite3_pcache_methods] object.  This object specifies the interface
1862** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1863** object and uses it for page cache memory allocations.</dd>
1864**
1865** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1866** <dd> ^(This option takes a single argument which is a pointer to an
1867** [sqlite3_pcache_methods] object.  SQLite copies of the current
1868** page cache implementation into that object.)^ </dd>
1869**
1870** <dt>SQLITE_CONFIG_LOG</dt>
1871** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1872** function with a call signature of void(*)(void*,int,const char*),
1873** and a pointer to void. ^If the function pointer is not NULL, it is
1874** invoked by [sqlite3_log()] to process each logging event.  ^If the
1875** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1876** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1877** passed through as the first parameter to the application-defined logger
1878** function whenever that function is invoked.  ^The second parameter to
1879** the logger function is a copy of the first parameter to the corresponding
1880** [sqlite3_log()] call and is intended to be a [result code] or an
1881** [extended result code].  ^The third parameter passed to the logger is
1882** log message after formatting via [sqlite3_snprintf()].
1883** The SQLite logging interface is not reentrant; the logger function
1884** supplied by the application must not invoke any SQLite interface.
1885** In a multi-threaded application, the application-defined logger
1886** function must be threadsafe. </dd>
1887**
1888** </dl>
1889*/
1890#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1891#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1892#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1893#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1894#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1895#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1896#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1897#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1898#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1899#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1900#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1901/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1902#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1903#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1904#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1905#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1906
1907/*
1908** CAPI3REF: Database Connection Configuration Options
1909**
1910** These constants are the available integer configuration options that
1911** can be passed as the second argument to the [sqlite3_db_config()] interface.
1912**
1913** New configuration options may be added in future releases of SQLite.
1914** Existing configuration options might be discontinued.  Applications
1915** should check the return code from [sqlite3_db_config()] to make sure that
1916** the call worked.  ^The [sqlite3_db_config()] interface will return a
1917** non-zero [error code] if a discontinued or unsupported configuration option
1918** is invoked.
1919**
1920** <dl>
1921** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1922** <dd> ^This option takes three additional arguments that determine the
1923** [lookaside memory allocator] configuration for the [database connection].
1924** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1925** pointer to an memory buffer to use for lookaside memory.
1926** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1927** may be NULL in which case SQLite will allocate the
1928** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1929** size of each lookaside buffer slot.  ^The third argument is the number of
1930** slots.  The size of the buffer in the first argument must be greater than
1931** or equal to the product of the second and third arguments.  The buffer
1932** must be aligned to an 8-byte boundary.  ^If the second argument to
1933** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1934** rounded down to the next smaller
1935** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1936**
1937** </dl>
1938*/
1939#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1940
1941
1942/*
1943** CAPI3REF: Enable Or Disable Extended Result Codes
1944**
1945** ^The sqlite3_extended_result_codes() routine enables or disables the
1946** [extended result codes] feature of SQLite. ^The extended result
1947** codes are disabled by default for historical compatibility.
1948*/
1949SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1950
1951/*
1952** CAPI3REF: Last Insert Rowid
1953**
1954** ^Each entry in an SQLite table has a unique 64-bit signed
1955** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1956** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1957** names are not also used by explicitly declared columns. ^If
1958** the table has a column of type [INTEGER PRIMARY KEY] then that column
1959** is another alias for the rowid.
1960**
1961** ^This routine returns the [rowid] of the most recent
1962** successful [INSERT] into the database from the [database connection]
1963** in the first argument.  ^If no successful [INSERT]s
1964** have ever occurred on that database connection, zero is returned.
1965**
1966** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1967** row is returned by this routine as long as the trigger is running.
1968** But once the trigger terminates, the value returned by this routine
1969** reverts to the last value inserted before the trigger fired.)^
1970**
1971** ^An [INSERT] that fails due to a constraint violation is not a
1972** successful [INSERT] and does not change the value returned by this
1973** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1974** and INSERT OR ABORT make no changes to the return value of this
1975** routine when their insertion fails.  ^(When INSERT OR REPLACE
1976** encounters a constraint violation, it does not fail.  The
1977** INSERT continues to completion after deleting rows that caused
1978** the constraint problem so INSERT OR REPLACE will always change
1979** the return value of this interface.)^
1980**
1981** ^For the purposes of this routine, an [INSERT] is considered to
1982** be successful even if it is subsequently rolled back.
1983**
1984** This function is accessible to SQL statements via the
1985** [last_insert_rowid() SQL function].
1986**
1987** If a separate thread performs a new [INSERT] on the same
1988** database connection while the [sqlite3_last_insert_rowid()]
1989** function is running and thus changes the last insert [rowid],
1990** then the value returned by [sqlite3_last_insert_rowid()] is
1991** unpredictable and might not equal either the old or the new
1992** last insert [rowid].
1993*/
1994SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1995
1996/*
1997** CAPI3REF: Count The Number Of Rows Modified
1998**
1999** ^This function returns the number of database rows that were changed
2000** or inserted or deleted by the most recently completed SQL statement
2001** on the [database connection] specified by the first parameter.
2002** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2003** or [DELETE] statement are counted.  Auxiliary changes caused by
2004** triggers or [foreign key actions] are not counted.)^ Use the
2005** [sqlite3_total_changes()] function to find the total number of changes
2006** including changes caused by triggers and foreign key actions.
2007**
2008** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2009** are not counted.  Only real table changes are counted.
2010**
2011** ^(A "row change" is a change to a single row of a single table
2012** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2013** are changed as side effects of [REPLACE] constraint resolution,
2014** rollback, ABORT processing, [DROP TABLE], or by any other
2015** mechanisms do not count as direct row changes.)^
2016**
2017** A "trigger context" is a scope of execution that begins and
2018** ends with the script of a [CREATE TRIGGER | trigger].
2019** Most SQL statements are
2020** evaluated outside of any trigger.  This is the "top level"
2021** trigger context.  If a trigger fires from the top level, a
2022** new trigger context is entered for the duration of that one
2023** trigger.  Subtriggers create subcontexts for their duration.
2024**
2025** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2026** not create a new trigger context.
2027**
2028** ^This function returns the number of direct row changes in the
2029** most recent INSERT, UPDATE, or DELETE statement within the same
2030** trigger context.
2031**
2032** ^Thus, when called from the top level, this function returns the
2033** number of changes in the most recent INSERT, UPDATE, or DELETE
2034** that also occurred at the top level.  ^(Within the body of a trigger,
2035** the sqlite3_changes() interface can be called to find the number of
2036** changes in the most recently completed INSERT, UPDATE, or DELETE
2037** statement within the body of the same trigger.
2038** However, the number returned does not include changes
2039** caused by subtriggers since those have their own context.)^
2040**
2041** See also the [sqlite3_total_changes()] interface, the
2042** [count_changes pragma], and the [changes() SQL function].
2043**
2044** If a separate thread makes changes on the same database connection
2045** while [sqlite3_changes()] is running then the value returned
2046** is unpredictable and not meaningful.
2047*/
2048SQLITE_API int sqlite3_changes(sqlite3*);
2049
2050/*
2051** CAPI3REF: Total Number Of Rows Modified
2052**
2053** ^This function returns the number of row changes caused by [INSERT],
2054** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2055** ^(The count returned by sqlite3_total_changes() includes all changes
2056** from all [CREATE TRIGGER | trigger] contexts and changes made by
2057** [foreign key actions]. However,
2058** the count does not include changes used to implement [REPLACE] constraints,
2059** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2060** count does not include rows of views that fire an [INSTEAD OF trigger],
2061** though if the INSTEAD OF trigger makes changes of its own, those changes
2062** are counted.)^
2063** ^The sqlite3_total_changes() function counts the changes as soon as
2064** the statement that makes them is completed (when the statement handle
2065** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2066**
2067** See also the [sqlite3_changes()] interface, the
2068** [count_changes pragma], and the [total_changes() SQL function].
2069**
2070** If a separate thread makes changes on the same database connection
2071** while [sqlite3_total_changes()] is running then the value
2072** returned is unpredictable and not meaningful.
2073*/
2074SQLITE_API int sqlite3_total_changes(sqlite3*);
2075
2076/*
2077** CAPI3REF: Interrupt A Long-Running Query
2078**
2079** ^This function causes any pending database operation to abort and
2080** return at its earliest opportunity. This routine is typically
2081** called in response to a user action such as pressing "Cancel"
2082** or Ctrl-C where the user wants a long query operation to halt
2083** immediately.
2084**
2085** ^It is safe to call this routine from a thread different from the
2086** thread that is currently running the database operation.  But it
2087** is not safe to call this routine with a [database connection] that
2088** is closed or might close before sqlite3_interrupt() returns.
2089**
2090** ^If an SQL operation is very nearly finished at the time when
2091** sqlite3_interrupt() is called, then it might not have an opportunity
2092** to be interrupted and might continue to completion.
2093**
2094** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2095** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2096** that is inside an explicit transaction, then the entire transaction
2097** will be rolled back automatically.
2098**
2099** ^The sqlite3_interrupt(D) call is in effect until all currently running
2100** SQL statements on [database connection] D complete.  ^Any new SQL statements
2101** that are started after the sqlite3_interrupt() call and before the
2102** running statements reaches zero are interrupted as if they had been
2103** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2104** that are started after the running statement count reaches zero are
2105** not effected by the sqlite3_interrupt().
2106** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2107** SQL statements is a no-op and has no effect on SQL statements
2108** that are started after the sqlite3_interrupt() call returns.
2109**
2110** If the database connection closes while [sqlite3_interrupt()]
2111** is running then bad things will likely happen.
2112*/
2113SQLITE_API void sqlite3_interrupt(sqlite3*);
2114
2115/*
2116** CAPI3REF: Determine If An SQL Statement Is Complete
2117**
2118** These routines are useful during command-line input to determine if the
2119** currently entered text seems to form a complete SQL statement or
2120** if additional input is needed before sending the text into
2121** SQLite for parsing.  ^These routines return 1 if the input string
2122** appears to be a complete SQL statement.  ^A statement is judged to be
2123** complete if it ends with a semicolon token and is not a prefix of a
2124** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2125** string literals or quoted identifier names or comments are not
2126** independent tokens (they are part of the token in which they are
2127** embedded) and thus do not count as a statement terminator.  ^Whitespace
2128** and comments that follow the final semicolon are ignored.
2129**
2130** ^These routines return 0 if the statement is incomplete.  ^If a
2131** memory allocation fails, then SQLITE_NOMEM is returned.
2132**
2133** ^These routines do not parse the SQL statements thus
2134** will not detect syntactically incorrect SQL.
2135**
2136** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2137** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2138** automatically by sqlite3_complete16().  If that initialization fails,
2139** then the return value from sqlite3_complete16() will be non-zero
2140** regardless of whether or not the input SQL is complete.)^
2141**
2142** The input to [sqlite3_complete()] must be a zero-terminated
2143** UTF-8 string.
2144**
2145** The input to [sqlite3_complete16()] must be a zero-terminated
2146** UTF-16 string in native byte order.
2147*/
2148SQLITE_API int sqlite3_complete(const char *sql);
2149SQLITE_API int sqlite3_complete16(const void *sql);
2150
2151/*
2152** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2153**
2154** ^This routine sets a callback function that might be invoked whenever
2155** an attempt is made to open a database table that another thread
2156** or process has locked.
2157**
2158** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2159** is returned immediately upon encountering the lock.  ^If the busy callback
2160** is not NULL, then the callback might be invoked with two arguments.
2161**
2162** ^The first argument to the busy handler is a copy of the void* pointer which
2163** is the third argument to sqlite3_busy_handler().  ^The second argument to
2164** the busy handler callback is the number of times that the busy handler has
2165** been invoked for this locking event.  ^If the
2166** busy callback returns 0, then no additional attempts are made to
2167** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2168** ^If the callback returns non-zero, then another attempt
2169** is made to open the database for reading and the cycle repeats.
2170**
2171** The presence of a busy handler does not guarantee that it will be invoked
2172** when there is lock contention. ^If SQLite determines that invoking the busy
2173** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2174** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2175** Consider a scenario where one process is holding a read lock that
2176** it is trying to promote to a reserved lock and
2177** a second process is holding a reserved lock that it is trying
2178** to promote to an exclusive lock.  The first process cannot proceed
2179** because it is blocked by the second and the second process cannot
2180** proceed because it is blocked by the first.  If both processes
2181** invoke the busy handlers, neither will make any progress.  Therefore,
2182** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2183** will induce the first process to release its read lock and allow
2184** the second process to proceed.
2185**
2186** ^The default busy callback is NULL.
2187**
2188** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2189** when SQLite is in the middle of a large transaction where all the
2190** changes will not fit into the in-memory cache.  SQLite will
2191** already hold a RESERVED lock on the database file, but it needs
2192** to promote this lock to EXCLUSIVE so that it can spill cache
2193** pages into the database file without harm to concurrent
2194** readers.  ^If it is unable to promote the lock, then the in-memory
2195** cache will be left in an inconsistent state and so the error
2196** code is promoted from the relatively benign [SQLITE_BUSY] to
2197** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2198** forces an automatic rollback of the changes.  See the
2199** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2200** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2201** this is important.
2202**
2203** ^(There can only be a single busy handler defined for each
2204** [database connection].  Setting a new busy handler clears any
2205** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2206** will also set or clear the busy handler.
2207**
2208** The busy callback should not take any actions which modify the
2209** database connection that invoked the busy handler.  Any such actions
2210** result in undefined behavior.
2211**
2212** A busy handler must not close the database connection
2213** or [prepared statement] that invoked the busy handler.
2214*/
2215SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2216
2217/*
2218** CAPI3REF: Set A Busy Timeout
2219**
2220** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2221** for a specified amount of time when a table is locked.  ^The handler
2222** will sleep multiple times until at least "ms" milliseconds of sleeping
2223** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2224** the handler returns 0 which causes [sqlite3_step()] to return
2225** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2226**
2227** ^Calling this routine with an argument less than or equal to zero
2228** turns off all busy handlers.
2229**
2230** ^(There can only be a single busy handler for a particular
2231** [database connection] any any given moment.  If another busy handler
2232** was defined  (using [sqlite3_busy_handler()]) prior to calling
2233** this routine, that other busy handler is cleared.)^
2234*/
2235SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2236
2237/*
2238** CAPI3REF: Convenience Routines For Running Queries
2239**
2240** Definition: A <b>result table</b> is memory data structure created by the
2241** [sqlite3_get_table()] interface.  A result table records the
2242** complete query results from one or more queries.
2243**
2244** The table conceptually has a number of rows and columns.  But
2245** these numbers are not part of the result table itself.  These
2246** numbers are obtained separately.  Let N be the number of rows
2247** and M be the number of columns.
2248**
2249** A result table is an array of pointers to zero-terminated UTF-8 strings.
2250** There are (N+1)*M elements in the array.  The first M pointers point
2251** to zero-terminated strings that  contain the names of the columns.
2252** The remaining entries all point to query results.  NULL values result
2253** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2254** string representation as returned by [sqlite3_column_text()].
2255**
2256** A result table might consist of one or more memory allocations.
2257** It is not safe to pass a result table directly to [sqlite3_free()].
2258** A result table should be deallocated using [sqlite3_free_table()].
2259**
2260** As an example of the result table format, suppose a query result
2261** is as follows:
2262**
2263** <blockquote><pre>
2264**        Name        | Age
2265**        -----------------------
2266**        Alice       | 43
2267**        Bob         | 28
2268**        Cindy       | 21
2269** </pre></blockquote>
2270**
2271** There are two column (M==2) and three rows (N==3).  Thus the
2272** result table has 8 entries.  Suppose the result table is stored
2273** in an array names azResult.  Then azResult holds this content:
2274**
2275** <blockquote><pre>
2276**        azResult&#91;0] = "Name";
2277**        azResult&#91;1] = "Age";
2278**        azResult&#91;2] = "Alice";
2279**        azResult&#91;3] = "43";
2280**        azResult&#91;4] = "Bob";
2281**        azResult&#91;5] = "28";
2282**        azResult&#91;6] = "Cindy";
2283**        azResult&#91;7] = "21";
2284** </pre></blockquote>
2285**
2286** ^The sqlite3_get_table() function evaluates one or more
2287** semicolon-separated SQL statements in the zero-terminated UTF-8
2288** string of its 2nd parameter and returns a result table to the
2289** pointer given in its 3rd parameter.
2290**
2291** After the application has finished with the result from sqlite3_get_table(),
2292** it should pass the result table pointer to sqlite3_free_table() in order to
2293** release the memory that was malloced.  Because of the way the
2294** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2295** function must not try to call [sqlite3_free()] directly.  Only
2296** [sqlite3_free_table()] is able to release the memory properly and safely.
2297**
2298** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2299** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2300** to any internal data structures of SQLite.  It uses only the public
2301** interface defined here.  As a consequence, errors that occur in the
2302** wrapper layer outside of the internal [sqlite3_exec()] call are not
2303** reflected in subsequent calls to [sqlite3_errcode()] or
2304** [sqlite3_errmsg()].)^
2305*/
2306SQLITE_API int sqlite3_get_table(
2307  sqlite3 *db,          /* An open database */
2308  const char *zSql,     /* SQL to be evaluated */
2309  char ***pazResult,    /* Results of the query */
2310  int *pnRow,           /* Number of result rows written here */
2311  int *pnColumn,        /* Number of result columns written here */
2312  char **pzErrmsg       /* Error msg written here */
2313);
2314SQLITE_API void sqlite3_free_table(char **result);
2315
2316/*
2317** CAPI3REF: Formatted String Printing Functions
2318**
2319** These routines are work-alikes of the "printf()" family of functions
2320** from the standard C library.
2321**
2322** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2323** results into memory obtained from [sqlite3_malloc()].
2324** The strings returned by these two routines should be
2325** released by [sqlite3_free()].  ^Both routines return a
2326** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2327** memory to hold the resulting string.
2328**
2329** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2330** the standard C library.  The result is written into the
2331** buffer supplied as the second parameter whose size is given by
2332** the first parameter. Note that the order of the
2333** first two parameters is reversed from snprintf().)^  This is an
2334** historical accident that cannot be fixed without breaking
2335** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2336** returns a pointer to its buffer instead of the number of
2337** characters actually written into the buffer.)^  We admit that
2338** the number of characters written would be a more useful return
2339** value but we cannot change the implementation of sqlite3_snprintf()
2340** now without breaking compatibility.
2341**
2342** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2343** guarantees that the buffer is always zero-terminated.  ^The first
2344** parameter "n" is the total size of the buffer, including space for
2345** the zero terminator.  So the longest string that can be completely
2346** written will be n-1 characters.
2347**
2348** These routines all implement some additional formatting
2349** options that are useful for constructing SQL statements.
2350** All of the usual printf() formatting options apply.  In addition, there
2351** is are "%q", "%Q", and "%z" options.
2352**
2353** ^(The %q option works like %s in that it substitutes a null-terminated
2354** string from the argument list.  But %q also doubles every '\'' character.
2355** %q is designed for use inside a string literal.)^  By doubling each '\''
2356** character it escapes that character and allows it to be inserted into
2357** the string.
2358**
2359** For example, assume the string variable zText contains text as follows:
2360**
2361** <blockquote><pre>
2362**  char *zText = "It's a happy day!";
2363** </pre></blockquote>
2364**
2365** One can use this text in an SQL statement as follows:
2366**
2367** <blockquote><pre>
2368**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2369**  sqlite3_exec(db, zSQL, 0, 0, 0);
2370**  sqlite3_free(zSQL);
2371** </pre></blockquote>
2372**
2373** Because the %q format string is used, the '\'' character in zText
2374** is escaped and the SQL generated is as follows:
2375**
2376** <blockquote><pre>
2377**  INSERT INTO table1 VALUES('It''s a happy day!')
2378** </pre></blockquote>
2379**
2380** This is correct.  Had we used %s instead of %q, the generated SQL
2381** would have looked like this:
2382**
2383** <blockquote><pre>
2384**  INSERT INTO table1 VALUES('It's a happy day!');
2385** </pre></blockquote>
2386**
2387** This second example is an SQL syntax error.  As a general rule you should
2388** always use %q instead of %s when inserting text into a string literal.
2389**
2390** ^(The %Q option works like %q except it also adds single quotes around
2391** the outside of the total string.  Additionally, if the parameter in the
2392** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2393** single quotes).)^  So, for example, one could say:
2394**
2395** <blockquote><pre>
2396**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2397**  sqlite3_exec(db, zSQL, 0, 0, 0);
2398**  sqlite3_free(zSQL);
2399** </pre></blockquote>
2400**
2401** The code above will render a correct SQL statement in the zSQL
2402** variable even if the zText variable is a NULL pointer.
2403**
2404** ^(The "%z" formatting option works like "%s" but with the
2405** addition that after the string has been read and copied into
2406** the result, [sqlite3_free()] is called on the input string.)^
2407*/
2408SQLITE_API char *sqlite3_mprintf(const char*,...);
2409SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2410SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2411
2412/*
2413** CAPI3REF: Memory Allocation Subsystem
2414**
2415** The SQLite core uses these three routines for all of its own
2416** internal memory allocation needs. "Core" in the previous sentence
2417** does not include operating-system specific VFS implementation.  The
2418** Windows VFS uses native malloc() and free() for some operations.
2419**
2420** ^The sqlite3_malloc() routine returns a pointer to a block
2421** of memory at least N bytes in length, where N is the parameter.
2422** ^If sqlite3_malloc() is unable to obtain sufficient free
2423** memory, it returns a NULL pointer.  ^If the parameter N to
2424** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2425** a NULL pointer.
2426**
2427** ^Calling sqlite3_free() with a pointer previously returned
2428** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2429** that it might be reused.  ^The sqlite3_free() routine is
2430** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2431** to sqlite3_free() is harmless.  After being freed, memory
2432** should neither be read nor written.  Even reading previously freed
2433** memory might result in a segmentation fault or other severe error.
2434** Memory corruption, a segmentation fault, or other severe error
2435** might result if sqlite3_free() is called with a non-NULL pointer that
2436** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2437**
2438** ^(The sqlite3_realloc() interface attempts to resize a
2439** prior memory allocation to be at least N bytes, where N is the
2440** second parameter.  The memory allocation to be resized is the first
2441** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2442** is a NULL pointer then its behavior is identical to calling
2443** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2444** ^If the second parameter to sqlite3_realloc() is zero or
2445** negative then the behavior is exactly the same as calling
2446** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2447** ^sqlite3_realloc() returns a pointer to a memory allocation
2448** of at least N bytes in size or NULL if sufficient memory is unavailable.
2449** ^If M is the size of the prior allocation, then min(N,M) bytes
2450** of the prior allocation are copied into the beginning of buffer returned
2451** by sqlite3_realloc() and the prior allocation is freed.
2452** ^If sqlite3_realloc() returns NULL, then the prior allocation
2453** is not freed.
2454**
2455** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2456** is always aligned to at least an 8 byte boundary.
2457**
2458** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2459** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2460** implementation of these routines to be omitted.  That capability
2461** is no longer provided.  Only built-in memory allocators can be used.
2462**
2463** The Windows OS interface layer calls
2464** the system malloc() and free() directly when converting
2465** filenames between the UTF-8 encoding used by SQLite
2466** and whatever filename encoding is used by the particular Windows
2467** installation.  Memory allocation errors are detected, but
2468** they are reported back as [SQLITE_CANTOPEN] or
2469** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2470**
2471** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2472** must be either NULL or else pointers obtained from a prior
2473** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2474** not yet been released.
2475**
2476** The application must not read or write any part of
2477** a block of memory after it has been released using
2478** [sqlite3_free()] or [sqlite3_realloc()].
2479*/
2480SQLITE_API void *sqlite3_malloc(int);
2481SQLITE_API void *sqlite3_realloc(void*, int);
2482SQLITE_API void sqlite3_free(void*);
2483
2484/*
2485** CAPI3REF: Memory Allocator Statistics
2486**
2487** SQLite provides these two interfaces for reporting on the status
2488** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2489** routines, which form the built-in memory allocation subsystem.
2490**
2491** ^The [sqlite3_memory_used()] routine returns the number of bytes
2492** of memory currently outstanding (malloced but not freed).
2493** ^The [sqlite3_memory_highwater()] routine returns the maximum
2494** value of [sqlite3_memory_used()] since the high-water mark
2495** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2496** [sqlite3_memory_highwater()] include any overhead
2497** added by SQLite in its implementation of [sqlite3_malloc()],
2498** but not overhead added by the any underlying system library
2499** routines that [sqlite3_malloc()] may call.
2500**
2501** ^The memory high-water mark is reset to the current value of
2502** [sqlite3_memory_used()] if and only if the parameter to
2503** [sqlite3_memory_highwater()] is true.  ^The value returned
2504** by [sqlite3_memory_highwater(1)] is the high-water mark
2505** prior to the reset.
2506*/
2507SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2508SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2509
2510/*
2511** CAPI3REF: Pseudo-Random Number Generator
2512**
2513** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2514** select random [ROWID | ROWIDs] when inserting new records into a table that
2515** already uses the largest possible [ROWID].  The PRNG is also used for
2516** the build-in random() and randomblob() SQL functions.  This interface allows
2517** applications to access the same PRNG for other purposes.
2518**
2519** ^A call to this routine stores N bytes of randomness into buffer P.
2520**
2521** ^The first time this routine is invoked (either internally or by
2522** the application) the PRNG is seeded using randomness obtained
2523** from the xRandomness method of the default [sqlite3_vfs] object.
2524** ^On all subsequent invocations, the pseudo-randomness is generated
2525** internally and without recourse to the [sqlite3_vfs] xRandomness
2526** method.
2527*/
2528SQLITE_API void sqlite3_randomness(int N, void *P);
2529
2530/*
2531** CAPI3REF: Compile-Time Authorization Callbacks
2532**
2533** ^This routine registers a authorizer callback with a particular
2534** [database connection], supplied in the first argument.
2535** ^The authorizer callback is invoked as SQL statements are being compiled
2536** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2537** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2538** points during the compilation process, as logic is being created
2539** to perform various actions, the authorizer callback is invoked to
2540** see if those actions are allowed.  ^The authorizer callback should
2541** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2542** specific action but allow the SQL statement to continue to be
2543** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2544** rejected with an error.  ^If the authorizer callback returns
2545** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2546** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2547** the authorizer will fail with an error message.
2548**
2549** When the callback returns [SQLITE_OK], that means the operation
2550** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2551** [sqlite3_prepare_v2()] or equivalent call that triggered the
2552** authorizer will fail with an error message explaining that
2553** access is denied.
2554**
2555** ^The first parameter to the authorizer callback is a copy of the third
2556** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2557** to the callback is an integer [SQLITE_COPY | action code] that specifies
2558** the particular action to be authorized. ^The third through sixth parameters
2559** to the callback are zero-terminated strings that contain additional
2560** details about the action to be authorized.
2561**
2562** ^If the action code is [SQLITE_READ]
2563** and the callback returns [SQLITE_IGNORE] then the
2564** [prepared statement] statement is constructed to substitute
2565** a NULL value in place of the table column that would have
2566** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2567** return can be used to deny an untrusted user access to individual
2568** columns of a table.
2569** ^If the action code is [SQLITE_DELETE] and the callback returns
2570** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2571** [truncate optimization] is disabled and all rows are deleted individually.
2572**
2573** An authorizer is used when [sqlite3_prepare | preparing]
2574** SQL statements from an untrusted source, to ensure that the SQL statements
2575** do not try to access data they are not allowed to see, or that they do not
2576** try to execute malicious statements that damage the database.  For
2577** example, an application may allow a user to enter arbitrary
2578** SQL queries for evaluation by a database.  But the application does
2579** not want the user to be able to make arbitrary changes to the
2580** database.  An authorizer could then be put in place while the
2581** user-entered SQL is being [sqlite3_prepare | prepared] that
2582** disallows everything except [SELECT] statements.
2583**
2584** Applications that need to process SQL from untrusted sources
2585** might also consider lowering resource limits using [sqlite3_limit()]
2586** and limiting database size using the [max_page_count] [PRAGMA]
2587** in addition to using an authorizer.
2588**
2589** ^(Only a single authorizer can be in place on a database connection
2590** at a time.  Each call to sqlite3_set_authorizer overrides the
2591** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2592** The authorizer is disabled by default.
2593**
2594** The authorizer callback must not do anything that will modify
2595** the database connection that invoked the authorizer callback.
2596** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2597** database connections for the meaning of "modify" in this paragraph.
2598**
2599** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2600** statement might be re-prepared during [sqlite3_step()] due to a
2601** schema change.  Hence, the application should ensure that the
2602** correct authorizer callback remains in place during the [sqlite3_step()].
2603**
2604** ^Note that the authorizer callback is invoked only during
2605** [sqlite3_prepare()] or its variants.  Authorization is not
2606** performed during statement evaluation in [sqlite3_step()], unless
2607** as stated in the previous paragraph, sqlite3_step() invokes
2608** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2609*/
2610SQLITE_API int sqlite3_set_authorizer(
2611  sqlite3*,
2612  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2613  void *pUserData
2614);
2615
2616/*
2617** CAPI3REF: Authorizer Return Codes
2618**
2619** The [sqlite3_set_authorizer | authorizer callback function] must
2620** return either [SQLITE_OK] or one of these two constants in order
2621** to signal SQLite whether or not the action is permitted.  See the
2622** [sqlite3_set_authorizer | authorizer documentation] for additional
2623** information.
2624*/
2625#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2626#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2627
2628/*
2629** CAPI3REF: Authorizer Action Codes
2630**
2631** The [sqlite3_set_authorizer()] interface registers a callback function
2632** that is invoked to authorize certain SQL statement actions.  The
2633** second parameter to the callback is an integer code that specifies
2634** what action is being authorized.  These are the integer action codes that
2635** the authorizer callback may be passed.
2636**
2637** These action code values signify what kind of operation is to be
2638** authorized.  The 3rd and 4th parameters to the authorization
2639** callback function will be parameters or NULL depending on which of these
2640** codes is used as the second parameter.  ^(The 5th parameter to the
2641** authorizer callback is the name of the database ("main", "temp",
2642** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2643** is the name of the inner-most trigger or view that is responsible for
2644** the access attempt or NULL if this access attempt is directly from
2645** top-level SQL code.
2646*/
2647/******************************************* 3rd ************ 4th ***********/
2648#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2649#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2650#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2651#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2652#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2653#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2654#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2655#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2656#define SQLITE_DELETE                9   /* Table Name      NULL            */
2657#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2658#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2659#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2660#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2661#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2662#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2663#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2664#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2665#define SQLITE_INSERT               18   /* Table Name      NULL            */
2666#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2667#define SQLITE_READ                 20   /* Table Name      Column Name     */
2668#define SQLITE_SELECT               21   /* NULL            NULL            */
2669#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2670#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2671#define SQLITE_ATTACH               24   /* Filename        NULL            */
2672#define SQLITE_DETACH               25   /* Database Name   NULL            */
2673#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2674#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2675#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2676#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2677#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2678#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2679#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2680#define SQLITE_COPY                  0   /* No longer used */
2681
2682/*
2683** CAPI3REF: Tracing And Profiling Functions
2684**
2685** These routines register callback functions that can be used for
2686** tracing and profiling the execution of SQL statements.
2687**
2688** ^The callback function registered by sqlite3_trace() is invoked at
2689** various times when an SQL statement is being run by [sqlite3_step()].
2690** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2691** SQL statement text as the statement first begins executing.
2692** ^(Additional sqlite3_trace() callbacks might occur
2693** as each triggered subprogram is entered.  The callbacks for triggers
2694** contain a UTF-8 SQL comment that identifies the trigger.)^
2695**
2696** ^The callback function registered by sqlite3_profile() is invoked
2697** as each SQL statement finishes.  ^The profile callback contains
2698** the original statement text and an estimate of wall-clock time
2699** of how long that statement took to run.
2700*/
2701SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2702SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2703   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2704
2705/*
2706** CAPI3REF: Query Progress Callbacks
2707**
2708** ^This routine configures a callback function - the
2709** progress callback - that is invoked periodically during long
2710** running calls to [sqlite3_exec()], [sqlite3_step()] and
2711** [sqlite3_get_table()].  An example use for this
2712** interface is to keep a GUI updated during a large query.
2713**
2714** ^If the progress callback returns non-zero, the operation is
2715** interrupted.  This feature can be used to implement a
2716** "Cancel" button on a GUI progress dialog box.
2717**
2718** The progress handler must not do anything that will modify
2719** the database connection that invoked the progress handler.
2720** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2721** database connections for the meaning of "modify" in this paragraph.
2722**
2723*/
2724SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2725
2726/*
2727** CAPI3REF: Opening A New Database Connection
2728**
2729** ^These routines open an SQLite database file whose name is given by the
2730** filename argument. ^The filename argument is interpreted as UTF-8 for
2731** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2732** order for sqlite3_open16(). ^(A [database connection] handle is usually
2733** returned in *ppDb, even if an error occurs.  The only exception is that
2734** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2735** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2736** object.)^ ^(If the database is opened (and/or created) successfully, then
2737** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2738** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2739** an English language description of the error following a failure of any
2740** of the sqlite3_open() routines.
2741**
2742** ^The default encoding for the database will be UTF-8 if
2743** sqlite3_open() or sqlite3_open_v2() is called and
2744** UTF-16 in the native byte order if sqlite3_open16() is used.
2745**
2746** Whether or not an error occurs when it is opened, resources
2747** associated with the [database connection] handle should be released by
2748** passing it to [sqlite3_close()] when it is no longer required.
2749**
2750** The sqlite3_open_v2() interface works like sqlite3_open()
2751** except that it accepts two additional parameters for additional control
2752** over the new database connection.  ^(The flags parameter to
2753** sqlite3_open_v2() can take one of
2754** the following three values, optionally combined with the
2755** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2756** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2757**
2758** <dl>
2759** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2760** <dd>The database is opened in read-only mode.  If the database does not
2761** already exist, an error is returned.</dd>)^
2762**
2763** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2764** <dd>The database is opened for reading and writing if possible, or reading
2765** only if the file is write protected by the operating system.  In either
2766** case the database must already exist, otherwise an error is returned.</dd>)^
2767**
2768** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2769** <dd>The database is opened for reading and writing, and is creates it if
2770** it does not already exist. This is the behavior that is always used for
2771** sqlite3_open() and sqlite3_open16().</dd>)^
2772** </dl>
2773**
2774** If the 3rd parameter to sqlite3_open_v2() is not one of the
2775** combinations shown above or one of the combinations shown above combined
2776** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2777** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2778** then the behavior is undefined.
2779**
2780** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2781** opens in the multi-thread [threading mode] as long as the single-thread
2782** mode has not been set at compile-time or start-time.  ^If the
2783** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2784** in the serialized [threading mode] unless single-thread was
2785** previously selected at compile-time or start-time.
2786** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2787** eligible to use [shared cache mode], regardless of whether or not shared
2788** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2789** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2790** participate in [shared cache mode] even if it is enabled.
2791**
2792** ^If the filename is ":memory:", then a private, temporary in-memory database
2793** is created for the connection.  ^This in-memory database will vanish when
2794** the database connection is closed.  Future versions of SQLite might
2795** make use of additional special filenames that begin with the ":" character.
2796** It is recommended that when a database filename actually does begin with
2797** a ":" character you should prefix the filename with a pathname such as
2798** "./" to avoid ambiguity.
2799**
2800** ^If the filename is an empty string, then a private, temporary
2801** on-disk database will be created.  ^This private database will be
2802** automatically deleted as soon as the database connection is closed.
2803**
2804** ^The fourth parameter to sqlite3_open_v2() is the name of the
2805** [sqlite3_vfs] object that defines the operating system interface that
2806** the new database connection should use.  ^If the fourth parameter is
2807** a NULL pointer then the default [sqlite3_vfs] object is used.
2808**
2809** <b>Note to Windows users:</b>  The encoding used for the filename argument
2810** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2811** codepage is currently defined.  Filenames containing international
2812** characters must be converted to UTF-8 prior to passing them into
2813** sqlite3_open() or sqlite3_open_v2().
2814*/
2815SQLITE_API int sqlite3_open(
2816  const char *filename,   /* Database filename (UTF-8) */
2817  sqlite3 **ppDb          /* OUT: SQLite db handle */
2818);
2819SQLITE_API int sqlite3_open16(
2820  const void *filename,   /* Database filename (UTF-16) */
2821  sqlite3 **ppDb          /* OUT: SQLite db handle */
2822);
2823SQLITE_API int sqlite3_open_v2(
2824  const char *filename,   /* Database filename (UTF-8) */
2825  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2826  int flags,              /* Flags */
2827  const char *zVfs        /* Name of VFS module to use */
2828);
2829
2830/*
2831** CAPI3REF: Error Codes And Messages
2832**
2833** ^The sqlite3_errcode() interface returns the numeric [result code] or
2834** [extended result code] for the most recent failed sqlite3_* API call
2835** associated with a [database connection]. If a prior API call failed
2836** but the most recent API call succeeded, the return value from
2837** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2838** interface is the same except that it always returns the
2839** [extended result code] even when extended result codes are
2840** disabled.
2841**
2842** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2843** text that describes the error, as either UTF-8 or UTF-16 respectively.
2844** ^(Memory to hold the error message string is managed internally.
2845** The application does not need to worry about freeing the result.
2846** However, the error string might be overwritten or deallocated by
2847** subsequent calls to other SQLite interface functions.)^
2848**
2849** When the serialized [threading mode] is in use, it might be the
2850** case that a second error occurs on a separate thread in between
2851** the time of the first error and the call to these interfaces.
2852** When that happens, the second error will be reported since these
2853** interfaces always report the most recent result.  To avoid
2854** this, each thread can obtain exclusive use of the [database connection] D
2855** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2856** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2857** all calls to the interfaces listed here are completed.
2858**
2859** If an interface fails with SQLITE_MISUSE, that means the interface
2860** was invoked incorrectly by the application.  In that case, the
2861** error code and message may or may not be set.
2862*/
2863SQLITE_API int sqlite3_errcode(sqlite3 *db);
2864SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2865SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2866SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2867
2868/*
2869** CAPI3REF: SQL Statement Object
2870** KEYWORDS: {prepared statement} {prepared statements}
2871**
2872** An instance of this object represents a single SQL statement.
2873** This object is variously known as a "prepared statement" or a
2874** "compiled SQL statement" or simply as a "statement".
2875**
2876** The life of a statement object goes something like this:
2877**
2878** <ol>
2879** <li> Create the object using [sqlite3_prepare_v2()] or a related
2880**      function.
2881** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2882**      interfaces.
2883** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2884** <li> Reset the statement using [sqlite3_reset()] then go back
2885**      to step 2.  Do this zero or more times.
2886** <li> Destroy the object using [sqlite3_finalize()].
2887** </ol>
2888**
2889** Refer to documentation on individual methods above for additional
2890** information.
2891*/
2892typedef struct sqlite3_stmt sqlite3_stmt;
2893
2894/*
2895** CAPI3REF: Run-time Limits
2896**
2897** ^(This interface allows the size of various constructs to be limited
2898** on a connection by connection basis.  The first parameter is the
2899** [database connection] whose limit is to be set or queried.  The
2900** second parameter is one of the [limit categories] that define a
2901** class of constructs to be size limited.  The third parameter is the
2902** new limit for that construct.  The function returns the old limit.)^
2903**
2904** ^If the new limit is a negative number, the limit is unchanged.
2905** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2906** [limits | hard upper bound]
2907** set by a compile-time C preprocessor macro named
2908** [limits | SQLITE_MAX_XYZ].
2909** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2910** ^Attempts to increase a limit above its hard upper bound are
2911** silently truncated to the hard upper bound.
2912**
2913** Run-time limits are intended for use in applications that manage
2914** both their own internal database and also databases that are controlled
2915** by untrusted external sources.  An example application might be a
2916** web browser that has its own databases for storing history and
2917** separate databases controlled by JavaScript applications downloaded
2918** off the Internet.  The internal databases can be given the
2919** large, default limits.  Databases managed by external sources can
2920** be given much smaller limits designed to prevent a denial of service
2921** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2922** interface to further control untrusted SQL.  The size of the database
2923** created by an untrusted script can be contained using the
2924** [max_page_count] [PRAGMA].
2925**
2926** New run-time limit categories may be added in future releases.
2927*/
2928SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2929
2930/*
2931** CAPI3REF: Run-Time Limit Categories
2932** KEYWORDS: {limit category} {*limit categories}
2933**
2934** These constants define various performance limits
2935** that can be lowered at run-time using [sqlite3_limit()].
2936** The synopsis of the meanings of the various limits is shown below.
2937** Additional information is available at [limits | Limits in SQLite].
2938**
2939** <dl>
2940** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2941** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2942**
2943** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2944** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2945**
2946** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2947** <dd>The maximum number of columns in a table definition or in the
2948** result set of a [SELECT] or the maximum number of columns in an index
2949** or in an ORDER BY or GROUP BY clause.</dd>)^
2950**
2951** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2952** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2953**
2954** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2955** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2956**
2957** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2958** <dd>The maximum number of instructions in a virtual machine program
2959** used to implement an SQL statement.</dd>)^
2960**
2961** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2962** <dd>The maximum number of arguments on a function.</dd>)^
2963**
2964** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2965** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2966**
2967** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2968** <dd>The maximum length of the pattern argument to the [LIKE] or
2969** [GLOB] operators.</dd>)^
2970**
2971** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2972** <dd>The maximum number of variables in an SQL statement that can
2973** be bound.</dd>)^
2974**
2975** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2976** <dd>The maximum depth of recursion for triggers.</dd>)^
2977** </dl>
2978*/
2979#define SQLITE_LIMIT_LENGTH                    0
2980#define SQLITE_LIMIT_SQL_LENGTH                1
2981#define SQLITE_LIMIT_COLUMN                    2
2982#define SQLITE_LIMIT_EXPR_DEPTH                3
2983#define SQLITE_LIMIT_COMPOUND_SELECT           4
2984#define SQLITE_LIMIT_VDBE_OP                   5
2985#define SQLITE_LIMIT_FUNCTION_ARG              6
2986#define SQLITE_LIMIT_ATTACHED                  7
2987#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2988#define SQLITE_LIMIT_VARIABLE_NUMBER           9
2989#define SQLITE_LIMIT_TRIGGER_DEPTH            10
2990
2991/*
2992** CAPI3REF: Compiling An SQL Statement
2993** KEYWORDS: {SQL statement compiler}
2994**
2995** To execute an SQL query, it must first be compiled into a byte-code
2996** program using one of these routines.
2997**
2998** The first argument, "db", is a [database connection] obtained from a
2999** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3000** [sqlite3_open16()].  The database connection must not have been closed.
3001**
3002** The second argument, "zSql", is the statement to be compiled, encoded
3003** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3004** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3005** use UTF-16.
3006**
3007** ^If the nByte argument is less than zero, then zSql is read up to the
3008** first zero terminator. ^If nByte is non-negative, then it is the maximum
3009** number of  bytes read from zSql.  ^When nByte is non-negative, the
3010** zSql string ends at either the first '\000' or '\u0000' character or
3011** the nByte-th byte, whichever comes first. If the caller knows
3012** that the supplied string is nul-terminated, then there is a small
3013** performance advantage to be gained by passing an nByte parameter that
3014** is equal to the number of bytes in the input string <i>including</i>
3015** the nul-terminator bytes.
3016**
3017** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3018** past the end of the first SQL statement in zSql.  These routines only
3019** compile the first statement in zSql, so *pzTail is left pointing to
3020** what remains uncompiled.
3021**
3022** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3023** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3024** to NULL.  ^If the input text contains no SQL (if the input is an empty
3025** string or a comment) then *ppStmt is set to NULL.
3026** The calling procedure is responsible for deleting the compiled
3027** SQL statement using [sqlite3_finalize()] after it has finished with it.
3028** ppStmt may not be NULL.
3029**
3030** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3031** otherwise an [error code] is returned.
3032**
3033** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3034** recommended for all new programs. The two older interfaces are retained
3035** for backwards compatibility, but their use is discouraged.
3036** ^In the "v2" interfaces, the prepared statement
3037** that is returned (the [sqlite3_stmt] object) contains a copy of the
3038** original SQL text. This causes the [sqlite3_step()] interface to
3039** behave differently in three ways:
3040**
3041** <ol>
3042** <li>
3043** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3044** always used to do, [sqlite3_step()] will automatically recompile the SQL
3045** statement and try to run it again.  ^If the schema has changed in
3046** a way that makes the statement no longer valid, [sqlite3_step()] will still
3047** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3048** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3049** error go away.  Note: use [sqlite3_errmsg()] to find the text
3050** of the parsing error that results in an [SQLITE_SCHEMA] return.
3051** </li>
3052**
3053** <li>
3054** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3055** [error codes] or [extended error codes].  ^The legacy behavior was that
3056** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3057** and the application would have to make a second call to [sqlite3_reset()]
3058** in order to find the underlying cause of the problem. With the "v2" prepare
3059** interfaces, the underlying reason for the error is returned immediately.
3060** </li>
3061**
3062** <li>
3063** ^If the value of a [parameter | host parameter] in the WHERE clause might
3064** change the query plan for a statement, then the statement may be
3065** automatically recompiled (as if there had been a schema change) on the first
3066** [sqlite3_step()] call following any change to the
3067** [sqlite3_bind_text | bindings] of the [parameter].
3068** </li>
3069** </ol>
3070*/
3071SQLITE_API int sqlite3_prepare(
3072  sqlite3 *db,            /* Database handle */
3073  const char *zSql,       /* SQL statement, UTF-8 encoded */
3074  int nByte,              /* Maximum length of zSql in bytes. */
3075  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3076  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3077);
3078SQLITE_API int sqlite3_prepare_v2(
3079  sqlite3 *db,            /* Database handle */
3080  const char *zSql,       /* SQL statement, UTF-8 encoded */
3081  int nByte,              /* Maximum length of zSql in bytes. */
3082  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3083  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3084);
3085SQLITE_API int sqlite3_prepare16(
3086  sqlite3 *db,            /* Database handle */
3087  const void *zSql,       /* SQL statement, UTF-16 encoded */
3088  int nByte,              /* Maximum length of zSql in bytes. */
3089  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3090  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3091);
3092SQLITE_API int sqlite3_prepare16_v2(
3093  sqlite3 *db,            /* Database handle */
3094  const void *zSql,       /* SQL statement, UTF-16 encoded */
3095  int nByte,              /* Maximum length of zSql in bytes. */
3096  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3097  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3098);
3099
3100/*
3101** CAPI3REF: Retrieving Statement SQL
3102**
3103** ^This interface can be used to retrieve a saved copy of the original
3104** SQL text used to create a [prepared statement] if that statement was
3105** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3106*/
3107SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3108
3109/*
3110** CAPI3REF: Dynamically Typed Value Object
3111** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3112**
3113** SQLite uses the sqlite3_value object to represent all values
3114** that can be stored in a database table. SQLite uses dynamic typing
3115** for the values it stores.  ^Values stored in sqlite3_value objects
3116** can be integers, floating point values, strings, BLOBs, or NULL.
3117**
3118** An sqlite3_value object may be either "protected" or "unprotected".
3119** Some interfaces require a protected sqlite3_value.  Other interfaces
3120** will accept either a protected or an unprotected sqlite3_value.
3121** Every interface that accepts sqlite3_value arguments specifies
3122** whether or not it requires a protected sqlite3_value.
3123**
3124** The terms "protected" and "unprotected" refer to whether or not
3125** a mutex is held.  A internal mutex is held for a protected
3126** sqlite3_value object but no mutex is held for an unprotected
3127** sqlite3_value object.  If SQLite is compiled to be single-threaded
3128** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3129** or if SQLite is run in one of reduced mutex modes
3130** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3131** then there is no distinction between protected and unprotected
3132** sqlite3_value objects and they can be used interchangeably.  However,
3133** for maximum code portability it is recommended that applications
3134** still make the distinction between between protected and unprotected
3135** sqlite3_value objects even when not strictly required.
3136**
3137** ^The sqlite3_value objects that are passed as parameters into the
3138** implementation of [application-defined SQL functions] are protected.
3139** ^The sqlite3_value object returned by
3140** [sqlite3_column_value()] is unprotected.
3141** Unprotected sqlite3_value objects may only be used with
3142** [sqlite3_result_value()] and [sqlite3_bind_value()].
3143** The [sqlite3_value_blob | sqlite3_value_type()] family of
3144** interfaces require protected sqlite3_value objects.
3145*/
3146typedef struct Mem sqlite3_value;
3147
3148/*
3149** CAPI3REF: SQL Function Context Object
3150**
3151** The context in which an SQL function executes is stored in an
3152** sqlite3_context object.  ^A pointer to an sqlite3_context object
3153** is always first parameter to [application-defined SQL functions].
3154** The application-defined SQL function implementation will pass this
3155** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3156** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3157** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3158** and/or [sqlite3_set_auxdata()].
3159*/
3160typedef struct sqlite3_context sqlite3_context;
3161
3162/*
3163** CAPI3REF: Binding Values To Prepared Statements
3164** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3165** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3166**
3167** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3168** literals may be replaced by a [parameter] that matches one of following
3169** templates:
3170**
3171** <ul>
3172** <li>  ?
3173** <li>  ?NNN
3174** <li>  :VVV
3175** <li>  @VVV
3176** <li>  $VVV
3177** </ul>
3178**
3179** In the templates above, NNN represents an integer literal,
3180** and VVV represents an alphanumeric identifer.)^  ^The values of these
3181** parameters (also called "host parameter names" or "SQL parameters")
3182** can be set using the sqlite3_bind_*() routines defined here.
3183**
3184** ^The first argument to the sqlite3_bind_*() routines is always
3185** a pointer to the [sqlite3_stmt] object returned from
3186** [sqlite3_prepare_v2()] or its variants.
3187**
3188** ^The second argument is the index of the SQL parameter to be set.
3189** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3190** SQL parameter is used more than once, second and subsequent
3191** occurrences have the same index as the first occurrence.
3192** ^The index for named parameters can be looked up using the
3193** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3194** for "?NNN" parameters is the value of NNN.
3195** ^The NNN value must be between 1 and the [sqlite3_limit()]
3196** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3197**
3198** ^The third argument is the value to bind to the parameter.
3199**
3200** ^(In those routines that have a fourth argument, its value is the
3201** number of bytes in the parameter.  To be clear: the value is the
3202** number of <u>bytes</u> in the value, not the number of characters.)^
3203** ^If the fourth parameter is negative, the length of the string is
3204** the number of bytes up to the first zero terminator.
3205**
3206** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3207** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3208** string after SQLite has finished with it. ^If the fifth argument is
3209** the special value [SQLITE_STATIC], then SQLite assumes that the
3210** information is in static, unmanaged space and does not need to be freed.
3211** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3212** SQLite makes its own private copy of the data immediately, before
3213** the sqlite3_bind_*() routine returns.
3214**
3215** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3216** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3217** (just an integer to hold its size) while it is being processed.
3218** Zeroblobs are intended to serve as placeholders for BLOBs whose
3219** content is later written using
3220** [sqlite3_blob_open | incremental BLOB I/O] routines.
3221** ^A negative value for the zeroblob results in a zero-length BLOB.
3222**
3223** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3224** for the [prepared statement] or with a prepared statement for which
3225** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3226** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3227** routine is passed a [prepared statement] that has been finalized, the
3228** result is undefined and probably harmful.
3229**
3230** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3231** ^Unbound parameters are interpreted as NULL.
3232**
3233** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3234** [error code] if anything goes wrong.
3235** ^[SQLITE_RANGE] is returned if the parameter
3236** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3237**
3238** See also: [sqlite3_bind_parameter_count()],
3239** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3240*/
3241SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3242SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3243SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3244SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3245SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3246SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3247SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3248SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3249SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3250
3251/*
3252** CAPI3REF: Number Of SQL Parameters
3253**
3254** ^This routine can be used to find the number of [SQL parameters]
3255** in a [prepared statement].  SQL parameters are tokens of the
3256** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3257** placeholders for values that are [sqlite3_bind_blob | bound]
3258** to the parameters at a later time.
3259**
3260** ^(This routine actually returns the index of the largest (rightmost)
3261** parameter. For all forms except ?NNN, this will correspond to the
3262** number of unique parameters.  If parameters of the ?NNN form are used,
3263** there may be gaps in the list.)^
3264**
3265** See also: [sqlite3_bind_blob|sqlite3_bind()],
3266** [sqlite3_bind_parameter_name()], and
3267** [sqlite3_bind_parameter_index()].
3268*/
3269SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3270
3271/*
3272** CAPI3REF: Name Of A Host Parameter
3273**
3274** ^The sqlite3_bind_parameter_name(P,N) interface returns
3275** the name of the N-th [SQL parameter] in the [prepared statement] P.
3276** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3277** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3278** respectively.
3279** In other words, the initial ":" or "$" or "@" or "?"
3280** is included as part of the name.)^
3281** ^Parameters of the form "?" without a following integer have no name
3282** and are referred to as "nameless" or "anonymous parameters".
3283**
3284** ^The first host parameter has an index of 1, not 0.
3285**
3286** ^If the value N is out of range or if the N-th parameter is
3287** nameless, then NULL is returned.  ^The returned string is
3288** always in UTF-8 encoding even if the named parameter was
3289** originally specified as UTF-16 in [sqlite3_prepare16()] or
3290** [sqlite3_prepare16_v2()].
3291**
3292** See also: [sqlite3_bind_blob|sqlite3_bind()],
3293** [sqlite3_bind_parameter_count()], and
3294** [sqlite3_bind_parameter_index()].
3295*/
3296SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3297
3298/*
3299** CAPI3REF: Index Of A Parameter With A Given Name
3300**
3301** ^Return the index of an SQL parameter given its name.  ^The
3302** index value returned is suitable for use as the second
3303** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3304** is returned if no matching parameter is found.  ^The parameter
3305** name must be given in UTF-8 even if the original statement
3306** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3307**
3308** See also: [sqlite3_bind_blob|sqlite3_bind()],
3309** [sqlite3_bind_parameter_count()], and
3310** [sqlite3_bind_parameter_index()].
3311*/
3312SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3313
3314/*
3315** CAPI3REF: Reset All Bindings On A Prepared Statement
3316**
3317** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3318** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3319** ^Use this routine to reset all host parameters to NULL.
3320*/
3321SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3322
3323/*
3324** CAPI3REF: Number Of Columns In A Result Set
3325**
3326** ^Return the number of columns in the result set returned by the
3327** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3328** statement that does not return data (for example an [UPDATE]).
3329*/
3330SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3331
3332/*
3333** CAPI3REF: Column Names In A Result Set
3334**
3335** ^These routines return the name assigned to a particular column
3336** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3337** interface returns a pointer to a zero-terminated UTF-8 string
3338** and sqlite3_column_name16() returns a pointer to a zero-terminated
3339** UTF-16 string.  ^The first parameter is the [prepared statement]
3340** that implements the [SELECT] statement. ^The second parameter is the
3341** column number.  ^The leftmost column is number 0.
3342**
3343** ^The returned string pointer is valid until either the [prepared statement]
3344** is destroyed by [sqlite3_finalize()] or until the next call to
3345** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3346**
3347** ^If sqlite3_malloc() fails during the processing of either routine
3348** (for example during a conversion from UTF-8 to UTF-16) then a
3349** NULL pointer is returned.
3350**
3351** ^The name of a result column is the value of the "AS" clause for
3352** that column, if there is an AS clause.  If there is no AS clause
3353** then the name of the column is unspecified and may change from
3354** one release of SQLite to the next.
3355*/
3356SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3357SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3358
3359/*
3360** CAPI3REF: Source Of Data In A Query Result
3361**
3362** ^These routines provide a means to determine the database, table, and
3363** table column that is the origin of a particular result column in
3364** [SELECT] statement.
3365** ^The name of the database or table or column can be returned as
3366** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3367** the database name, the _table_ routines return the table name, and
3368** the origin_ routines return the column name.
3369** ^The returned string is valid until the [prepared statement] is destroyed
3370** using [sqlite3_finalize()] or until the same information is requested
3371** again in a different encoding.
3372**
3373** ^The names returned are the original un-aliased names of the
3374** database, table, and column.
3375**
3376** ^The first argument to these interfaces is a [prepared statement].
3377** ^These functions return information about the Nth result column returned by
3378** the statement, where N is the second function argument.
3379** ^The left-most column is column 0 for these routines.
3380**
3381** ^If the Nth column returned by the statement is an expression or
3382** subquery and is not a column value, then all of these functions return
3383** NULL.  ^These routine might also return NULL if a memory allocation error
3384** occurs.  ^Otherwise, they return the name of the attached database, table,
3385** or column that query result column was extracted from.
3386**
3387** ^As with all other SQLite APIs, those whose names end with "16" return
3388** UTF-16 encoded strings and the other functions return UTF-8.
3389**
3390** ^These APIs are only available if the library was compiled with the
3391** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3392**
3393** If two or more threads call one or more of these routines against the same
3394** prepared statement and column at the same time then the results are
3395** undefined.
3396**
3397** If two or more threads call one or more
3398** [sqlite3_column_database_name | column metadata interfaces]
3399** for the same [prepared statement] and result column
3400** at the same time then the results are undefined.
3401*/
3402SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3403SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3404SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3405SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3406SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3407SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3408
3409/*
3410** CAPI3REF: Declared Datatype Of A Query Result
3411**
3412** ^(The first parameter is a [prepared statement].
3413** If this statement is a [SELECT] statement and the Nth column of the
3414** returned result set of that [SELECT] is a table column (not an
3415** expression or subquery) then the declared type of the table
3416** column is returned.)^  ^If the Nth column of the result set is an
3417** expression or subquery, then a NULL pointer is returned.
3418** ^The returned string is always UTF-8 encoded.
3419**
3420** ^(For example, given the database schema:
3421**
3422** CREATE TABLE t1(c1 VARIANT);
3423**
3424** and the following statement to be compiled:
3425**
3426** SELECT c1 + 1, c1 FROM t1;
3427**
3428** this routine would return the string "VARIANT" for the second result
3429** column (i==1), and a NULL pointer for the first result column (i==0).)^
3430**
3431** ^SQLite uses dynamic run-time typing.  ^So just because a column
3432** is declared to contain a particular type does not mean that the
3433** data stored in that column is of the declared type.  SQLite is
3434** strongly typed, but the typing is dynamic not static.  ^Type
3435** is associated with individual values, not with the containers
3436** used to hold those values.
3437*/
3438SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3439SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3440
3441/*
3442** CAPI3REF: Evaluate An SQL Statement
3443**
3444** After a [prepared statement] has been prepared using either
3445** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3446** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3447** must be called one or more times to evaluate the statement.
3448**
3449** The details of the behavior of the sqlite3_step() interface depend
3450** on whether the statement was prepared using the newer "v2" interface
3451** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3452** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3453** new "v2" interface is recommended for new applications but the legacy
3454** interface will continue to be supported.
3455**
3456** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3457** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3458** ^With the "v2" interface, any of the other [result codes] or
3459** [extended result codes] might be returned as well.
3460**
3461** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3462** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3463** or occurs outside of an explicit transaction, then you can retry the
3464** statement.  If the statement is not a [COMMIT] and occurs within a
3465** explicit transaction then you should rollback the transaction before
3466** continuing.
3467**
3468** ^[SQLITE_DONE] means that the statement has finished executing
3469** successfully.  sqlite3_step() should not be called again on this virtual
3470** machine without first calling [sqlite3_reset()] to reset the virtual
3471** machine back to its initial state.
3472**
3473** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3474** is returned each time a new row of data is ready for processing by the
3475** caller. The values may be accessed using the [column access functions].
3476** sqlite3_step() is called again to retrieve the next row of data.
3477**
3478** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3479** violation) has occurred.  sqlite3_step() should not be called again on
3480** the VM. More information may be found by calling [sqlite3_errmsg()].
3481** ^With the legacy interface, a more specific error code (for example,
3482** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3483** can be obtained by calling [sqlite3_reset()] on the
3484** [prepared statement].  ^In the "v2" interface,
3485** the more specific error code is returned directly by sqlite3_step().
3486**
3487** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3488** Perhaps it was called on a [prepared statement] that has
3489** already been [sqlite3_finalize | finalized] or on one that had
3490** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3491** be the case that the same database connection is being used by two or
3492** more threads at the same moment in time.
3493**
3494** For all versions of SQLite up to and including 3.6.23.1, it was required
3495** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3496** [sqlite3_reset()] be called before any subsequent invocation of
3497** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3498** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3499** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()]
3500** automatically in this circumstance rather than returning [SQLITE_MISUSE].
3501**
3502** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3503** API always returns a generic error code, [SQLITE_ERROR], following any
3504** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3505** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3506** specific [error codes] that better describes the error.
3507** We admit that this is a goofy design.  The problem has been fixed
3508** with the "v2" interface.  If you prepare all of your SQL statements
3509** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3510** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3511** then the more specific [error codes] are returned directly
3512** by sqlite3_step().  The use of the "v2" interface is recommended.
3513*/
3514SQLITE_API int sqlite3_step(sqlite3_stmt*);
3515
3516/*
3517** CAPI3REF: Number of columns in a result set
3518**
3519** ^The sqlite3_data_count(P) the number of columns in the
3520** of the result set of [prepared statement] P.
3521*/
3522SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3523
3524/*
3525** CAPI3REF: Fundamental Datatypes
3526** KEYWORDS: SQLITE_TEXT
3527**
3528** ^(Every value in SQLite has one of five fundamental datatypes:
3529**
3530** <ul>
3531** <li> 64-bit signed integer
3532** <li> 64-bit IEEE floating point number
3533** <li> string
3534** <li> BLOB
3535** <li> NULL
3536** </ul>)^
3537**
3538** These constants are codes for each of those types.
3539**
3540** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3541** for a completely different meaning.  Software that links against both
3542** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3543** SQLITE_TEXT.
3544*/
3545#define SQLITE_INTEGER  1
3546#define SQLITE_FLOAT    2
3547#define SQLITE_BLOB     4
3548#define SQLITE_NULL     5
3549#ifdef SQLITE_TEXT
3550# undef SQLITE_TEXT
3551#else
3552# define SQLITE_TEXT     3
3553#endif
3554#define SQLITE3_TEXT     3
3555
3556/*
3557** CAPI3REF: Result Values From A Query
3558** KEYWORDS: {column access functions}
3559**
3560** These routines form the "result set" interface.
3561**
3562** ^These routines return information about a single column of the current
3563** result row of a query.  ^In every case the first argument is a pointer
3564** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3565** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3566** and the second argument is the index of the column for which information
3567** should be returned. ^The leftmost column of the result set has the index 0.
3568** ^The number of columns in the result can be determined using
3569** [sqlite3_column_count()].
3570**
3571** If the SQL statement does not currently point to a valid row, or if the
3572** column index is out of range, the result is undefined.
3573** These routines may only be called when the most recent call to
3574** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3575** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3576** If any of these routines are called after [sqlite3_reset()] or
3577** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3578** something other than [SQLITE_ROW], the results are undefined.
3579** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3580** are called from a different thread while any of these routines
3581** are pending, then the results are undefined.
3582**
3583** ^The sqlite3_column_type() routine returns the
3584** [SQLITE_INTEGER | datatype code] for the initial data type
3585** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3586** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3587** returned by sqlite3_column_type() is only meaningful if no type
3588** conversions have occurred as described below.  After a type conversion,
3589** the value returned by sqlite3_column_type() is undefined.  Future
3590** versions of SQLite may change the behavior of sqlite3_column_type()
3591** following a type conversion.
3592**
3593** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3594** routine returns the number of bytes in that BLOB or string.
3595** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3596** the string to UTF-8 and then returns the number of bytes.
3597** ^If the result is a numeric value then sqlite3_column_bytes() uses
3598** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3599** the number of bytes in that string.
3600** ^The value returned does not include the zero terminator at the end
3601** of the string.  ^For clarity: the value returned is the number of
3602** bytes in the string, not the number of characters.
3603**
3604** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3605** even empty strings, are always zero terminated.  ^The return
3606** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3607** pointer, possibly even a NULL pointer.
3608**
3609** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3610** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3611** ^The zero terminator is not included in this count.
3612**
3613** ^The object returned by [sqlite3_column_value()] is an
3614** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3615** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3616** If the [unprotected sqlite3_value] object returned by
3617** [sqlite3_column_value()] is used in any other way, including calls
3618** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3619** or [sqlite3_value_bytes()], then the behavior is undefined.
3620**
3621** These routines attempt to convert the value where appropriate.  ^For
3622** example, if the internal representation is FLOAT and a text result
3623** is requested, [sqlite3_snprintf()] is used internally to perform the
3624** conversion automatically.  ^(The following table details the conversions
3625** that are applied:
3626**
3627** <blockquote>
3628** <table border="1">
3629** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3630**
3631** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3632** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3633** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3634** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3635** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3636** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3637** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3638** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3639** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3640** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3641** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3642** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3643** <tr><td>  TEXT    <td>   BLOB    <td> No change
3644** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3645** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3646** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3647** </table>
3648** </blockquote>)^
3649**
3650** The table above makes reference to standard C library functions atoi()
3651** and atof().  SQLite does not really use these functions.  It has its
3652** own equivalent internal routines.  The atoi() and atof() names are
3653** used in the table for brevity and because they are familiar to most
3654** C programmers.
3655**
3656** ^Note that when type conversions occur, pointers returned by prior
3657** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3658** sqlite3_column_text16() may be invalidated.
3659** ^(Type conversions and pointer invalidations might occur
3660** in the following cases:
3661**
3662** <ul>
3663** <li> The initial content is a BLOB and sqlite3_column_text() or
3664**      sqlite3_column_text16() is called.  A zero-terminator might
3665**      need to be added to the string.</li>
3666** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3667**      sqlite3_column_text16() is called.  The content must be converted
3668**      to UTF-16.</li>
3669** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3670**      sqlite3_column_text() is called.  The content must be converted
3671**      to UTF-8.</li>
3672** </ul>)^
3673**
3674** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3675** not invalidate a prior pointer, though of course the content of the buffer
3676** that the prior pointer points to will have been modified.  Other kinds
3677** of conversion are done in place when it is possible, but sometimes they
3678** are not possible and in those cases prior pointers are invalidated.
3679**
3680** ^(The safest and easiest to remember policy is to invoke these routines
3681** in one of the following ways:
3682**
3683** <ul>
3684**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3685**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3686**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3687** </ul>)^
3688**
3689** In other words, you should call sqlite3_column_text(),
3690** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3691** into the desired format, then invoke sqlite3_column_bytes() or
3692** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3693** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3694** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3695** with calls to sqlite3_column_bytes().
3696**
3697** ^The pointers returned are valid until a type conversion occurs as
3698** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3699** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3700** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3701** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3702** [sqlite3_free()].
3703**
3704** ^(If a memory allocation error occurs during the evaluation of any
3705** of these routines, a default value is returned.  The default value
3706** is either the integer 0, the floating point number 0.0, or a NULL
3707** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3708** [SQLITE_NOMEM].)^
3709*/
3710SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3711SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3712SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3713SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3714SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3715SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3716SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3717SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3718SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3719SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3720
3721/*
3722** CAPI3REF: Destroy A Prepared Statement Object
3723**
3724** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3725** ^If the statement was executed successfully or not executed at all, then
3726** SQLITE_OK is returned. ^If execution of the statement failed then an
3727** [error code] or [extended error code] is returned.
3728**
3729** ^This routine can be called at any point during the execution of the
3730** [prepared statement].  ^If the virtual machine has not
3731** completed execution when this routine is called, that is like
3732** encountering an error or an [sqlite3_interrupt | interrupt].
3733** ^Incomplete updates may be rolled back and transactions canceled,
3734** depending on the circumstances, and the
3735** [error code] returned will be [SQLITE_ABORT].
3736*/
3737SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3738
3739/*
3740** CAPI3REF: Reset A Prepared Statement Object
3741**
3742** The sqlite3_reset() function is called to reset a [prepared statement]
3743** object back to its initial state, ready to be re-executed.
3744** ^Any SQL statement variables that had values bound to them using
3745** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3746** Use [sqlite3_clear_bindings()] to reset the bindings.
3747**
3748** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3749** back to the beginning of its program.
3750**
3751** ^If the most recent call to [sqlite3_step(S)] for the
3752** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3753** or if [sqlite3_step(S)] has never before been called on S,
3754** then [sqlite3_reset(S)] returns [SQLITE_OK].
3755**
3756** ^If the most recent call to [sqlite3_step(S)] for the
3757** [prepared statement] S indicated an error, then
3758** [sqlite3_reset(S)] returns an appropriate [error code].
3759**
3760** ^The [sqlite3_reset(S)] interface does not change the values
3761** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3762*/
3763SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3764
3765/*
3766** CAPI3REF: Create Or Redefine SQL Functions
3767** KEYWORDS: {function creation routines}
3768** KEYWORDS: {application-defined SQL function}
3769** KEYWORDS: {application-defined SQL functions}
3770**
3771** ^These two functions (collectively known as "function creation routines")
3772** are used to add SQL functions or aggregates or to redefine the behavior
3773** of existing SQL functions or aggregates.  The only difference between the
3774** two is that the second parameter, the name of the (scalar) function or
3775** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3776** for sqlite3_create_function16().
3777**
3778** ^The first parameter is the [database connection] to which the SQL
3779** function is to be added.  ^If an application uses more than one database
3780** connection then application-defined SQL functions must be added
3781** to each database connection separately.
3782**
3783** The second parameter is the name of the SQL function to be created or
3784** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3785** the zero-terminator.  Note that the name length limit is in bytes, not
3786** characters.  ^Any attempt to create a function with a longer name
3787** will result in [SQLITE_ERROR] being returned.
3788**
3789** ^The third parameter (nArg)
3790** is the number of arguments that the SQL function or
3791** aggregate takes. ^If this parameter is -1, then the SQL function or
3792** aggregate may take any number of arguments between 0 and the limit
3793** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3794** parameter is less than -1 or greater than 127 then the behavior is
3795** undefined.
3796**
3797** The fourth parameter, eTextRep, specifies what
3798** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3799** its parameters.  Any SQL function implementation should be able to work
3800** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3801** more efficient with one encoding than another.  ^An application may
3802** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3803** times with the same function but with different values of eTextRep.
3804** ^When multiple implementations of the same function are available, SQLite
3805** will pick the one that involves the least amount of data conversion.
3806** If there is only a single implementation which does not care what text
3807** encoding is used, then the fourth argument should be [SQLITE_ANY].
3808**
3809** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3810** function can gain access to this pointer using [sqlite3_user_data()].)^
3811**
3812** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3813** pointers to C-language functions that implement the SQL function or
3814** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3815** callback only; NULL pointers should be passed as the xStep and xFinal
3816** parameters. ^An aggregate SQL function requires an implementation of xStep
3817** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3818** SQL function or aggregate, pass NULL for all three function callbacks.
3819**
3820** ^It is permitted to register multiple implementations of the same
3821** functions with the same name but with either differing numbers of
3822** arguments or differing preferred text encodings.  ^SQLite will use
3823** the implementation that most closely matches the way in which the
3824** SQL function is used.  ^A function implementation with a non-negative
3825** nArg parameter is a better match than a function implementation with
3826** a negative nArg.  ^A function where the preferred text encoding
3827** matches the database encoding is a better
3828** match than a function where the encoding is different.
3829** ^A function where the encoding difference is between UTF16le and UTF16be
3830** is a closer match than a function where the encoding difference is
3831** between UTF8 and UTF16.
3832**
3833** ^Built-in functions may be overloaded by new application-defined functions.
3834** ^The first application-defined function with a given name overrides all
3835** built-in functions in the same [database connection] with the same name.
3836** ^Subsequent application-defined functions of the same name only override
3837** prior application-defined functions that are an exact match for the
3838** number of parameters and preferred encoding.
3839**
3840** ^An application-defined function is permitted to call other
3841** SQLite interfaces.  However, such calls must not
3842** close the database connection nor finalize or reset the prepared
3843** statement in which the function is running.
3844*/
3845SQLITE_API int sqlite3_create_function(
3846  sqlite3 *db,
3847  const char *zFunctionName,
3848  int nArg,
3849  int eTextRep,
3850  void *pApp,
3851  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3852  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3853  void (*xFinal)(sqlite3_context*)
3854);
3855SQLITE_API int sqlite3_create_function16(
3856  sqlite3 *db,
3857  const void *zFunctionName,
3858  int nArg,
3859  int eTextRep,
3860  void *pApp,
3861  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3862  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3863  void (*xFinal)(sqlite3_context*)
3864);
3865
3866/*
3867** CAPI3REF: Text Encodings
3868**
3869** These constant define integer codes that represent the various
3870** text encodings supported by SQLite.
3871*/
3872#define SQLITE_UTF8           1
3873#define SQLITE_UTF16LE        2
3874#define SQLITE_UTF16BE        3
3875#define SQLITE_UTF16          4    /* Use native byte order */
3876#define SQLITE_ANY            5    /* sqlite3_create_function only */
3877#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3878
3879/*
3880** CAPI3REF: Deprecated Functions
3881** DEPRECATED
3882**
3883** These functions are [deprecated].  In order to maintain
3884** backwards compatibility with older code, these functions continue
3885** to be supported.  However, new applications should avoid
3886** the use of these functions.  To help encourage people to avoid
3887** using these functions, we are not going to tell you what they do.
3888*/
3889#ifndef SQLITE_OMIT_DEPRECATED
3890SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3891SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3892SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3893SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3894SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3895SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3896#endif
3897
3898/*
3899** CAPI3REF: Obtaining SQL Function Parameter Values
3900**
3901** The C-language implementation of SQL functions and aggregates uses
3902** this set of interface routines to access the parameter values on
3903** the function or aggregate.
3904**
3905** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3906** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3907** define callbacks that implement the SQL functions and aggregates.
3908** The 4th parameter to these callbacks is an array of pointers to
3909** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3910** each parameter to the SQL function.  These routines are used to
3911** extract values from the [sqlite3_value] objects.
3912**
3913** These routines work only with [protected sqlite3_value] objects.
3914** Any attempt to use these routines on an [unprotected sqlite3_value]
3915** object results in undefined behavior.
3916**
3917** ^These routines work just like the corresponding [column access functions]
3918** except that  these routines take a single [protected sqlite3_value] object
3919** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3920**
3921** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3922** in the native byte-order of the host machine.  ^The
3923** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3924** extract UTF-16 strings as big-endian and little-endian respectively.
3925**
3926** ^(The sqlite3_value_numeric_type() interface attempts to apply
3927** numeric affinity to the value.  This means that an attempt is
3928** made to convert the value to an integer or floating point.  If
3929** such a conversion is possible without loss of information (in other
3930** words, if the value is a string that looks like a number)
3931** then the conversion is performed.  Otherwise no conversion occurs.
3932** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3933**
3934** Please pay particular attention to the fact that the pointer returned
3935** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3936** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3937** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3938** or [sqlite3_value_text16()].
3939**
3940** These routines must be called from the same thread as
3941** the SQL function that supplied the [sqlite3_value*] parameters.
3942*/
3943SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3944SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3945SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3946SQLITE_API double sqlite3_value_double(sqlite3_value*);
3947SQLITE_API int sqlite3_value_int(sqlite3_value*);
3948SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3949SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3950SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3951SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3952SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3953SQLITE_API int sqlite3_value_type(sqlite3_value*);
3954SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3955
3956/*
3957** CAPI3REF: Obtain Aggregate Function Context
3958**
3959** Implementions of aggregate SQL functions use this
3960** routine to allocate memory for storing their state.
3961**
3962** ^The first time the sqlite3_aggregate_context(C,N) routine is called
3963** for a particular aggregate function, SQLite
3964** allocates N of memory, zeroes out that memory, and returns a pointer
3965** to the new memory. ^On second and subsequent calls to
3966** sqlite3_aggregate_context() for the same aggregate function instance,
3967** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3968** called once for each invocation of the xStep callback and then one
3969** last time when the xFinal callback is invoked.  ^(When no rows match
3970** an aggregate query, the xStep() callback of the aggregate function
3971** implementation is never called and xFinal() is called exactly once.
3972** In those cases, sqlite3_aggregate_context() might be called for the
3973** first time from within xFinal().)^
3974**
3975** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3976** less than or equal to zero or if a memory allocate error occurs.
3977**
3978** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3979** determined by the N parameter on first successful call.  Changing the
3980** value of N in subsequent call to sqlite3_aggregate_context() within
3981** the same aggregate function instance will not resize the memory
3982** allocation.)^
3983**
3984** ^SQLite automatically frees the memory allocated by
3985** sqlite3_aggregate_context() when the aggregate query concludes.
3986**
3987** The first parameter must be a copy of the
3988** [sqlite3_context | SQL function context] that is the first parameter
3989** to the xStep or xFinal callback routine that implements the aggregate
3990** function.
3991**
3992** This routine must be called from the same thread in which
3993** the aggregate SQL function is running.
3994*/
3995SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3996
3997/*
3998** CAPI3REF: User Data For Functions
3999**
4000** ^The sqlite3_user_data() interface returns a copy of
4001** the pointer that was the pUserData parameter (the 5th parameter)
4002** of the [sqlite3_create_function()]
4003** and [sqlite3_create_function16()] routines that originally
4004** registered the application defined function.
4005**
4006** This routine must be called from the same thread in which
4007** the application-defined function is running.
4008*/
4009SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4010
4011/*
4012** CAPI3REF: Database Connection For Functions
4013**
4014** ^The sqlite3_context_db_handle() interface returns a copy of
4015** the pointer to the [database connection] (the 1st parameter)
4016** of the [sqlite3_create_function()]
4017** and [sqlite3_create_function16()] routines that originally
4018** registered the application defined function.
4019*/
4020SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4021
4022/*
4023** CAPI3REF: Function Auxiliary Data
4024**
4025** The following two functions may be used by scalar SQL functions to
4026** associate metadata with argument values. If the same value is passed to
4027** multiple invocations of the same SQL function during query execution, under
4028** some circumstances the associated metadata may be preserved. This may
4029** be used, for example, to add a regular-expression matching scalar
4030** function. The compiled version of the regular expression is stored as
4031** metadata associated with the SQL value passed as the regular expression
4032** pattern.  The compiled regular expression can be reused on multiple
4033** invocations of the same function so that the original pattern string
4034** does not need to be recompiled on each invocation.
4035**
4036** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4037** associated by the sqlite3_set_auxdata() function with the Nth argument
4038** value to the application-defined function. ^If no metadata has been ever
4039** been set for the Nth argument of the function, or if the corresponding
4040** function parameter has changed since the meta-data was set,
4041** then sqlite3_get_auxdata() returns a NULL pointer.
4042**
4043** ^The sqlite3_set_auxdata() interface saves the metadata
4044** pointed to by its 3rd parameter as the metadata for the N-th
4045** argument of the application-defined function.  Subsequent
4046** calls to sqlite3_get_auxdata() might return this data, if it has
4047** not been destroyed.
4048** ^If it is not NULL, SQLite will invoke the destructor
4049** function given by the 4th parameter to sqlite3_set_auxdata() on
4050** the metadata when the corresponding function parameter changes
4051** or when the SQL statement completes, whichever comes first.
4052**
4053** SQLite is free to call the destructor and drop metadata on any
4054** parameter of any function at any time.  ^The only guarantee is that
4055** the destructor will be called before the metadata is dropped.
4056**
4057** ^(In practice, metadata is preserved between function calls for
4058** expressions that are constant at compile time. This includes literal
4059** values and [parameters].)^
4060**
4061** These routines must be called from the same thread in which
4062** the SQL function is running.
4063*/
4064SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4065SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4066
4067
4068/*
4069** CAPI3REF: Constants Defining Special Destructor Behavior
4070**
4071** These are special values for the destructor that is passed in as the
4072** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4073** argument is SQLITE_STATIC, it means that the content pointer is constant
4074** and will never change.  It does not need to be destroyed.  ^The
4075** SQLITE_TRANSIENT value means that the content will likely change in
4076** the near future and that SQLite should make its own private copy of
4077** the content before returning.
4078**
4079** The typedef is necessary to work around problems in certain
4080** C++ compilers.  See ticket #2191.
4081*/
4082typedef void (*sqlite3_destructor_type)(void*);
4083#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4084#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4085
4086/*
4087** CAPI3REF: Setting The Result Of An SQL Function
4088**
4089** These routines are used by the xFunc or xFinal callbacks that
4090** implement SQL functions and aggregates.  See
4091** [sqlite3_create_function()] and [sqlite3_create_function16()]
4092** for additional information.
4093**
4094** These functions work very much like the [parameter binding] family of
4095** functions used to bind values to host parameters in prepared statements.
4096** Refer to the [SQL parameter] documentation for additional information.
4097**
4098** ^The sqlite3_result_blob() interface sets the result from
4099** an application-defined function to be the BLOB whose content is pointed
4100** to by the second parameter and which is N bytes long where N is the
4101** third parameter.
4102**
4103** ^The sqlite3_result_zeroblob() interfaces set the result of
4104** the application-defined function to be a BLOB containing all zero
4105** bytes and N bytes in size, where N is the value of the 2nd parameter.
4106**
4107** ^The sqlite3_result_double() interface sets the result from
4108** an application-defined function to be a floating point value specified
4109** by its 2nd argument.
4110**
4111** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4112** cause the implemented SQL function to throw an exception.
4113** ^SQLite uses the string pointed to by the
4114** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4115** as the text of an error message.  ^SQLite interprets the error
4116** message string from sqlite3_result_error() as UTF-8. ^SQLite
4117** interprets the string from sqlite3_result_error16() as UTF-16 in native
4118** byte order.  ^If the third parameter to sqlite3_result_error()
4119** or sqlite3_result_error16() is negative then SQLite takes as the error
4120** message all text up through the first zero character.
4121** ^If the third parameter to sqlite3_result_error() or
4122** sqlite3_result_error16() is non-negative then SQLite takes that many
4123** bytes (not characters) from the 2nd parameter as the error message.
4124** ^The sqlite3_result_error() and sqlite3_result_error16()
4125** routines make a private copy of the error message text before
4126** they return.  Hence, the calling function can deallocate or
4127** modify the text after they return without harm.
4128** ^The sqlite3_result_error_code() function changes the error code
4129** returned by SQLite as a result of an error in a function.  ^By default,
4130** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4131** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4132**
4133** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4134** indicating that a string or BLOB is too long to represent.
4135**
4136** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4137** indicating that a memory allocation failed.
4138**
4139** ^The sqlite3_result_int() interface sets the return value
4140** of the application-defined function to be the 32-bit signed integer
4141** value given in the 2nd argument.
4142** ^The sqlite3_result_int64() interface sets the return value
4143** of the application-defined function to be the 64-bit signed integer
4144** value given in the 2nd argument.
4145**
4146** ^The sqlite3_result_null() interface sets the return value
4147** of the application-defined function to be NULL.
4148**
4149** ^The sqlite3_result_text(), sqlite3_result_text16(),
4150** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4151** set the return value of the application-defined function to be
4152** a text string which is represented as UTF-8, UTF-16 native byte order,
4153** UTF-16 little endian, or UTF-16 big endian, respectively.
4154** ^SQLite takes the text result from the application from
4155** the 2nd parameter of the sqlite3_result_text* interfaces.
4156** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4157** is negative, then SQLite takes result text from the 2nd parameter
4158** through the first zero character.
4159** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4160** is non-negative, then as many bytes (not characters) of the text
4161** pointed to by the 2nd parameter are taken as the application-defined
4162** function result.
4163** ^If the 4th parameter to the sqlite3_result_text* interfaces
4164** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4165** function as the destructor on the text or BLOB result when it has
4166** finished using that result.
4167** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4168** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4169** assumes that the text or BLOB result is in constant space and does not
4170** copy the content of the parameter nor call a destructor on the content
4171** when it has finished using that result.
4172** ^If the 4th parameter to the sqlite3_result_text* interfaces
4173** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4174** then SQLite makes a copy of the result into space obtained from
4175** from [sqlite3_malloc()] before it returns.
4176**
4177** ^The sqlite3_result_value() interface sets the result of
4178** the application-defined function to be a copy the
4179** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4180** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4181** so that the [sqlite3_value] specified in the parameter may change or
4182** be deallocated after sqlite3_result_value() returns without harm.
4183** ^A [protected sqlite3_value] object may always be used where an
4184** [unprotected sqlite3_value] object is required, so either
4185** kind of [sqlite3_value] object can be used with this interface.
4186**
4187** If these routines are called from within the different thread
4188** than the one containing the application-defined function that received
4189** the [sqlite3_context] pointer, the results are undefined.
4190*/
4191SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4192SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4193SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4194SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4195SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4196SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4197SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4198SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4199SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4200SQLITE_API void sqlite3_result_null(sqlite3_context*);
4201SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4202SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4203SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4204SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4205SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4206SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4207
4208/*
4209** CAPI3REF: Define New Collating Sequences
4210**
4211** These functions are used to add new collation sequences to the
4212** [database connection] specified as the first argument.
4213**
4214** ^The name of the new collation sequence is specified as a UTF-8 string
4215** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4216** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4217** the name is passed as the second function argument.
4218**
4219** ^The third argument may be one of the constants [SQLITE_UTF8],
4220** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4221** routine expects to be passed pointers to strings encoded using UTF-8,
4222** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4223** third argument might also be [SQLITE_UTF16] to indicate that the routine
4224** expects pointers to be UTF-16 strings in the native byte order, or the
4225** argument can be [SQLITE_UTF16_ALIGNED] if the
4226** the routine expects pointers to 16-bit word aligned strings
4227** of UTF-16 in the native byte order.
4228**
4229** A pointer to the user supplied routine must be passed as the fifth
4230** argument.  ^If it is NULL, this is the same as deleting the collation
4231** sequence (so that SQLite cannot call it anymore).
4232** ^Each time the application supplied function is invoked, it is passed
4233** as its first parameter a copy of the void* passed as the fourth argument
4234** to sqlite3_create_collation() or sqlite3_create_collation16().
4235**
4236** ^The remaining arguments to the application-supplied routine are two strings,
4237** each represented by a (length, data) pair and encoded in the encoding
4238** that was passed as the third argument when the collation sequence was
4239** registered.  The application defined collation routine should
4240** return negative, zero or positive if the first string is less than,
4241** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4242**
4243** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4244** except that it takes an extra argument which is a destructor for
4245** the collation.  ^The destructor is called when the collation is
4246** destroyed and is passed a copy of the fourth parameter void* pointer
4247** of the sqlite3_create_collation_v2().
4248** ^Collations are destroyed when they are overridden by later calls to the
4249** collation creation functions or when the [database connection] is closed
4250** using [sqlite3_close()].
4251**
4252** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4253*/
4254SQLITE_API int sqlite3_create_collation(
4255  sqlite3*,
4256  const char *zName,
4257  int eTextRep,
4258  void*,
4259  int(*xCompare)(void*,int,const void*,int,const void*)
4260);
4261SQLITE_API int sqlite3_create_collation_v2(
4262  sqlite3*,
4263  const char *zName,
4264  int eTextRep,
4265  void*,
4266  int(*xCompare)(void*,int,const void*,int,const void*),
4267  void(*xDestroy)(void*)
4268);
4269SQLITE_API int sqlite3_create_collation16(
4270  sqlite3*,
4271  const void *zName,
4272  int eTextRep,
4273  void*,
4274  int(*xCompare)(void*,int,const void*,int,const void*)
4275);
4276
4277/*
4278** CAPI3REF: Collation Needed Callbacks
4279**
4280** ^To avoid having to register all collation sequences before a database
4281** can be used, a single callback function may be registered with the
4282** [database connection] to be invoked whenever an undefined collation
4283** sequence is required.
4284**
4285** ^If the function is registered using the sqlite3_collation_needed() API,
4286** then it is passed the names of undefined collation sequences as strings
4287** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4288** the names are passed as UTF-16 in machine native byte order.
4289** ^A call to either function replaces the existing collation-needed callback.
4290**
4291** ^(When the callback is invoked, the first argument passed is a copy
4292** of the second argument to sqlite3_collation_needed() or
4293** sqlite3_collation_needed16().  The second argument is the database
4294** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4295** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4296** sequence function required.  The fourth parameter is the name of the
4297** required collation sequence.)^
4298**
4299** The callback function should register the desired collation using
4300** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4301** [sqlite3_create_collation_v2()].
4302*/
4303SQLITE_API int sqlite3_collation_needed(
4304  sqlite3*,
4305  void*,
4306  void(*)(void*,sqlite3*,int eTextRep,const char*)
4307);
4308SQLITE_API int sqlite3_collation_needed16(
4309  sqlite3*,
4310  void*,
4311  void(*)(void*,sqlite3*,int eTextRep,const void*)
4312);
4313
4314#ifdef SQLITE_HAS_CODEC
4315/*
4316** Specify the key for an encrypted database.  This routine should be
4317** called right after sqlite3_open().
4318**
4319** The code to implement this API is not available in the public release
4320** of SQLite.
4321*/
4322SQLITE_API int sqlite3_key(
4323  sqlite3 *db,                   /* Database to be rekeyed */
4324  const void *pKey, int nKey     /* The key */
4325);
4326
4327/*
4328** Change the key on an open database.  If the current database is not
4329** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4330** database is decrypted.
4331**
4332** The code to implement this API is not available in the public release
4333** of SQLite.
4334*/
4335SQLITE_API int sqlite3_rekey(
4336  sqlite3 *db,                   /* Database to be rekeyed */
4337  const void *pKey, int nKey     /* The new key */
4338);
4339
4340/*
4341** Specify the activation key for a SEE database.  Unless
4342** activated, none of the SEE routines will work.
4343*/
4344SQLITE_API void sqlite3_activate_see(
4345  const char *zPassPhrase        /* Activation phrase */
4346);
4347#endif
4348
4349#ifdef SQLITE_ENABLE_CEROD
4350/*
4351** Specify the activation key for a CEROD database.  Unless
4352** activated, none of the CEROD routines will work.
4353*/
4354SQLITE_API void sqlite3_activate_cerod(
4355  const char *zPassPhrase        /* Activation phrase */
4356);
4357#endif
4358
4359/*
4360** CAPI3REF: Suspend Execution For A Short Time
4361**
4362** ^The sqlite3_sleep() function causes the current thread to suspend execution
4363** for at least a number of milliseconds specified in its parameter.
4364**
4365** ^If the operating system does not support sleep requests with
4366** millisecond time resolution, then the time will be rounded up to
4367** the nearest second. ^The number of milliseconds of sleep actually
4368** requested from the operating system is returned.
4369**
4370** ^SQLite implements this interface by calling the xSleep()
4371** method of the default [sqlite3_vfs] object.
4372*/
4373SQLITE_API int sqlite3_sleep(int);
4374
4375/*
4376** CAPI3REF: Name Of The Folder Holding Temporary Files
4377**
4378** ^(If this global variable is made to point to a string which is
4379** the name of a folder (a.k.a. directory), then all temporary files
4380** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4381** will be placed in that directory.)^  ^If this variable
4382** is a NULL pointer, then SQLite performs a search for an appropriate
4383** temporary file directory.
4384**
4385** It is not safe to read or modify this variable in more than one
4386** thread at a time.  It is not safe to read or modify this variable
4387** if a [database connection] is being used at the same time in a separate
4388** thread.
4389** It is intended that this variable be set once
4390** as part of process initialization and before any SQLite interface
4391** routines have been called and that this variable remain unchanged
4392** thereafter.
4393**
4394** ^The [temp_store_directory pragma] may modify this variable and cause
4395** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4396** the [temp_store_directory pragma] always assumes that any string
4397** that this variable points to is held in memory obtained from
4398** [sqlite3_malloc] and the pragma may attempt to free that memory
4399** using [sqlite3_free].
4400** Hence, if this variable is modified directly, either it should be
4401** made NULL or made to point to memory obtained from [sqlite3_malloc]
4402** or else the use of the [temp_store_directory pragma] should be avoided.
4403*/
4404SQLITE_API char *sqlite3_temp_directory;
4405
4406/*
4407** CAPI3REF: Test For Auto-Commit Mode
4408** KEYWORDS: {autocommit mode}
4409**
4410** ^The sqlite3_get_autocommit() interface returns non-zero or
4411** zero if the given database connection is or is not in autocommit mode,
4412** respectively.  ^Autocommit mode is on by default.
4413** ^Autocommit mode is disabled by a [BEGIN] statement.
4414** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4415**
4416** If certain kinds of errors occur on a statement within a multi-statement
4417** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4418** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4419** transaction might be rolled back automatically.  The only way to
4420** find out whether SQLite automatically rolled back the transaction after
4421** an error is to use this function.
4422**
4423** If another thread changes the autocommit status of the database
4424** connection while this routine is running, then the return value
4425** is undefined.
4426*/
4427SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4428
4429/*
4430** CAPI3REF: Find The Database Handle Of A Prepared Statement
4431**
4432** ^The sqlite3_db_handle interface returns the [database connection] handle
4433** to which a [prepared statement] belongs.  ^The [database connection]
4434** returned by sqlite3_db_handle is the same [database connection]
4435** that was the first argument
4436** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4437** create the statement in the first place.
4438*/
4439SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4440
4441/*
4442** CAPI3REF: Find the next prepared statement
4443**
4444** ^This interface returns a pointer to the next [prepared statement] after
4445** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4446** then this interface returns a pointer to the first prepared statement
4447** associated with the database connection pDb.  ^If no prepared statement
4448** satisfies the conditions of this routine, it returns NULL.
4449**
4450** The [database connection] pointer D in a call to
4451** [sqlite3_next_stmt(D,S)] must refer to an open database
4452** connection and in particular must not be a NULL pointer.
4453*/
4454SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4455
4456/*
4457** CAPI3REF: Commit And Rollback Notification Callbacks
4458**
4459** ^The sqlite3_commit_hook() interface registers a callback
4460** function to be invoked whenever a transaction is [COMMIT | committed].
4461** ^Any callback set by a previous call to sqlite3_commit_hook()
4462** for the same database connection is overridden.
4463** ^The sqlite3_rollback_hook() interface registers a callback
4464** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4465** ^Any callback set by a previous call to sqlite3_rollback_hook()
4466** for the same database connection is overridden.
4467** ^The pArg argument is passed through to the callback.
4468** ^If the callback on a commit hook function returns non-zero,
4469** then the commit is converted into a rollback.
4470**
4471** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4472** return the P argument from the previous call of the same function
4473** on the same [database connection] D, or NULL for
4474** the first call for each function on D.
4475**
4476** The callback implementation must not do anything that will modify
4477** the database connection that invoked the callback.  Any actions
4478** to modify the database connection must be deferred until after the
4479** completion of the [sqlite3_step()] call that triggered the commit
4480** or rollback hook in the first place.
4481** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4482** database connections for the meaning of "modify" in this paragraph.
4483**
4484** ^Registering a NULL function disables the callback.
4485**
4486** ^When the commit hook callback routine returns zero, the [COMMIT]
4487** operation is allowed to continue normally.  ^If the commit hook
4488** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4489** ^The rollback hook is invoked on a rollback that results from a commit
4490** hook returning non-zero, just as it would be with any other rollback.
4491**
4492** ^For the purposes of this API, a transaction is said to have been
4493** rolled back if an explicit "ROLLBACK" statement is executed, or
4494** an error or constraint causes an implicit rollback to occur.
4495** ^The rollback callback is not invoked if a transaction is
4496** automatically rolled back because the database connection is closed.
4497**
4498** See also the [sqlite3_update_hook()] interface.
4499*/
4500SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4501SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4502
4503/*
4504** CAPI3REF: Data Change Notification Callbacks
4505**
4506** ^The sqlite3_update_hook() interface registers a callback function
4507** with the [database connection] identified by the first argument
4508** to be invoked whenever a row is updated, inserted or deleted.
4509** ^Any callback set by a previous call to this function
4510** for the same database connection is overridden.
4511**
4512** ^The second argument is a pointer to the function to invoke when a
4513** row is updated, inserted or deleted.
4514** ^The first argument to the callback is a copy of the third argument
4515** to sqlite3_update_hook().
4516** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4517** or [SQLITE_UPDATE], depending on the operation that caused the callback
4518** to be invoked.
4519** ^The third and fourth arguments to the callback contain pointers to the
4520** database and table name containing the affected row.
4521** ^The final callback parameter is the [rowid] of the row.
4522** ^In the case of an update, this is the [rowid] after the update takes place.
4523**
4524** ^(The update hook is not invoked when internal system tables are
4525** modified (i.e. sqlite_master and sqlite_sequence).)^
4526**
4527** ^In the current implementation, the update hook
4528** is not invoked when duplication rows are deleted because of an
4529** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4530** invoked when rows are deleted using the [truncate optimization].
4531** The exceptions defined in this paragraph might change in a future
4532** release of SQLite.
4533**
4534** The update hook implementation must not do anything that will modify
4535** the database connection that invoked the update hook.  Any actions
4536** to modify the database connection must be deferred until after the
4537** completion of the [sqlite3_step()] call that triggered the update hook.
4538** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4539** database connections for the meaning of "modify" in this paragraph.
4540**
4541** ^The sqlite3_update_hook(D,C,P) function
4542** returns the P argument from the previous call
4543** on the same [database connection] D, or NULL for
4544** the first call on D.
4545**
4546** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4547** interfaces.
4548*/
4549SQLITE_API void *sqlite3_update_hook(
4550  sqlite3*,
4551  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4552  void*
4553);
4554
4555/*
4556** CAPI3REF: Enable Or Disable Shared Pager Cache
4557** KEYWORDS: {shared cache}
4558**
4559** ^(This routine enables or disables the sharing of the database cache
4560** and schema data structures between [database connection | connections]
4561** to the same database. Sharing is enabled if the argument is true
4562** and disabled if the argument is false.)^
4563**
4564** ^Cache sharing is enabled and disabled for an entire process.
4565** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4566** sharing was enabled or disabled for each thread separately.
4567**
4568** ^(The cache sharing mode set by this interface effects all subsequent
4569** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4570** Existing database connections continue use the sharing mode
4571** that was in effect at the time they were opened.)^
4572**
4573** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4574** successfully.  An [error code] is returned otherwise.)^
4575**
4576** ^Shared cache is disabled by default. But this might change in
4577** future releases of SQLite.  Applications that care about shared
4578** cache setting should set it explicitly.
4579**
4580** See Also:  [SQLite Shared-Cache Mode]
4581*/
4582SQLITE_API int sqlite3_enable_shared_cache(int);
4583
4584/*
4585** CAPI3REF: Attempt To Free Heap Memory
4586**
4587** ^The sqlite3_release_memory() interface attempts to free N bytes
4588** of heap memory by deallocating non-essential memory allocations
4589** held by the database library.   Memory used to cache database
4590** pages to improve performance is an example of non-essential memory.
4591** ^sqlite3_release_memory() returns the number of bytes actually freed,
4592** which might be more or less than the amount requested.
4593*/
4594SQLITE_API int sqlite3_release_memory(int);
4595
4596/*
4597** CAPI3REF: Impose A Limit On Heap Size
4598**
4599** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4600** on the amount of heap memory that may be allocated by SQLite.
4601** ^If an internal allocation is requested that would exceed the
4602** soft heap limit, [sqlite3_release_memory()] is invoked one or
4603** more times to free up some space before the allocation is performed.
4604**
4605** ^The limit is called "soft" because if [sqlite3_release_memory()]
4606** cannot free sufficient memory to prevent the limit from being exceeded,
4607** the memory is allocated anyway and the current operation proceeds.
4608**
4609** ^A negative or zero value for N means that there is no soft heap limit and
4610** [sqlite3_release_memory()] will only be called when memory is exhausted.
4611** ^The default value for the soft heap limit is zero.
4612**
4613** ^(SQLite makes a best effort to honor the soft heap limit.
4614** But if the soft heap limit cannot be honored, execution will
4615** continue without error or notification.)^  This is why the limit is
4616** called a "soft" limit.  It is advisory only.
4617**
4618** Prior to SQLite version 3.5.0, this routine only constrained the memory
4619** allocated by a single thread - the same thread in which this routine
4620** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4621** applied to all threads. The value specified for the soft heap limit
4622** is an upper bound on the total memory allocation for all threads. In
4623** version 3.5.0 there is no mechanism for limiting the heap usage for
4624** individual threads.
4625*/
4626SQLITE_API void sqlite3_soft_heap_limit(int);
4627
4628/*
4629** CAPI3REF: Extract Metadata About A Column Of A Table
4630**
4631** ^This routine returns metadata about a specific column of a specific
4632** database table accessible using the [database connection] handle
4633** passed as the first function argument.
4634**
4635** ^The column is identified by the second, third and fourth parameters to
4636** this function. ^The second parameter is either the name of the database
4637** (i.e. "main", "temp", or an attached database) containing the specified
4638** table or NULL. ^If it is NULL, then all attached databases are searched
4639** for the table using the same algorithm used by the database engine to
4640** resolve unqualified table references.
4641**
4642** ^The third and fourth parameters to this function are the table and column
4643** name of the desired column, respectively. Neither of these parameters
4644** may be NULL.
4645**
4646** ^Metadata is returned by writing to the memory locations passed as the 5th
4647** and subsequent parameters to this function. ^Any of these arguments may be
4648** NULL, in which case the corresponding element of metadata is omitted.
4649**
4650** ^(<blockquote>
4651** <table border="1">
4652** <tr><th> Parameter <th> Output<br>Type <th>  Description
4653**
4654** <tr><td> 5th <td> const char* <td> Data type
4655** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4656** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4657** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4658** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4659** </table>
4660** </blockquote>)^
4661**
4662** ^The memory pointed to by the character pointers returned for the
4663** declaration type and collation sequence is valid only until the next
4664** call to any SQLite API function.
4665**
4666** ^If the specified table is actually a view, an [error code] is returned.
4667**
4668** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4669** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4670** parameters are set for the explicitly declared column. ^(If there is no
4671** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4672** parameters are set as follows:
4673**
4674** <pre>
4675**     data type: "INTEGER"
4676**     collation sequence: "BINARY"
4677**     not null: 0
4678**     primary key: 1
4679**     auto increment: 0
4680** </pre>)^
4681**
4682** ^(This function may load one or more schemas from database files. If an
4683** error occurs during this process, or if the requested table or column
4684** cannot be found, an [error code] is returned and an error message left
4685** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4686**
4687** ^This API is only available if the library was compiled with the
4688** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4689*/
4690SQLITE_API int sqlite3_table_column_metadata(
4691  sqlite3 *db,                /* Connection handle */
4692  const char *zDbName,        /* Database name or NULL */
4693  const char *zTableName,     /* Table name */
4694  const char *zColumnName,    /* Column name */
4695  char const **pzDataType,    /* OUTPUT: Declared data type */
4696  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4697  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4698  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4699  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4700);
4701
4702/*
4703** CAPI3REF: Load An Extension
4704**
4705** ^This interface loads an SQLite extension library from the named file.
4706**
4707** ^The sqlite3_load_extension() interface attempts to load an
4708** SQLite extension library contained in the file zFile.
4709**
4710** ^The entry point is zProc.
4711** ^zProc may be 0, in which case the name of the entry point
4712** defaults to "sqlite3_extension_init".
4713** ^The sqlite3_load_extension() interface returns
4714** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4715** ^If an error occurs and pzErrMsg is not 0, then the
4716** [sqlite3_load_extension()] interface shall attempt to
4717** fill *pzErrMsg with error message text stored in memory
4718** obtained from [sqlite3_malloc()]. The calling function
4719** should free this memory by calling [sqlite3_free()].
4720**
4721** ^Extension loading must be enabled using
4722** [sqlite3_enable_load_extension()] prior to calling this API,
4723** otherwise an error will be returned.
4724**
4725** See also the [load_extension() SQL function].
4726*/
4727SQLITE_API int sqlite3_load_extension(
4728  sqlite3 *db,          /* Load the extension into this database connection */
4729  const char *zFile,    /* Name of the shared library containing extension */
4730  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4731  char **pzErrMsg       /* Put error message here if not 0 */
4732);
4733
4734/*
4735** CAPI3REF: Enable Or Disable Extension Loading
4736**
4737** ^So as not to open security holes in older applications that are
4738** unprepared to deal with extension loading, and as a means of disabling
4739** extension loading while evaluating user-entered SQL, the following API
4740** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4741**
4742** ^Extension loading is off by default. See ticket #1863.
4743** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4744** to turn extension loading on and call it with onoff==0 to turn
4745** it back off again.
4746*/
4747SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4748
4749/*
4750** CAPI3REF: Automatically Load An Extensions
4751**
4752** ^This API can be invoked at program startup in order to register
4753** one or more statically linked extensions that will be available
4754** to all new [database connections].
4755**
4756** ^(This routine stores a pointer to the extension entry point
4757** in an array that is obtained from [sqlite3_malloc()].  That memory
4758** is deallocated by [sqlite3_reset_auto_extension()].)^
4759**
4760** ^This function registers an extension entry point that is
4761** automatically invoked whenever a new [database connection]
4762** is opened using [sqlite3_open()], [sqlite3_open16()],
4763** or [sqlite3_open_v2()].
4764** ^Duplicate extensions are detected so calling this routine
4765** multiple times with the same extension is harmless.
4766** ^Automatic extensions apply across all threads.
4767*/
4768SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4769
4770/*
4771** CAPI3REF: Reset Automatic Extension Loading
4772**
4773** ^(This function disables all previously registered automatic
4774** extensions. It undoes the effect of all prior
4775** [sqlite3_auto_extension()] calls.)^
4776**
4777** ^This function disables automatic extensions in all threads.
4778*/
4779SQLITE_API void sqlite3_reset_auto_extension(void);
4780
4781/*
4782** The interface to the virtual-table mechanism is currently considered
4783** to be experimental.  The interface might change in incompatible ways.
4784** If this is a problem for you, do not use the interface at this time.
4785**
4786** When the virtual-table mechanism stabilizes, we will declare the
4787** interface fixed, support it indefinitely, and remove this comment.
4788*/
4789
4790/*
4791** Structures used by the virtual table interface
4792*/
4793typedef struct sqlite3_vtab sqlite3_vtab;
4794typedef struct sqlite3_index_info sqlite3_index_info;
4795typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4796typedef struct sqlite3_module sqlite3_module;
4797
4798/*
4799** CAPI3REF: Virtual Table Object
4800** KEYWORDS: sqlite3_module {virtual table module}
4801**
4802** This structure, sometimes called a a "virtual table module",
4803** defines the implementation of a [virtual tables].
4804** This structure consists mostly of methods for the module.
4805**
4806** ^A virtual table module is created by filling in a persistent
4807** instance of this structure and passing a pointer to that instance
4808** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4809** ^The registration remains valid until it is replaced by a different
4810** module or until the [database connection] closes.  The content
4811** of this structure must not change while it is registered with
4812** any database connection.
4813*/
4814struct sqlite3_module {
4815  int iVersion;
4816  int (*xCreate)(sqlite3*, void *pAux,
4817               int argc, const char *const*argv,
4818               sqlite3_vtab **ppVTab, char**);
4819  int (*xConnect)(sqlite3*, void *pAux,
4820               int argc, const char *const*argv,
4821               sqlite3_vtab **ppVTab, char**);
4822  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4823  int (*xDisconnect)(sqlite3_vtab *pVTab);
4824  int (*xDestroy)(sqlite3_vtab *pVTab);
4825  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4826  int (*xClose)(sqlite3_vtab_cursor*);
4827  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4828                int argc, sqlite3_value **argv);
4829  int (*xNext)(sqlite3_vtab_cursor*);
4830  int (*xEof)(sqlite3_vtab_cursor*);
4831  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4832  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4833  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4834  int (*xBegin)(sqlite3_vtab *pVTab);
4835  int (*xSync)(sqlite3_vtab *pVTab);
4836  int (*xCommit)(sqlite3_vtab *pVTab);
4837  int (*xRollback)(sqlite3_vtab *pVTab);
4838  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4839                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4840                       void **ppArg);
4841  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4842};
4843
4844/*
4845** CAPI3REF: Virtual Table Indexing Information
4846** KEYWORDS: sqlite3_index_info
4847**
4848** The sqlite3_index_info structure and its substructures is used to
4849** pass information into and receive the reply from the [xBestIndex]
4850** method of a [virtual table module].  The fields under **Inputs** are the
4851** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4852** results into the **Outputs** fields.
4853**
4854** ^(The aConstraint[] array records WHERE clause constraints of the form:
4855**
4856** <pre>column OP expr</pre>
4857**
4858** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4859** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4860** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4861** expr on the right-hand side can be evaluated (and thus the constraint
4862** is usable) and false if it cannot.)^
4863**
4864** ^The optimizer automatically inverts terms of the form "expr OP column"
4865** and makes other simplifications to the WHERE clause in an attempt to
4866** get as many WHERE clause terms into the form shown above as possible.
4867** ^The aConstraint[] array only reports WHERE clause terms that are
4868** relevant to the particular virtual table being queried.
4869**
4870** ^Information about the ORDER BY clause is stored in aOrderBy[].
4871** ^Each term of aOrderBy records a column of the ORDER BY clause.
4872**
4873** The [xBestIndex] method must fill aConstraintUsage[] with information
4874** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4875** the right-hand side of the corresponding aConstraint[] is evaluated
4876** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4877** is true, then the constraint is assumed to be fully handled by the
4878** virtual table and is not checked again by SQLite.)^
4879**
4880** ^The idxNum and idxPtr values are recorded and passed into the
4881** [xFilter] method.
4882** ^[sqlite3_free()] is used to free idxPtr if and only if
4883** needToFreeIdxPtr is true.
4884**
4885** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4886** the correct order to satisfy the ORDER BY clause so that no separate
4887** sorting step is required.
4888**
4889** ^The estimatedCost value is an estimate of the cost of doing the
4890** particular lookup.  A full scan of a table with N entries should have
4891** a cost of N.  A binary search of a table of N entries should have a
4892** cost of approximately log(N).
4893*/
4894struct sqlite3_index_info {
4895  /* Inputs */
4896  int nConstraint;           /* Number of entries in aConstraint */
4897  struct sqlite3_index_constraint {
4898     int iColumn;              /* Column on left-hand side of constraint */
4899     unsigned char op;         /* Constraint operator */
4900     unsigned char usable;     /* True if this constraint is usable */
4901     int iTermOffset;          /* Used internally - xBestIndex should ignore */
4902  } *aConstraint;            /* Table of WHERE clause constraints */
4903  int nOrderBy;              /* Number of terms in the ORDER BY clause */
4904  struct sqlite3_index_orderby {
4905     int iColumn;              /* Column number */
4906     unsigned char desc;       /* True for DESC.  False for ASC. */
4907  } *aOrderBy;               /* The ORDER BY clause */
4908  /* Outputs */
4909  struct sqlite3_index_constraint_usage {
4910    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4911    unsigned char omit;      /* Do not code a test for this constraint */
4912  } *aConstraintUsage;
4913  int idxNum;                /* Number used to identify the index */
4914  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4915  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4916  int orderByConsumed;       /* True if output is already ordered */
4917  double estimatedCost;      /* Estimated cost of using this index */
4918};
4919#define SQLITE_INDEX_CONSTRAINT_EQ    2
4920#define SQLITE_INDEX_CONSTRAINT_GT    4
4921#define SQLITE_INDEX_CONSTRAINT_LE    8
4922#define SQLITE_INDEX_CONSTRAINT_LT    16
4923#define SQLITE_INDEX_CONSTRAINT_GE    32
4924#define SQLITE_INDEX_CONSTRAINT_MATCH 64
4925
4926/*
4927** CAPI3REF: Register A Virtual Table Implementation
4928**
4929** ^These routines are used to register a new [virtual table module] name.
4930** ^Module names must be registered before
4931** creating a new [virtual table] using the module and before using a
4932** preexisting [virtual table] for the module.
4933**
4934** ^The module name is registered on the [database connection] specified
4935** by the first parameter.  ^The name of the module is given by the
4936** second parameter.  ^The third parameter is a pointer to
4937** the implementation of the [virtual table module].   ^The fourth
4938** parameter is an arbitrary client data pointer that is passed through
4939** into the [xCreate] and [xConnect] methods of the virtual table module
4940** when a new virtual table is be being created or reinitialized.
4941**
4942** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4943** is a pointer to a destructor for the pClientData.  ^SQLite will
4944** invoke the destructor function (if it is not NULL) when SQLite
4945** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4946** interface is equivalent to sqlite3_create_module_v2() with a NULL
4947** destructor.
4948*/
4949SQLITE_API int sqlite3_create_module(
4950  sqlite3 *db,               /* SQLite connection to register module with */
4951  const char *zName,         /* Name of the module */
4952  const sqlite3_module *p,   /* Methods for the module */
4953  void *pClientData          /* Client data for xCreate/xConnect */
4954);
4955SQLITE_API int sqlite3_create_module_v2(
4956  sqlite3 *db,               /* SQLite connection to register module with */
4957  const char *zName,         /* Name of the module */
4958  const sqlite3_module *p,   /* Methods for the module */
4959  void *pClientData,         /* Client data for xCreate/xConnect */
4960  void(*xDestroy)(void*)     /* Module destructor function */
4961);
4962
4963/*
4964** CAPI3REF: Virtual Table Instance Object
4965** KEYWORDS: sqlite3_vtab
4966**
4967** Every [virtual table module] implementation uses a subclass
4968** of this object to describe a particular instance
4969** of the [virtual table].  Each subclass will
4970** be tailored to the specific needs of the module implementation.
4971** The purpose of this superclass is to define certain fields that are
4972** common to all module implementations.
4973**
4974** ^Virtual tables methods can set an error message by assigning a
4975** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4976** take care that any prior string is freed by a call to [sqlite3_free()]
4977** prior to assigning a new string to zErrMsg.  ^After the error message
4978** is delivered up to the client application, the string will be automatically
4979** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4980*/
4981struct sqlite3_vtab {
4982  const sqlite3_module *pModule;  /* The module for this virtual table */
4983  int nRef;                       /* NO LONGER USED */
4984  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4985  /* Virtual table implementations will typically add additional fields */
4986};
4987
4988/*
4989** CAPI3REF: Virtual Table Cursor Object
4990** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4991**
4992** Every [virtual table module] implementation uses a subclass of the
4993** following structure to describe cursors that point into the
4994** [virtual table] and are used
4995** to loop through the virtual table.  Cursors are created using the
4996** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4997** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4998** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4999** of the module.  Each module implementation will define
5000** the content of a cursor structure to suit its own needs.
5001**
5002** This superclass exists in order to define fields of the cursor that
5003** are common to all implementations.
5004*/
5005struct sqlite3_vtab_cursor {
5006  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5007  /* Virtual table implementations will typically add additional fields */
5008};
5009
5010/*
5011** CAPI3REF: Declare The Schema Of A Virtual Table
5012**
5013** ^The [xCreate] and [xConnect] methods of a
5014** [virtual table module] call this interface
5015** to declare the format (the names and datatypes of the columns) of
5016** the virtual tables they implement.
5017*/
5018SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5019
5020/*
5021** CAPI3REF: Overload A Function For A Virtual Table
5022**
5023** ^(Virtual tables can provide alternative implementations of functions
5024** using the [xFindFunction] method of the [virtual table module].
5025** But global versions of those functions
5026** must exist in order to be overloaded.)^
5027**
5028** ^(This API makes sure a global version of a function with a particular
5029** name and number of parameters exists.  If no such function exists
5030** before this API is called, a new function is created.)^  ^The implementation
5031** of the new function always causes an exception to be thrown.  So
5032** the new function is not good for anything by itself.  Its only
5033** purpose is to be a placeholder function that can be overloaded
5034** by a [virtual table].
5035*/
5036SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5037
5038/*
5039** The interface to the virtual-table mechanism defined above (back up
5040** to a comment remarkably similar to this one) is currently considered
5041** to be experimental.  The interface might change in incompatible ways.
5042** If this is a problem for you, do not use the interface at this time.
5043**
5044** When the virtual-table mechanism stabilizes, we will declare the
5045** interface fixed, support it indefinitely, and remove this comment.
5046*/
5047
5048/*
5049** CAPI3REF: A Handle To An Open BLOB
5050** KEYWORDS: {BLOB handle} {BLOB handles}
5051**
5052** An instance of this object represents an open BLOB on which
5053** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5054** ^Objects of this type are created by [sqlite3_blob_open()]
5055** and destroyed by [sqlite3_blob_close()].
5056** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5057** can be used to read or write small subsections of the BLOB.
5058** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5059*/
5060typedef struct sqlite3_blob sqlite3_blob;
5061
5062/*
5063** CAPI3REF: Open A BLOB For Incremental I/O
5064**
5065** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5066** in row iRow, column zColumn, table zTable in database zDb;
5067** in other words, the same BLOB that would be selected by:
5068**
5069** <pre>
5070**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5071** </pre>)^
5072**
5073** ^If the flags parameter is non-zero, then the BLOB is opened for read
5074** and write access. ^If it is zero, the BLOB is opened for read access.
5075** ^It is not possible to open a column that is part of an index or primary
5076** key for writing. ^If [foreign key constraints] are enabled, it is
5077** not possible to open a column that is part of a [child key] for writing.
5078**
5079** ^Note that the database name is not the filename that contains
5080** the database but rather the symbolic name of the database that
5081** appears after the AS keyword when the database is connected using [ATTACH].
5082** ^For the main database file, the database name is "main".
5083** ^For TEMP tables, the database name is "temp".
5084**
5085** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5086** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5087** to be a null pointer.)^
5088** ^This function sets the [database connection] error code and message
5089** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5090** functions. ^Note that the *ppBlob variable is always initialized in a
5091** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5092** regardless of the success or failure of this routine.
5093**
5094** ^(If the row that a BLOB handle points to is modified by an
5095** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5096** then the BLOB handle is marked as "expired".
5097** This is true if any column of the row is changed, even a column
5098** other than the one the BLOB handle is open on.)^
5099** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5100** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5101** ^(Changes written into a BLOB prior to the BLOB expiring are not
5102** rolled back by the expiration of the BLOB.  Such changes will eventually
5103** commit if the transaction continues to completion.)^
5104**
5105** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5106** the opened blob.  ^The size of a blob may not be changed by this
5107** interface.  Use the [UPDATE] SQL command to change the size of a
5108** blob.
5109**
5110** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5111** and the built-in [zeroblob] SQL function can be used, if desired,
5112** to create an empty, zero-filled blob in which to read or write using
5113** this interface.
5114**
5115** To avoid a resource leak, every open [BLOB handle] should eventually
5116** be released by a call to [sqlite3_blob_close()].
5117*/
5118SQLITE_API int sqlite3_blob_open(
5119  sqlite3*,
5120  const char *zDb,
5121  const char *zTable,
5122  const char *zColumn,
5123  sqlite3_int64 iRow,
5124  int flags,
5125  sqlite3_blob **ppBlob
5126);
5127
5128/*
5129** CAPI3REF: Close A BLOB Handle
5130**
5131** ^Closes an open [BLOB handle].
5132**
5133** ^Closing a BLOB shall cause the current transaction to commit
5134** if there are no other BLOBs, no pending prepared statements, and the
5135** database connection is in [autocommit mode].
5136** ^If any writes were made to the BLOB, they might be held in cache
5137** until the close operation if they will fit.
5138**
5139** ^(Closing the BLOB often forces the changes
5140** out to disk and so if any I/O errors occur, they will likely occur
5141** at the time when the BLOB is closed.  Any errors that occur during
5142** closing are reported as a non-zero return value.)^
5143**
5144** ^(The BLOB is closed unconditionally.  Even if this routine returns
5145** an error code, the BLOB is still closed.)^
5146**
5147** ^Calling this routine with a null pointer (such as would be returned
5148** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5149*/
5150SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5151
5152/*
5153** CAPI3REF: Return The Size Of An Open BLOB
5154**
5155** ^Returns the size in bytes of the BLOB accessible via the
5156** successfully opened [BLOB handle] in its only argument.  ^The
5157** incremental blob I/O routines can only read or overwriting existing
5158** blob content; they cannot change the size of a blob.
5159**
5160** This routine only works on a [BLOB handle] which has been created
5161** by a prior successful call to [sqlite3_blob_open()] and which has not
5162** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5163** to this routine results in undefined and probably undesirable behavior.
5164*/
5165SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5166
5167/*
5168** CAPI3REF: Read Data From A BLOB Incrementally
5169**
5170** ^(This function is used to read data from an open [BLOB handle] into a
5171** caller-supplied buffer. N bytes of data are copied into buffer Z
5172** from the open BLOB, starting at offset iOffset.)^
5173**
5174** ^If offset iOffset is less than N bytes from the end of the BLOB,
5175** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5176** less than zero, [SQLITE_ERROR] is returned and no data is read.
5177** ^The size of the blob (and hence the maximum value of N+iOffset)
5178** can be determined using the [sqlite3_blob_bytes()] interface.
5179**
5180** ^An attempt to read from an expired [BLOB handle] fails with an
5181** error code of [SQLITE_ABORT].
5182**
5183** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5184** Otherwise, an [error code] or an [extended error code] is returned.)^
5185**
5186** This routine only works on a [BLOB handle] which has been created
5187** by a prior successful call to [sqlite3_blob_open()] and which has not
5188** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5189** to this routine results in undefined and probably undesirable behavior.
5190**
5191** See also: [sqlite3_blob_write()].
5192*/
5193SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5194
5195/*
5196** CAPI3REF: Write Data Into A BLOB Incrementally
5197**
5198** ^This function is used to write data into an open [BLOB handle] from a
5199** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5200** into the open BLOB, starting at offset iOffset.
5201**
5202** ^If the [BLOB handle] passed as the first argument was not opened for
5203** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5204** this function returns [SQLITE_READONLY].
5205**
5206** ^This function may only modify the contents of the BLOB; it is
5207** not possible to increase the size of a BLOB using this API.
5208** ^If offset iOffset is less than N bytes from the end of the BLOB,
5209** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5210** less than zero [SQLITE_ERROR] is returned and no data is written.
5211** The size of the BLOB (and hence the maximum value of N+iOffset)
5212** can be determined using the [sqlite3_blob_bytes()] interface.
5213**
5214** ^An attempt to write to an expired [BLOB handle] fails with an
5215** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5216** before the [BLOB handle] expired are not rolled back by the
5217** expiration of the handle, though of course those changes might
5218** have been overwritten by the statement that expired the BLOB handle
5219** or by other independent statements.
5220**
5221** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5222** Otherwise, an  [error code] or an [extended error code] is returned.)^
5223**
5224** This routine only works on a [BLOB handle] which has been created
5225** by a prior successful call to [sqlite3_blob_open()] and which has not
5226** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5227** to this routine results in undefined and probably undesirable behavior.
5228**
5229** See also: [sqlite3_blob_read()].
5230*/
5231SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5232
5233/*
5234** CAPI3REF: Virtual File System Objects
5235**
5236** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5237** that SQLite uses to interact
5238** with the underlying operating system.  Most SQLite builds come with a
5239** single default VFS that is appropriate for the host computer.
5240** New VFSes can be registered and existing VFSes can be unregistered.
5241** The following interfaces are provided.
5242**
5243** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5244** ^Names are case sensitive.
5245** ^Names are zero-terminated UTF-8 strings.
5246** ^If there is no match, a NULL pointer is returned.
5247** ^If zVfsName is NULL then the default VFS is returned.
5248**
5249** ^New VFSes are registered with sqlite3_vfs_register().
5250** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5251** ^The same VFS can be registered multiple times without injury.
5252** ^To make an existing VFS into the default VFS, register it again
5253** with the makeDflt flag set.  If two different VFSes with the
5254** same name are registered, the behavior is undefined.  If a
5255** VFS is registered with a name that is NULL or an empty string,
5256** then the behavior is undefined.
5257**
5258** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5259** ^(If the default VFS is unregistered, another VFS is chosen as
5260** the default.  The choice for the new VFS is arbitrary.)^
5261*/
5262SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5263SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5264SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5265
5266/*
5267** CAPI3REF: Mutexes
5268**
5269** The SQLite core uses these routines for thread
5270** synchronization. Though they are intended for internal
5271** use by SQLite, code that links against SQLite is
5272** permitted to use any of these routines.
5273**
5274** The SQLite source code contains multiple implementations
5275** of these mutex routines.  An appropriate implementation
5276** is selected automatically at compile-time.  ^(The following
5277** implementations are available in the SQLite core:
5278**
5279** <ul>
5280** <li>   SQLITE_MUTEX_OS2
5281** <li>   SQLITE_MUTEX_PTHREAD
5282** <li>   SQLITE_MUTEX_W32
5283** <li>   SQLITE_MUTEX_NOOP
5284** </ul>)^
5285**
5286** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5287** that does no real locking and is appropriate for use in
5288** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5289** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5290** are appropriate for use on OS/2, Unix, and Windows.
5291**
5292** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5293** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5294** implementation is included with the library. In this case the
5295** application must supply a custom mutex implementation using the
5296** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5297** before calling sqlite3_initialize() or any other public sqlite3_
5298** function that calls sqlite3_initialize().)^
5299**
5300** ^The sqlite3_mutex_alloc() routine allocates a new
5301** mutex and returns a pointer to it. ^If it returns NULL
5302** that means that a mutex could not be allocated.  ^SQLite
5303** will unwind its stack and return an error.  ^(The argument
5304** to sqlite3_mutex_alloc() is one of these integer constants:
5305**
5306** <ul>
5307** <li>  SQLITE_MUTEX_FAST
5308** <li>  SQLITE_MUTEX_RECURSIVE
5309** <li>  SQLITE_MUTEX_STATIC_MASTER
5310** <li>  SQLITE_MUTEX_STATIC_MEM
5311** <li>  SQLITE_MUTEX_STATIC_MEM2
5312** <li>  SQLITE_MUTEX_STATIC_PRNG
5313** <li>  SQLITE_MUTEX_STATIC_LRU
5314** <li>  SQLITE_MUTEX_STATIC_LRU2
5315** </ul>)^
5316**
5317** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5318** cause sqlite3_mutex_alloc() to create
5319** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5320** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5321** The mutex implementation does not need to make a distinction
5322** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5323** not want to.  ^SQLite will only request a recursive mutex in
5324** cases where it really needs one.  ^If a faster non-recursive mutex
5325** implementation is available on the host platform, the mutex subsystem
5326** might return such a mutex in response to SQLITE_MUTEX_FAST.
5327**
5328** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5329** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5330** a pointer to a static preexisting mutex.  ^Six static mutexes are
5331** used by the current version of SQLite.  Future versions of SQLite
5332** may add additional static mutexes.  Static mutexes are for internal
5333** use by SQLite only.  Applications that use SQLite mutexes should
5334** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5335** SQLITE_MUTEX_RECURSIVE.
5336**
5337** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5338** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5339** returns a different mutex on every call.  ^But for the static
5340** mutex types, the same mutex is returned on every call that has
5341** the same type number.
5342**
5343** ^The sqlite3_mutex_free() routine deallocates a previously
5344** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5345** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5346** use when they are deallocated.  Attempting to deallocate a static
5347** mutex results in undefined behavior.  ^SQLite never deallocates
5348** a static mutex.
5349**
5350** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5351** to enter a mutex.  ^If another thread is already within the mutex,
5352** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5353** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5354** upon successful entry.  ^(Mutexes created using
5355** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5356** In such cases the,
5357** mutex must be exited an equal number of times before another thread
5358** can enter.)^  ^(If the same thread tries to enter any other
5359** kind of mutex more than once, the behavior is undefined.
5360** SQLite will never exhibit
5361** such behavior in its own use of mutexes.)^
5362**
5363** ^(Some systems (for example, Windows 95) do not support the operation
5364** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5365** will always return SQLITE_BUSY.  The SQLite core only ever uses
5366** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5367**
5368** ^The sqlite3_mutex_leave() routine exits a mutex that was
5369** previously entered by the same thread.   ^(The behavior
5370** is undefined if the mutex is not currently entered by the
5371** calling thread or is not currently allocated.  SQLite will
5372** never do either.)^
5373**
5374** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5375** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5376** behave as no-ops.
5377**
5378** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5379*/
5380SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5381SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5382SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5383SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5384SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5385
5386/*
5387** CAPI3REF: Mutex Methods Object
5388**
5389** An instance of this structure defines the low-level routines
5390** used to allocate and use mutexes.
5391**
5392** Usually, the default mutex implementations provided by SQLite are
5393** sufficient, however the user has the option of substituting a custom
5394** implementation for specialized deployments or systems for which SQLite
5395** does not provide a suitable implementation. In this case, the user
5396** creates and populates an instance of this structure to pass
5397** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5398** Additionally, an instance of this structure can be used as an
5399** output variable when querying the system for the current mutex
5400** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5401**
5402** ^The xMutexInit method defined by this structure is invoked as
5403** part of system initialization by the sqlite3_initialize() function.
5404** ^The xMutexInit routine is calle by SQLite exactly once for each
5405** effective call to [sqlite3_initialize()].
5406**
5407** ^The xMutexEnd method defined by this structure is invoked as
5408** part of system shutdown by the sqlite3_shutdown() function. The
5409** implementation of this method is expected to release all outstanding
5410** resources obtained by the mutex methods implementation, especially
5411** those obtained by the xMutexInit method.  ^The xMutexEnd()
5412** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5413**
5414** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5415** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5416** xMutexNotheld) implement the following interfaces (respectively):
5417**
5418** <ul>
5419**   <li>  [sqlite3_mutex_alloc()] </li>
5420**   <li>  [sqlite3_mutex_free()] </li>
5421**   <li>  [sqlite3_mutex_enter()] </li>
5422**   <li>  [sqlite3_mutex_try()] </li>
5423**   <li>  [sqlite3_mutex_leave()] </li>
5424**   <li>  [sqlite3_mutex_held()] </li>
5425**   <li>  [sqlite3_mutex_notheld()] </li>
5426** </ul>)^
5427**
5428** The only difference is that the public sqlite3_XXX functions enumerated
5429** above silently ignore any invocations that pass a NULL pointer instead
5430** of a valid mutex handle. The implementations of the methods defined
5431** by this structure are not required to handle this case, the results
5432** of passing a NULL pointer instead of a valid mutex handle are undefined
5433** (i.e. it is acceptable to provide an implementation that segfaults if
5434** it is passed a NULL pointer).
5435**
5436** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5437** invoke xMutexInit() mutiple times within the same process and without
5438** intervening calls to xMutexEnd().  Second and subsequent calls to
5439** xMutexInit() must be no-ops.
5440**
5441** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5442** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5443** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5444** memory allocation for a fast or recursive mutex.
5445**
5446** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5447** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5448** If xMutexInit fails in any way, it is expected to clean up after itself
5449** prior to returning.
5450*/
5451typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5452struct sqlite3_mutex_methods {
5453  int (*xMutexInit)(void);
5454  int (*xMutexEnd)(void);
5455  sqlite3_mutex *(*xMutexAlloc)(int);
5456  void (*xMutexFree)(sqlite3_mutex *);
5457  void (*xMutexEnter)(sqlite3_mutex *);
5458  int (*xMutexTry)(sqlite3_mutex *);
5459  void (*xMutexLeave)(sqlite3_mutex *);
5460  int (*xMutexHeld)(sqlite3_mutex *);
5461  int (*xMutexNotheld)(sqlite3_mutex *);
5462};
5463
5464/*
5465** CAPI3REF: Mutex Verification Routines
5466**
5467** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5468** are intended for use inside assert() statements.  ^The SQLite core
5469** never uses these routines except inside an assert() and applications
5470** are advised to follow the lead of the core.  ^The SQLite core only
5471** provides implementations for these routines when it is compiled
5472** with the SQLITE_DEBUG flag.  ^External mutex implementations
5473** are only required to provide these routines if SQLITE_DEBUG is
5474** defined and if NDEBUG is not defined.
5475**
5476** ^These routines should return true if the mutex in their argument
5477** is held or not held, respectively, by the calling thread.
5478**
5479** ^The implementation is not required to provided versions of these
5480** routines that actually work. If the implementation does not provide working
5481** versions of these routines, it should at least provide stubs that always
5482** return true so that one does not get spurious assertion failures.
5483**
5484** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5485** the routine should return 1.   This seems counter-intuitive since
5486** clearly the mutex cannot be held if it does not exist.  But the
5487** the reason the mutex does not exist is because the build is not
5488** using mutexes.  And we do not want the assert() containing the
5489** call to sqlite3_mutex_held() to fail, so a non-zero return is
5490** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5491** interface should also return 1 when given a NULL pointer.
5492*/
5493#ifndef NDEBUG
5494SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5495SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5496#endif
5497
5498/*
5499** CAPI3REF: Mutex Types
5500**
5501** The [sqlite3_mutex_alloc()] interface takes a single argument
5502** which is one of these integer constants.
5503**
5504** The set of static mutexes may change from one SQLite release to the
5505** next.  Applications that override the built-in mutex logic must be
5506** prepared to accommodate additional static mutexes.
5507*/
5508#define SQLITE_MUTEX_FAST             0
5509#define SQLITE_MUTEX_RECURSIVE        1
5510#define SQLITE_MUTEX_STATIC_MASTER    2
5511#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5512#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5513#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5514#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5515#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5516#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5517
5518/*
5519** CAPI3REF: Retrieve the mutex for a database connection
5520**
5521** ^This interface returns a pointer the [sqlite3_mutex] object that
5522** serializes access to the [database connection] given in the argument
5523** when the [threading mode] is Serialized.
5524** ^If the [threading mode] is Single-thread or Multi-thread then this
5525** routine returns a NULL pointer.
5526*/
5527SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5528
5529/*
5530** CAPI3REF: Low-Level Control Of Database Files
5531**
5532** ^The [sqlite3_file_control()] interface makes a direct call to the
5533** xFileControl method for the [sqlite3_io_methods] object associated
5534** with a particular database identified by the second argument. ^The
5535** name of the database "main" for the main database or "temp" for the
5536** TEMP database, or the name that appears after the AS keyword for
5537** databases that are added using the [ATTACH] SQL command.
5538** ^A NULL pointer can be used in place of "main" to refer to the
5539** main database file.
5540** ^The third and fourth parameters to this routine
5541** are passed directly through to the second and third parameters of
5542** the xFileControl method.  ^The return value of the xFileControl
5543** method becomes the return value of this routine.
5544**
5545** ^If the second parameter (zDbName) does not match the name of any
5546** open database file, then SQLITE_ERROR is returned.  ^This error
5547** code is not remembered and will not be recalled by [sqlite3_errcode()]
5548** or [sqlite3_errmsg()].  The underlying xFileControl method might
5549** also return SQLITE_ERROR.  There is no way to distinguish between
5550** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5551** xFileControl method.
5552**
5553** See also: [SQLITE_FCNTL_LOCKSTATE]
5554*/
5555SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5556
5557/*
5558** CAPI3REF: Testing Interface
5559**
5560** ^The sqlite3_test_control() interface is used to read out internal
5561** state of SQLite and to inject faults into SQLite for testing
5562** purposes.  ^The first parameter is an operation code that determines
5563** the number, meaning, and operation of all subsequent parameters.
5564**
5565** This interface is not for use by applications.  It exists solely
5566** for verifying the correct operation of the SQLite library.  Depending
5567** on how the SQLite library is compiled, this interface might not exist.
5568**
5569** The details of the operation codes, their meanings, the parameters
5570** they take, and what they do are all subject to change without notice.
5571** Unlike most of the SQLite API, this function is not guaranteed to
5572** operate consistently from one release to the next.
5573*/
5574SQLITE_API int sqlite3_test_control(int op, ...);
5575
5576/*
5577** CAPI3REF: Testing Interface Operation Codes
5578**
5579** These constants are the valid operation code parameters used
5580** as the first argument to [sqlite3_test_control()].
5581**
5582** These parameters and their meanings are subject to change
5583** without notice.  These values are for testing purposes only.
5584** Applications should not use any of these parameters or the
5585** [sqlite3_test_control()] interface.
5586*/
5587#define SQLITE_TESTCTRL_FIRST                    5
5588#define SQLITE_TESTCTRL_PRNG_SAVE                5
5589#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5590#define SQLITE_TESTCTRL_PRNG_RESET               7
5591#define SQLITE_TESTCTRL_BITVEC_TEST              8
5592#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5593#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5594#define SQLITE_TESTCTRL_PENDING_BYTE            11
5595#define SQLITE_TESTCTRL_ASSERT                  12
5596#define SQLITE_TESTCTRL_ALWAYS                  13
5597#define SQLITE_TESTCTRL_RESERVE                 14
5598#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5599#define SQLITE_TESTCTRL_ISKEYWORD               16
5600#define SQLITE_TESTCTRL_PGHDRSZ                 17
5601#define SQLITE_TESTCTRL_LAST                    17
5602
5603/*
5604** CAPI3REF: SQLite Runtime Status
5605**
5606** ^This interface is used to retrieve runtime status information
5607** about the preformance of SQLite, and optionally to reset various
5608** highwater marks.  ^The first argument is an integer code for
5609** the specific parameter to measure.  ^(Recognized integer codes
5610** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5611** ^The current value of the parameter is returned into *pCurrent.
5612** ^The highest recorded value is returned in *pHighwater.  ^If the
5613** resetFlag is true, then the highest record value is reset after
5614** *pHighwater is written.  ^(Some parameters do not record the highest
5615** value.  For those parameters
5616** nothing is written into *pHighwater and the resetFlag is ignored.)^
5617** ^(Other parameters record only the highwater mark and not the current
5618** value.  For these latter parameters nothing is written into *pCurrent.)^
5619**
5620** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5621** non-zero [error code] on failure.
5622**
5623** This routine is threadsafe but is not atomic.  This routine can be
5624** called while other threads are running the same or different SQLite
5625** interfaces.  However the values returned in *pCurrent and
5626** *pHighwater reflect the status of SQLite at different points in time
5627** and it is possible that another thread might change the parameter
5628** in between the times when *pCurrent and *pHighwater are written.
5629**
5630** See also: [sqlite3_db_status()]
5631*/
5632SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5633
5634
5635/*
5636** CAPI3REF: Status Parameters
5637**
5638** These integer constants designate various run-time status parameters
5639** that can be returned by [sqlite3_status()].
5640**
5641** <dl>
5642** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5643** <dd>This parameter is the current amount of memory checked out
5644** using [sqlite3_malloc()], either directly or indirectly.  The
5645** figure includes calls made to [sqlite3_malloc()] by the application
5646** and internal memory usage by the SQLite library.  Scratch memory
5647** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5648** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5649** this parameter.  The amount returned is the sum of the allocation
5650** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5651**
5652** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5653** <dd>This parameter records the largest memory allocation request
5654** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5655** internal equivalents).  Only the value returned in the
5656** *pHighwater parameter to [sqlite3_status()] is of interest.
5657** The value written into the *pCurrent parameter is undefined.</dd>)^
5658**
5659** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5660** <dd>This parameter returns the number of pages used out of the
5661** [pagecache memory allocator] that was configured using
5662** [SQLITE_CONFIG_PAGECACHE].  The
5663** value returned is in pages, not in bytes.</dd>)^
5664**
5665** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5666** <dd>This parameter returns the number of bytes of page cache
5667** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5668** buffer and where forced to overflow to [sqlite3_malloc()].  The
5669** returned value includes allocations that overflowed because they
5670** where too large (they were larger than the "sz" parameter to
5671** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5672** no space was left in the page cache.</dd>)^
5673**
5674** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5675** <dd>This parameter records the largest memory allocation request
5676** handed to [pagecache memory allocator].  Only the value returned in the
5677** *pHighwater parameter to [sqlite3_status()] is of interest.
5678** The value written into the *pCurrent parameter is undefined.</dd>)^
5679**
5680** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5681** <dd>This parameter returns the number of allocations used out of the
5682** [scratch memory allocator] configured using
5683** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5684** in bytes.  Since a single thread may only have one scratch allocation
5685** outstanding at time, this parameter also reports the number of threads
5686** using scratch memory at the same time.</dd>)^
5687**
5688** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5689** <dd>This parameter returns the number of bytes of scratch memory
5690** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5691** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5692** returned include overflows because the requested allocation was too
5693** larger (that is, because the requested allocation was larger than the
5694** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5695** slots were available.
5696** </dd>)^
5697**
5698** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5699** <dd>This parameter records the largest memory allocation request
5700** handed to [scratch memory allocator].  Only the value returned in the
5701** *pHighwater parameter to [sqlite3_status()] is of interest.
5702** The value written into the *pCurrent parameter is undefined.</dd>)^
5703**
5704** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5705** <dd>This parameter records the deepest parser stack.  It is only
5706** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5707** </dl>
5708**
5709** New status parameters may be added from time to time.
5710*/
5711#define SQLITE_STATUS_MEMORY_USED          0
5712#define SQLITE_STATUS_PAGECACHE_USED       1
5713#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5714#define SQLITE_STATUS_SCRATCH_USED         3
5715#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5716#define SQLITE_STATUS_MALLOC_SIZE          5
5717#define SQLITE_STATUS_PARSER_STACK         6
5718#define SQLITE_STATUS_PAGECACHE_SIZE       7
5719#define SQLITE_STATUS_SCRATCH_SIZE         8
5720
5721/*
5722** CAPI3REF: Database Connection Status
5723**
5724** ^This interface is used to retrieve runtime status information
5725** about a single [database connection].  ^The first argument is the
5726** database connection object to be interrogated.  ^The second argument
5727** is an integer constant, taken from the set of
5728** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5729** determiness the parameter to interrogate.  The set of
5730** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5731** to grow in future releases of SQLite.
5732**
5733** ^The current value of the requested parameter is written into *pCur
5734** and the highest instantaneous value is written into *pHiwtr.  ^If
5735** the resetFlg is true, then the highest instantaneous value is
5736** reset back down to the current value.
5737**
5738** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5739*/
5740SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5741
5742/*
5743** CAPI3REF: Status Parameters for database connections
5744**
5745** These constants are the available integer "verbs" that can be passed as
5746** the second argument to the [sqlite3_db_status()] interface.
5747**
5748** New verbs may be added in future releases of SQLite. Existing verbs
5749** might be discontinued. Applications should check the return code from
5750** [sqlite3_db_status()] to make sure that the call worked.
5751** The [sqlite3_db_status()] interface will return a non-zero error code
5752** if a discontinued or unsupported verb is invoked.
5753**
5754** <dl>
5755** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5756** <dd>This parameter returns the number of lookaside memory slots currently
5757** checked out.</dd>)^
5758**
5759** <dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5760** <dd>^This parameter returns the approximate number of of bytes of heap
5761** memory used by all pager caches associated with the database connection.
5762** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5763** checked out.</dd>)^
5764** </dl>
5765*/
5766#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5767#define SQLITE_DBSTATUS_CACHE_USED         1
5768#define SQLITE_DBSTATUS_MAX                1   /* Largest defined DBSTATUS */
5769
5770
5771/*
5772** CAPI3REF: Prepared Statement Status
5773**
5774** ^(Each prepared statement maintains various
5775** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5776** of times it has performed specific operations.)^  These counters can
5777** be used to monitor the performance characteristics of the prepared
5778** statements.  For example, if the number of table steps greatly exceeds
5779** the number of table searches or result rows, that would tend to indicate
5780** that the prepared statement is using a full table scan rather than
5781** an index.
5782**
5783** ^(This interface is used to retrieve and reset counter values from
5784** a [prepared statement].  The first argument is the prepared statement
5785** object to be interrogated.  The second argument
5786** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5787** to be interrogated.)^
5788** ^The current value of the requested counter is returned.
5789** ^If the resetFlg is true, then the counter is reset to zero after this
5790** interface call returns.
5791**
5792** See also: [sqlite3_status()] and [sqlite3_db_status()].
5793*/
5794SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5795
5796/*
5797** CAPI3REF: Status Parameters for prepared statements
5798**
5799** These preprocessor macros define integer codes that name counter
5800** values associated with the [sqlite3_stmt_status()] interface.
5801** The meanings of the various counters are as follows:
5802**
5803** <dl>
5804** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5805** <dd>^This is the number of times that SQLite has stepped forward in
5806** a table as part of a full table scan.  Large numbers for this counter
5807** may indicate opportunities for performance improvement through
5808** careful use of indices.</dd>
5809**
5810** <dt>SQLITE_STMTSTATUS_SORT</dt>
5811** <dd>^This is the number of sort operations that have occurred.
5812** A non-zero value in this counter may indicate an opportunity to
5813** improvement performance through careful use of indices.</dd>
5814**
5815** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5816** <dd>^This is the number of rows inserted into transient indices that
5817** were created automatically in order to help joins run faster.
5818** A non-zero value in this counter may indicate an opportunity to
5819** improvement performance by adding permanent indices that do not
5820** need to be reinitialized each time the statement is run.</dd>
5821**
5822** </dl>
5823*/
5824#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5825#define SQLITE_STMTSTATUS_SORT              2
5826#define SQLITE_STMTSTATUS_AUTOINDEX         3
5827
5828/*
5829** CAPI3REF: Custom Page Cache Object
5830**
5831** The sqlite3_pcache type is opaque.  It is implemented by
5832** the pluggable module.  The SQLite core has no knowledge of
5833** its size or internal structure and never deals with the
5834** sqlite3_pcache object except by holding and passing pointers
5835** to the object.
5836**
5837** See [sqlite3_pcache_methods] for additional information.
5838*/
5839typedef struct sqlite3_pcache sqlite3_pcache;
5840
5841/*
5842** CAPI3REF: Application Defined Page Cache.
5843** KEYWORDS: {page cache}
5844**
5845** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5846** register an alternative page cache implementation by passing in an
5847** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5848** heap memory used by SQLite is used by the page cache to cache data read
5849** from, or ready to be written to, the database file. By implementing a
5850** custom page cache using this API, an application can control more
5851** precisely the amount of memory consumed by SQLite, the way in which
5852** that memory is allocated and released, and the policies used to
5853** determine exactly which parts of a database file are cached and for
5854** how long.
5855**
5856** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5857** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5858** the application may discard the parameter after the call to
5859** [sqlite3_config()] returns.)^
5860**
5861** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5862** (usually only once during the lifetime of the process). ^(The xInit()
5863** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5864** ^The xInit() method can set up up global structures and/or any mutexes
5865** required by the custom page cache implementation.
5866**
5867** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5868** if the application invokes this API. It can be used to clean up
5869** any outstanding resources before process shutdown, if required.
5870**
5871** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5872** the xInit method, so the xInit method need not be threadsafe.  ^The
5873** xShutdown method is only called from [sqlite3_shutdown()] so it does
5874** not need to be threadsafe either.  All other methods must be threadsafe
5875** in multithreaded applications.
5876**
5877** ^SQLite will never invoke xInit() more than once without an intervening
5878** call to xShutdown().
5879**
5880** ^The xCreate() method is used to construct a new cache instance.  SQLite
5881** will typically create one cache instance for each open database file,
5882** though this is not guaranteed. ^The
5883** first parameter, szPage, is the size in bytes of the pages that must
5884** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5885** will the page size of the database file that is to be cached plus an
5886** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5887** extra R bytes on each page to store metadata about the underlying
5888** database page on disk.  The value of R depends
5889** on the SQLite version, the target platform, and how SQLite was compiled.
5890** ^R is constant for a particular build of SQLite.  ^The second argument to
5891** xCreate(), bPurgeable, is true if the cache being created will
5892** be used to cache database pages of a file stored on disk, or
5893** false if it is used for an in-memory database. ^The cache implementation
5894** does not have to do anything special based with the value of bPurgeable;
5895** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5896** never invoke xUnpin() except to deliberately delete a page.
5897** ^In other words, a cache created with bPurgeable set to false will
5898** never contain any unpinned pages.
5899**
5900** ^(The xCachesize() method may be called at any time by SQLite to set the
5901** suggested maximum cache-size (number of pages stored by) the cache
5902** instance passed as the first argument. This is the value configured using
5903** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5904** parameter, the implementation is not required to do anything with this
5905** value; it is advisory only.
5906**
5907** ^The xPagecount() method should return the number of pages currently
5908** stored in the cache.
5909**
5910** ^The xFetch() method is used to fetch a page and return a pointer to it.
5911** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5912** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5913** mimimum key value is 1. After it has been retrieved using xFetch, the page
5914** is considered to be "pinned".
5915**
5916** ^If the requested page is already in the page cache, then the page cache
5917** implementation must return a pointer to the page buffer with its content
5918** intact.  ^(If the requested page is not already in the cache, then the
5919** behavior of the cache implementation is determined by the value of the
5920** createFlag parameter passed to xFetch, according to the following table:
5921**
5922** <table border=1 width=85% align=center>
5923** <tr><th> createFlag <th> Behaviour when page is not already in cache
5924** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5925** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5926**                 Otherwise return NULL.
5927** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5928**                 NULL if allocating a new page is effectively impossible.
5929** </table>)^
5930**
5931** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5932** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5933** attempt to unpin one or more cache pages by spilling the content of
5934** pinned pages to disk and synching the operating system disk cache. After
5935** attempting to unpin pages, the xFetch() method will be invoked again with
5936** a createFlag of 2.
5937**
5938** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5939** as its second argument. ^(If the third parameter, discard, is non-zero,
5940** then the page should be evicted from the cache. In this case SQLite
5941** assumes that the next time the page is retrieved from the cache using
5942** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5943** zero, then the page is considered to be unpinned. ^The cache implementation
5944** may choose to evict unpinned pages at any time.
5945**
5946** ^(The cache is not required to perform any reference counting. A single
5947** call to xUnpin() unpins the page regardless of the number of prior calls
5948** to xFetch().)^
5949**
5950** ^The xRekey() method is used to change the key value associated with the
5951** page passed as the second argument from oldKey to newKey. ^If the cache
5952** previously contains an entry associated with newKey, it should be
5953** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5954** to be pinned.
5955**
5956** ^When SQLite calls the xTruncate() method, the cache must discard all
5957** existing cache entries with page numbers (keys) greater than or equal
5958** to the value of the iLimit parameter passed to xTruncate(). ^If any
5959** of these pages are pinned, they are implicitly unpinned, meaning that
5960** they can be safely discarded.
5961**
5962** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5963** All resources associated with the specified cache should be freed. ^After
5964** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5965** handle invalid, and will not use it with any other sqlite3_pcache_methods
5966** functions.
5967*/
5968typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5969struct sqlite3_pcache_methods {
5970  void *pArg;
5971  int (*xInit)(void*);
5972  void (*xShutdown)(void*);
5973  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5974  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5975  int (*xPagecount)(sqlite3_pcache*);
5976  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5977  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5978  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5979  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5980  void (*xDestroy)(sqlite3_pcache*);
5981};
5982
5983/*
5984** CAPI3REF: Online Backup Object
5985**
5986** The sqlite3_backup object records state information about an ongoing
5987** online backup operation.  ^The sqlite3_backup object is created by
5988** a call to [sqlite3_backup_init()] and is destroyed by a call to
5989** [sqlite3_backup_finish()].
5990**
5991** See Also: [Using the SQLite Online Backup API]
5992*/
5993typedef struct sqlite3_backup sqlite3_backup;
5994
5995/*
5996** CAPI3REF: Online Backup API.
5997**
5998** The backup API copies the content of one database into another.
5999** It is useful either for creating backups of databases or
6000** for copying in-memory databases to or from persistent files.
6001**
6002** See Also: [Using the SQLite Online Backup API]
6003**
6004** ^Exclusive access is required to the destination database for the
6005** duration of the operation. ^However the source database is only
6006** read-locked while it is actually being read; it is not locked
6007** continuously for the entire backup operation. ^Thus, the backup may be
6008** performed on a live source database without preventing other users from
6009** reading or writing to the source database while the backup is underway.
6010**
6011** ^(To perform a backup operation:
6012**   <ol>
6013**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6014**         backup,
6015**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6016**         the data between the two databases, and finally
6017**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6018**         associated with the backup operation.
6019**   </ol>)^
6020** There should be exactly one call to sqlite3_backup_finish() for each
6021** successful call to sqlite3_backup_init().
6022**
6023** <b>sqlite3_backup_init()</b>
6024**
6025** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6026** [database connection] associated with the destination database
6027** and the database name, respectively.
6028** ^The database name is "main" for the main database, "temp" for the
6029** temporary database, or the name specified after the AS keyword in
6030** an [ATTACH] statement for an attached database.
6031** ^The S and M arguments passed to
6032** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6033** and database name of the source database, respectively.
6034** ^The source and destination [database connections] (parameters S and D)
6035** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6036** an error.
6037**
6038** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6039** returned and an error code and error message are store3d in the
6040** destination [database connection] D.
6041** ^The error code and message for the failed call to sqlite3_backup_init()
6042** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6043** [sqlite3_errmsg16()] functions.
6044** ^A successful call to sqlite3_backup_init() returns a pointer to an
6045** [sqlite3_backup] object.
6046** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6047** sqlite3_backup_finish() functions to perform the specified backup
6048** operation.
6049**
6050** <b>sqlite3_backup_step()</b>
6051**
6052** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6053** the source and destination databases specified by [sqlite3_backup] object B.
6054** ^If N is negative, all remaining source pages are copied.
6055** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6056** are still more pages to be copied, then the function resturns [SQLITE_OK].
6057** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6058** from source to destination, then it returns [SQLITE_DONE].
6059** ^If an error occurs while running sqlite3_backup_step(B,N),
6060** then an [error code] is returned. ^As well as [SQLITE_OK] and
6061** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6062** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6063** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6064**
6065** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6066** <ol>
6067** <li> the destination database was opened read-only, or
6068** <li> the destination database is using write-ahead-log journaling
6069** and the destination and source page sizes differ, or
6070** <li> The destination database is an in-memory database and the
6071** destination and source page sizes differ.
6072** </ol>)^
6073**
6074** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6075** the [sqlite3_busy_handler | busy-handler function]
6076** is invoked (if one is specified). ^If the
6077** busy-handler returns non-zero before the lock is available, then
6078** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6079** sqlite3_backup_step() can be retried later. ^If the source
6080** [database connection]
6081** is being used to write to the source database when sqlite3_backup_step()
6082** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6083** case the call to sqlite3_backup_step() can be retried later on. ^(If
6084** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6085** [SQLITE_READONLY] is returned, then
6086** there is no point in retrying the call to sqlite3_backup_step(). These
6087** errors are considered fatal.)^  The application must accept
6088** that the backup operation has failed and pass the backup operation handle
6089** to the sqlite3_backup_finish() to release associated resources.
6090**
6091** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6092** on the destination file. ^The exclusive lock is not released until either
6093** sqlite3_backup_finish() is called or the backup operation is complete
6094** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6095** sqlite3_backup_step() obtains a [shared lock] on the source database that
6096** lasts for the duration of the sqlite3_backup_step() call.
6097** ^Because the source database is not locked between calls to
6098** sqlite3_backup_step(), the source database may be modified mid-way
6099** through the backup process.  ^If the source database is modified by an
6100** external process or via a database connection other than the one being
6101** used by the backup operation, then the backup will be automatically
6102** restarted by the next call to sqlite3_backup_step(). ^If the source
6103** database is modified by the using the same database connection as is used
6104** by the backup operation, then the backup database is automatically
6105** updated at the same time.
6106**
6107** <b>sqlite3_backup_finish()</b>
6108**
6109** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6110** application wishes to abandon the backup operation, the application
6111** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6112** ^The sqlite3_backup_finish() interfaces releases all
6113** resources associated with the [sqlite3_backup] object.
6114** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6115** active write-transaction on the destination database is rolled back.
6116** The [sqlite3_backup] object is invalid
6117** and may not be used following a call to sqlite3_backup_finish().
6118**
6119** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6120** sqlite3_backup_step() errors occurred, regardless or whether or not
6121** sqlite3_backup_step() completed.
6122** ^If an out-of-memory condition or IO error occurred during any prior
6123** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6124** sqlite3_backup_finish() returns the corresponding [error code].
6125**
6126** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6127** is not a permanent error and does not affect the return value of
6128** sqlite3_backup_finish().
6129**
6130** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6131**
6132** ^Each call to sqlite3_backup_step() sets two values inside
6133** the [sqlite3_backup] object: the number of pages still to be backed
6134** up and the total number of pages in the source databae file.
6135** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6136** retrieve these two values, respectively.
6137**
6138** ^The values returned by these functions are only updated by
6139** sqlite3_backup_step(). ^If the source database is modified during a backup
6140** operation, then the values are not updated to account for any extra
6141** pages that need to be updated or the size of the source database file
6142** changing.
6143**
6144** <b>Concurrent Usage of Database Handles</b>
6145**
6146** ^The source [database connection] may be used by the application for other
6147** purposes while a backup operation is underway or being initialized.
6148** ^If SQLite is compiled and configured to support threadsafe database
6149** connections, then the source database connection may be used concurrently
6150** from within other threads.
6151**
6152** However, the application must guarantee that the destination
6153** [database connection] is not passed to any other API (by any thread) after
6154** sqlite3_backup_init() is called and before the corresponding call to
6155** sqlite3_backup_finish().  SQLite does not currently check to see
6156** if the application incorrectly accesses the destination [database connection]
6157** and so no error code is reported, but the operations may malfunction
6158** nevertheless.  Use of the destination database connection while a
6159** backup is in progress might also also cause a mutex deadlock.
6160**
6161** If running in [shared cache mode], the application must
6162** guarantee that the shared cache used by the destination database
6163** is not accessed while the backup is running. In practice this means
6164** that the application must guarantee that the disk file being
6165** backed up to is not accessed by any connection within the process,
6166** not just the specific connection that was passed to sqlite3_backup_init().
6167**
6168** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6169** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6170** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6171** APIs are not strictly speaking threadsafe. If they are invoked at the
6172** same time as another thread is invoking sqlite3_backup_step() it is
6173** possible that they return invalid values.
6174*/
6175SQLITE_API sqlite3_backup *sqlite3_backup_init(
6176  sqlite3 *pDest,                        /* Destination database handle */
6177  const char *zDestName,                 /* Destination database name */
6178  sqlite3 *pSource,                      /* Source database handle */
6179  const char *zSourceName                /* Source database name */
6180);
6181SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6182SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6183SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6184SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6185
6186/*
6187** CAPI3REF: Unlock Notification
6188**
6189** ^When running in shared-cache mode, a database operation may fail with
6190** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6191** individual tables within the shared-cache cannot be obtained. See
6192** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6193** ^This API may be used to register a callback that SQLite will invoke
6194** when the connection currently holding the required lock relinquishes it.
6195** ^This API is only available if the library was compiled with the
6196** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6197**
6198** See Also: [Using the SQLite Unlock Notification Feature].
6199**
6200** ^Shared-cache locks are released when a database connection concludes
6201** its current transaction, either by committing it or rolling it back.
6202**
6203** ^When a connection (known as the blocked connection) fails to obtain a
6204** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6205** identity of the database connection (the blocking connection) that
6206** has locked the required resource is stored internally. ^After an
6207** application receives an SQLITE_LOCKED error, it may call the
6208** sqlite3_unlock_notify() method with the blocked connection handle as
6209** the first argument to register for a callback that will be invoked
6210** when the blocking connections current transaction is concluded. ^The
6211** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6212** call that concludes the blocking connections transaction.
6213**
6214** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6215** there is a chance that the blocking connection will have already
6216** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6217** If this happens, then the specified callback is invoked immediately,
6218** from within the call to sqlite3_unlock_notify().)^
6219**
6220** ^If the blocked connection is attempting to obtain a write-lock on a
6221** shared-cache table, and more than one other connection currently holds
6222** a read-lock on the same table, then SQLite arbitrarily selects one of
6223** the other connections to use as the blocking connection.
6224**
6225** ^(There may be at most one unlock-notify callback registered by a
6226** blocked connection. If sqlite3_unlock_notify() is called when the
6227** blocked connection already has a registered unlock-notify callback,
6228** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6229** called with a NULL pointer as its second argument, then any existing
6230** unlock-notify callback is cancelled. ^The blocked connections
6231** unlock-notify callback may also be canceled by closing the blocked
6232** connection using [sqlite3_close()].
6233**
6234** The unlock-notify callback is not reentrant. If an application invokes
6235** any sqlite3_xxx API functions from within an unlock-notify callback, a
6236** crash or deadlock may be the result.
6237**
6238** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6239** returns SQLITE_OK.
6240**
6241** <b>Callback Invocation Details</b>
6242**
6243** When an unlock-notify callback is registered, the application provides a
6244** single void* pointer that is passed to the callback when it is invoked.
6245** However, the signature of the callback function allows SQLite to pass
6246** it an array of void* context pointers. The first argument passed to
6247** an unlock-notify callback is a pointer to an array of void* pointers,
6248** and the second is the number of entries in the array.
6249**
6250** When a blocking connections transaction is concluded, there may be
6251** more than one blocked connection that has registered for an unlock-notify
6252** callback. ^If two or more such blocked connections have specified the
6253** same callback function, then instead of invoking the callback function
6254** multiple times, it is invoked once with the set of void* context pointers
6255** specified by the blocked connections bundled together into an array.
6256** This gives the application an opportunity to prioritize any actions
6257** related to the set of unblocked database connections.
6258**
6259** <b>Deadlock Detection</b>
6260**
6261** Assuming that after registering for an unlock-notify callback a
6262** database waits for the callback to be issued before taking any further
6263** action (a reasonable assumption), then using this API may cause the
6264** application to deadlock. For example, if connection X is waiting for
6265** connection Y's transaction to be concluded, and similarly connection
6266** Y is waiting on connection X's transaction, then neither connection
6267** will proceed and the system may remain deadlocked indefinitely.
6268**
6269** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6270** detection. ^If a given call to sqlite3_unlock_notify() would put the
6271** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6272** unlock-notify callback is registered. The system is said to be in
6273** a deadlocked state if connection A has registered for an unlock-notify
6274** callback on the conclusion of connection B's transaction, and connection
6275** B has itself registered for an unlock-notify callback when connection
6276** A's transaction is concluded. ^Indirect deadlock is also detected, so
6277** the system is also considered to be deadlocked if connection B has
6278** registered for an unlock-notify callback on the conclusion of connection
6279** C's transaction, where connection C is waiting on connection A. ^Any
6280** number of levels of indirection are allowed.
6281**
6282** <b>The "DROP TABLE" Exception</b>
6283**
6284** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6285** always appropriate to call sqlite3_unlock_notify(). There is however,
6286** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6287** SQLite checks if there are any currently executing SELECT statements
6288** that belong to the same connection. If there are, SQLITE_LOCKED is
6289** returned. In this case there is no "blocking connection", so invoking
6290** sqlite3_unlock_notify() results in the unlock-notify callback being
6291** invoked immediately. If the application then re-attempts the "DROP TABLE"
6292** or "DROP INDEX" query, an infinite loop might be the result.
6293**
6294** One way around this problem is to check the extended error code returned
6295** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6296** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6297** the special "DROP TABLE/INDEX" case, the extended error code is just
6298** SQLITE_LOCKED.)^
6299*/
6300SQLITE_API int sqlite3_unlock_notify(
6301  sqlite3 *pBlocked,                          /* Waiting connection */
6302  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6303  void *pNotifyArg                            /* Argument to pass to xNotify */
6304);
6305
6306
6307/*
6308** CAPI3REF: String Comparison
6309**
6310** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6311** compare the contents of two buffers containing UTF-8 strings in a
6312** case-indendent fashion, using the same definition of case independence
6313** that SQLite uses internally when comparing identifiers.
6314*/
6315SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6316
6317/*
6318** CAPI3REF: Error Logging Interface
6319**
6320** ^The [sqlite3_log()] interface writes a message into the error log
6321** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6322** ^If logging is enabled, the zFormat string and subsequent arguments are
6323** used with [sqlite3_snprintf()] to generate the final output string.
6324**
6325** The sqlite3_log() interface is intended for use by extensions such as
6326** virtual tables, collating functions, and SQL functions.  While there is
6327** nothing to prevent an application from calling sqlite3_log(), doing so
6328** is considered bad form.
6329**
6330** The zFormat string must not be NULL.
6331**
6332** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6333** will not use dynamically allocated memory.  The log message is stored in
6334** a fixed-length buffer on the stack.  If the log message is longer than
6335** a few hundred characters, it will be truncated to the length of the
6336** buffer.
6337*/
6338SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6339
6340/*
6341** CAPI3REF: Write-Ahead Log Commit Hook
6342**
6343** ^The [sqlite3_wal_hook()] function is used to register a callback that
6344** will be invoked each time a database connection commits data to a
6345** [write-ahead log] (i.e. whenever a transaction is committed in
6346** [journal_mode | journal_mode=WAL mode]).
6347**
6348** ^The callback is invoked by SQLite after the commit has taken place and
6349** the associated write-lock on the database released, so the implementation
6350** may read, write or [checkpoint] the database as required.
6351**
6352** ^The first parameter passed to the callback function when it is invoked
6353** is a copy of the third parameter passed to sqlite3_wal_hook() when
6354** registering the callback. ^The second is a copy of the database handle.
6355** ^The third parameter is the name of the database that was written to -
6356** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6357** is the number of pages currently in the write-ahead log file,
6358** including those that were just committed.
6359**
6360** The callback function should normally return [SQLITE_OK].  ^If an error
6361** code is returned, that error will propagate back up through the
6362** SQLite code base to cause the statement that provoked the callback
6363** to report an error, though the commit will have still occurred. If the
6364** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6365** that does not correspond to any valid SQLite error code, the results
6366** are undefined.
6367**
6368** A single database handle may have at most a single write-ahead log callback
6369** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6370** previously registered write-ahead log callback. ^Note that the
6371** [sqlite3_wal_autocheckpoint()] interface and the
6372** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6373** those overwrite any prior [sqlite3_wal_hook()] settings.
6374*/
6375SQLITE_API void *sqlite3_wal_hook(
6376  sqlite3*,
6377  int(*)(void *,sqlite3*,const char*,int),
6378  void*
6379);
6380
6381/*
6382** CAPI3REF: Configure an auto-checkpoint
6383**
6384** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6385** [sqlite3_wal_hook()] that causes any database on [database connection] D
6386** to automatically [checkpoint]
6387** after committing a transaction if there are N or
6388** more frames in the [write-ahead log] file.  ^Passing zero or
6389** a negative value as the nFrame parameter disables automatic
6390** checkpoints entirely.
6391**
6392** ^The callback registered by this function replaces any existing callback
6393** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6394** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6395** configured by this function.
6396**
6397** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6398** from SQL.
6399**
6400** ^Every new [database connection] defaults to having the auto-checkpoint
6401** enabled with a threshold of 1000 pages.  The use of this interface
6402** is only necessary if the default setting is found to be suboptimal
6403** for a particular application.
6404*/
6405SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6406
6407/*
6408** CAPI3REF: Checkpoint a database
6409**
6410** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6411** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6412** empty string, then a checkpoint is run on all databases of
6413** connection D.  ^If the database connection D is not in
6414** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6415**
6416** ^The [wal_checkpoint pragma] can be used to invoke this interface
6417** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6418** [wal_autocheckpoint pragma] can be used to cause this interface to be
6419** run whenever the WAL reaches a certain size threshold.
6420*/
6421SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6422
6423/*
6424** Undo the hack that converts floating point types to integer for
6425** builds on processors without floating point support.
6426*/
6427#ifdef SQLITE_OMIT_FLOATING_POINT
6428# undef double
6429#endif
6430
6431#if 0
6432}  /* End of the 'extern "C"' block */
6433#endif
6434#endif
6435
6436
6437/************** End of sqlite3.h *********************************************/
6438/************** Continuing where we left off in sqliteInt.h ******************/
6439/************** Include hash.h in the middle of sqliteInt.h ******************/
6440/************** Begin file hash.h ********************************************/
6441/*
6442** 2001 September 22
6443**
6444** The author disclaims copyright to this source code.  In place of
6445** a legal notice, here is a blessing:
6446**
6447**    May you do good and not evil.
6448**    May you find forgiveness for yourself and forgive others.
6449**    May you share freely, never taking more than you give.
6450**
6451*************************************************************************
6452** This is the header file for the generic hash-table implemenation
6453** used in SQLite.
6454*/
6455#ifndef _SQLITE_HASH_H_
6456#define _SQLITE_HASH_H_
6457
6458/* Forward declarations of structures. */
6459typedef struct Hash Hash;
6460typedef struct HashElem HashElem;
6461
6462/* A complete hash table is an instance of the following structure.
6463** The internals of this structure are intended to be opaque -- client
6464** code should not attempt to access or modify the fields of this structure
6465** directly.  Change this structure only by using the routines below.
6466** However, some of the "procedures" and "functions" for modifying and
6467** accessing this structure are really macros, so we can't really make
6468** this structure opaque.
6469**
6470** All elements of the hash table are on a single doubly-linked list.
6471** Hash.first points to the head of this list.
6472**
6473** There are Hash.htsize buckets.  Each bucket points to a spot in
6474** the global doubly-linked list.  The contents of the bucket are the
6475** element pointed to plus the next _ht.count-1 elements in the list.
6476**
6477** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6478** by a linear search of the global list.  For small tables, the
6479** Hash.ht table is never allocated because if there are few elements
6480** in the table, it is faster to do a linear search than to manage
6481** the hash table.
6482*/
6483struct Hash {
6484  unsigned int htsize;      /* Number of buckets in the hash table */
6485  unsigned int count;       /* Number of entries in this table */
6486  HashElem *first;          /* The first element of the array */
6487  struct _ht {              /* the hash table */
6488    int count;                 /* Number of entries with this hash */
6489    HashElem *chain;           /* Pointer to first entry with this hash */
6490  } *ht;
6491};
6492
6493/* Each element in the hash table is an instance of the following
6494** structure.  All elements are stored on a single doubly-linked list.
6495**
6496** Again, this structure is intended to be opaque, but it can't really
6497** be opaque because it is used by macros.
6498*/
6499struct HashElem {
6500  HashElem *next, *prev;       /* Next and previous elements in the table */
6501  void *data;                  /* Data associated with this element */
6502  const char *pKey; int nKey;  /* Key associated with this element */
6503};
6504
6505/*
6506** Access routines.  To delete, insert a NULL pointer.
6507*/
6508SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6509SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6510SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6511SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6512
6513/*
6514** Macros for looping over all elements of a hash table.  The idiom is
6515** like this:
6516**
6517**   Hash h;
6518**   HashElem *p;
6519**   ...
6520**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6521**     SomeStructure *pData = sqliteHashData(p);
6522**     // do something with pData
6523**   }
6524*/
6525#define sqliteHashFirst(H)  ((H)->first)
6526#define sqliteHashNext(E)   ((E)->next)
6527#define sqliteHashData(E)   ((E)->data)
6528/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6529/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6530
6531/*
6532** Number of entries in a hash table
6533*/
6534/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6535
6536#endif /* _SQLITE_HASH_H_ */
6537
6538/************** End of hash.h ************************************************/
6539/************** Continuing where we left off in sqliteInt.h ******************/
6540/************** Include parse.h in the middle of sqliteInt.h *****************/
6541/************** Begin file parse.h *******************************************/
6542#define TK_SEMI                            1
6543#define TK_EXPLAIN                         2
6544#define TK_QUERY                           3
6545#define TK_PLAN                            4
6546#define TK_BEGIN                           5
6547#define TK_TRANSACTION                     6
6548#define TK_DEFERRED                        7
6549#define TK_IMMEDIATE                       8
6550#define TK_EXCLUSIVE                       9
6551#define TK_COMMIT                         10
6552#define TK_END                            11
6553#define TK_ROLLBACK                       12
6554#define TK_SAVEPOINT                      13
6555#define TK_RELEASE                        14
6556#define TK_TO                             15
6557#define TK_TABLE                          16
6558#define TK_CREATE                         17
6559#define TK_IF                             18
6560#define TK_NOT                            19
6561#define TK_EXISTS                         20
6562#define TK_TEMP                           21
6563#define TK_LP                             22
6564#define TK_RP                             23
6565#define TK_AS                             24
6566#define TK_COMMA                          25
6567#define TK_ID                             26
6568#define TK_INDEXED                        27
6569#define TK_ABORT                          28
6570#define TK_ACTION                         29
6571#define TK_AFTER                          30
6572#define TK_ANALYZE                        31
6573#define TK_ASC                            32
6574#define TK_ATTACH                         33
6575#define TK_BEFORE                         34
6576#define TK_BY                             35
6577#define TK_CASCADE                        36
6578#define TK_CAST                           37
6579#define TK_COLUMNKW                       38
6580#define TK_CONFLICT                       39
6581#define TK_DATABASE                       40
6582#define TK_DESC                           41
6583#define TK_DETACH                         42
6584#define TK_EACH                           43
6585#define TK_FAIL                           44
6586#define TK_FOR                            45
6587#define TK_IGNORE                         46
6588#define TK_INITIALLY                      47
6589#define TK_INSTEAD                        48
6590#define TK_LIKE_KW                        49
6591#define TK_MATCH                          50
6592#define TK_NO                             51
6593#define TK_KEY                            52
6594#define TK_OF                             53
6595#define TK_OFFSET                         54
6596#define TK_PRAGMA                         55
6597#define TK_RAISE                          56
6598#define TK_REPLACE                        57
6599#define TK_RESTRICT                       58
6600#define TK_ROW                            59
6601#define TK_TRIGGER                        60
6602#define TK_VACUUM                         61
6603#define TK_VIEW                           62
6604#define TK_VIRTUAL                        63
6605#define TK_REINDEX                        64
6606#define TK_RENAME                         65
6607#define TK_CTIME_KW                       66
6608#define TK_ANY                            67
6609#define TK_OR                             68
6610#define TK_AND                            69
6611#define TK_IS                             70
6612#define TK_BETWEEN                        71
6613#define TK_IN                             72
6614#define TK_ISNULL                         73
6615#define TK_NOTNULL                        74
6616#define TK_NE                             75
6617#define TK_EQ                             76
6618#define TK_GT                             77
6619#define TK_LE                             78
6620#define TK_LT                             79
6621#define TK_GE                             80
6622#define TK_ESCAPE                         81
6623#define TK_BITAND                         82
6624#define TK_BITOR                          83
6625#define TK_LSHIFT                         84
6626#define TK_RSHIFT                         85
6627#define TK_PLUS                           86
6628#define TK_MINUS                          87
6629#define TK_STAR                           88
6630#define TK_SLASH                          89
6631#define TK_REM                            90
6632#define TK_CONCAT                         91
6633#define TK_COLLATE                        92
6634#define TK_BITNOT                         93
6635#define TK_STRING                         94
6636#define TK_JOIN_KW                        95
6637#define TK_CONSTRAINT                     96
6638#define TK_DEFAULT                        97
6639#define TK_NULL                           98
6640#define TK_PRIMARY                        99
6641#define TK_UNIQUE                         100
6642#define TK_CHECK                          101
6643#define TK_REFERENCES                     102
6644#define TK_AUTOINCR                       103
6645#define TK_ON                             104
6646#define TK_INSERT                         105
6647#define TK_DELETE                         106
6648#define TK_UPDATE                         107
6649#define TK_SET                            108
6650#define TK_DEFERRABLE                     109
6651#define TK_FOREIGN                        110
6652#define TK_DROP                           111
6653#define TK_UNION                          112
6654#define TK_ALL                            113
6655#define TK_EXCEPT                         114
6656#define TK_INTERSECT                      115
6657#define TK_SELECT                         116
6658#define TK_DISTINCT                       117
6659#define TK_DOT                            118
6660#define TK_FROM                           119
6661#define TK_JOIN                           120
6662#define TK_USING                          121
6663#define TK_ORDER                          122
6664#define TK_GROUP                          123
6665#define TK_HAVING                         124
6666#define TK_LIMIT                          125
6667#define TK_WHERE                          126
6668#define TK_INTO                           127
6669#define TK_VALUES                         128
6670#define TK_INTEGER                        129
6671#define TK_FLOAT                          130
6672#define TK_BLOB                           131
6673#define TK_REGISTER                       132
6674#define TK_VARIABLE                       133
6675#define TK_CASE                           134
6676#define TK_WHEN                           135
6677#define TK_THEN                           136
6678#define TK_ELSE                           137
6679#define TK_INDEX                          138
6680#define TK_ALTER                          139
6681#define TK_ADD                            140
6682#define TK_TO_TEXT                        141
6683#define TK_TO_BLOB                        142
6684#define TK_TO_NUMERIC                     143
6685#define TK_TO_INT                         144
6686#define TK_TO_REAL                        145
6687#define TK_ISNOT                          146
6688#define TK_END_OF_FILE                    147
6689#define TK_ILLEGAL                        148
6690#define TK_SPACE                          149
6691#define TK_UNCLOSED_STRING                150
6692#define TK_FUNCTION                       151
6693#define TK_COLUMN                         152
6694#define TK_AGG_FUNCTION                   153
6695#define TK_AGG_COLUMN                     154
6696#define TK_CONST_FUNC                     155
6697#define TK_UMINUS                         156
6698#define TK_UPLUS                          157
6699
6700/************** End of parse.h ***********************************************/
6701/************** Continuing where we left off in sqliteInt.h ******************/
6702#include <stdio.h>
6703#include <stdlib.h>
6704#include <string.h>
6705#include <assert.h>
6706#include <stddef.h>
6707
6708/*
6709** If compiling for a processor that lacks floating point support,
6710** substitute integer for floating-point
6711*/
6712#ifdef SQLITE_OMIT_FLOATING_POINT
6713# define double sqlite_int64
6714# define float sqlite_int64
6715# define LONGDOUBLE_TYPE sqlite_int64
6716# ifndef SQLITE_BIG_DBL
6717#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6718# endif
6719# define SQLITE_OMIT_DATETIME_FUNCS 1
6720# define SQLITE_OMIT_TRACE 1
6721# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6722# undef SQLITE_HAVE_ISNAN
6723#endif
6724#ifndef SQLITE_BIG_DBL
6725# define SQLITE_BIG_DBL (1e99)
6726#endif
6727
6728/*
6729** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6730** afterward. Having this macro allows us to cause the C compiler
6731** to omit code used by TEMP tables without messy #ifndef statements.
6732*/
6733#ifdef SQLITE_OMIT_TEMPDB
6734#define OMIT_TEMPDB 1
6735#else
6736#define OMIT_TEMPDB 0
6737#endif
6738
6739/*
6740** The "file format" number is an integer that is incremented whenever
6741** the VDBE-level file format changes.  The following macros define the
6742** the default file format for new databases and the maximum file format
6743** that the library can read.
6744*/
6745#define SQLITE_MAX_FILE_FORMAT 4
6746#ifndef SQLITE_DEFAULT_FILE_FORMAT
6747# define SQLITE_DEFAULT_FILE_FORMAT 1
6748#endif
6749
6750/*
6751** Determine whether triggers are recursive by default.  This can be
6752** changed at run-time using a pragma.
6753*/
6754#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6755# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6756#endif
6757
6758/*
6759** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6760** on the command-line
6761*/
6762#ifndef SQLITE_TEMP_STORE
6763# define SQLITE_TEMP_STORE 1
6764#endif
6765
6766/*
6767** GCC does not define the offsetof() macro so we'll have to do it
6768** ourselves.
6769*/
6770#ifndef offsetof
6771#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6772#endif
6773
6774/*
6775** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6776** not, there are still machines out there that use EBCDIC.)
6777*/
6778#if 'A' == '\301'
6779# define SQLITE_EBCDIC 1
6780#else
6781# define SQLITE_ASCII 1
6782#endif
6783
6784/*
6785** Integers of known sizes.  These typedefs might change for architectures
6786** where the sizes very.  Preprocessor macros are available so that the
6787** types can be conveniently redefined at compile-type.  Like this:
6788**
6789**         cc '-DUINTPTR_TYPE=long long int' ...
6790*/
6791#ifndef UINT32_TYPE
6792# ifdef HAVE_UINT32_T
6793#  define UINT32_TYPE uint32_t
6794# else
6795#  define UINT32_TYPE unsigned int
6796# endif
6797#endif
6798#ifndef UINT16_TYPE
6799# ifdef HAVE_UINT16_T
6800#  define UINT16_TYPE uint16_t
6801# else
6802#  define UINT16_TYPE unsigned short int
6803# endif
6804#endif
6805#ifndef INT16_TYPE
6806# ifdef HAVE_INT16_T
6807#  define INT16_TYPE int16_t
6808# else
6809#  define INT16_TYPE short int
6810# endif
6811#endif
6812#ifndef UINT8_TYPE
6813# ifdef HAVE_UINT8_T
6814#  define UINT8_TYPE uint8_t
6815# else
6816#  define UINT8_TYPE unsigned char
6817# endif
6818#endif
6819#ifndef INT8_TYPE
6820# ifdef HAVE_INT8_T
6821#  define INT8_TYPE int8_t
6822# else
6823#  define INT8_TYPE signed char
6824# endif
6825#endif
6826#ifndef LONGDOUBLE_TYPE
6827# define LONGDOUBLE_TYPE long double
6828#endif
6829typedef sqlite_int64 i64;          /* 8-byte signed integer */
6830typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6831typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6832typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6833typedef INT16_TYPE i16;            /* 2-byte signed integer */
6834typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6835typedef INT8_TYPE i8;              /* 1-byte signed integer */
6836
6837/*
6838** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6839** that can be stored in a u32 without loss of data.  The value
6840** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6841** have to specify the value in the less intuitive manner shown:
6842*/
6843#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6844
6845/*
6846** Macros to determine whether the machine is big or little endian,
6847** evaluated at runtime.
6848*/
6849#ifdef SQLITE_AMALGAMATION
6850SQLITE_PRIVATE const int sqlite3one = 1;
6851#else
6852SQLITE_PRIVATE const int sqlite3one;
6853#endif
6854#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6855                             || defined(__x86_64) || defined(__x86_64__)
6856# define SQLITE_BIGENDIAN    0
6857# define SQLITE_LITTLEENDIAN 1
6858# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6859#else
6860# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6861# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6862# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6863#endif
6864
6865/*
6866** Constants for the largest and smallest possible 64-bit signed integers.
6867** These macros are designed to work correctly on both 32-bit and 64-bit
6868** compilers.
6869*/
6870#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6871#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6872
6873/*
6874** Round up a number to the next larger multiple of 8.  This is used
6875** to force 8-byte alignment on 64-bit architectures.
6876*/
6877#define ROUND8(x)     (((x)+7)&~7)
6878
6879/*
6880** Round down to the nearest multiple of 8
6881*/
6882#define ROUNDDOWN8(x) ((x)&~7)
6883
6884/*
6885** Assert that the pointer X is aligned to an 8-byte boundary.  This
6886** macro is used only within assert() to verify that the code gets
6887** all alignment restrictions correct.
6888**
6889** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6890** underlying malloc() implemention might return us 4-byte aligned
6891** pointers.  In that case, only verify 4-byte alignment.
6892*/
6893#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6894# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6895#else
6896# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6897#endif
6898
6899
6900/*
6901** An instance of the following structure is used to store the busy-handler
6902** callback for a given sqlite handle.
6903**
6904** The sqlite.busyHandler member of the sqlite struct contains the busy
6905** callback for the database handle. Each pager opened via the sqlite
6906** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6907** callback is currently invoked only from within pager.c.
6908*/
6909typedef struct BusyHandler BusyHandler;
6910struct BusyHandler {
6911  int (*xFunc)(void *,int);  /* The busy callback */
6912  void *pArg;                /* First arg to busy callback */
6913  int nBusy;                 /* Incremented with each busy call */
6914};
6915
6916/*
6917** Name of the master database table.  The master database table
6918** is a special table that holds the names and attributes of all
6919** user tables and indices.
6920*/
6921#define MASTER_NAME       "sqlite_master"
6922#define TEMP_MASTER_NAME  "sqlite_temp_master"
6923
6924/*
6925** The root-page of the master database table.
6926*/
6927#define MASTER_ROOT       1
6928
6929/*
6930** The name of the schema table.
6931*/
6932#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6933
6934/*
6935** A convenience macro that returns the number of elements in
6936** an array.
6937*/
6938#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6939
6940/*
6941** The following value as a destructor means to use sqlite3DbFree().
6942** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6943*/
6944#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6945
6946/*
6947** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6948** not support Writable Static Data (WSD) such as global and static variables.
6949** All variables must either be on the stack or dynamically allocated from
6950** the heap.  When WSD is unsupported, the variable declarations scattered
6951** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6952** macro is used for this purpose.  And instead of referencing the variable
6953** directly, we use its constant as a key to lookup the run-time allocated
6954** buffer that holds real variable.  The constant is also the initializer
6955** for the run-time allocated buffer.
6956**
6957** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6958** macros become no-ops and have zero performance impact.
6959*/
6960#ifdef SQLITE_OMIT_WSD
6961  #define SQLITE_WSD const
6962  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6963  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6964SQLITE_API   int sqlite3_wsd_init(int N, int J);
6965SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6966#else
6967  #define SQLITE_WSD
6968  #define GLOBAL(t,v) v
6969  #define sqlite3GlobalConfig sqlite3Config
6970#endif
6971
6972/*
6973** The following macros are used to suppress compiler warnings and to
6974** make it clear to human readers when a function parameter is deliberately
6975** left unused within the body of a function. This usually happens when
6976** a function is called via a function pointer. For example the
6977** implementation of an SQL aggregate step callback may not use the
6978** parameter indicating the number of arguments passed to the aggregate,
6979** if it knows that this is enforced elsewhere.
6980**
6981** When a function parameter is not used at all within the body of a function,
6982** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6983** However, these macros may also be used to suppress warnings related to
6984** parameters that may or may not be used depending on compilation options.
6985** For example those parameters only used in assert() statements. In these
6986** cases the parameters are named as per the usual conventions.
6987*/
6988#define UNUSED_PARAMETER(x) (void)(x)
6989#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6990
6991/*
6992** Forward references to structures
6993*/
6994typedef struct AggInfo AggInfo;
6995typedef struct AuthContext AuthContext;
6996typedef struct AutoincInfo AutoincInfo;
6997typedef struct Bitvec Bitvec;
6998typedef struct CollSeq CollSeq;
6999typedef struct Column Column;
7000typedef struct Db Db;
7001typedef struct Schema Schema;
7002typedef struct Expr Expr;
7003typedef struct ExprList ExprList;
7004typedef struct ExprSpan ExprSpan;
7005typedef struct FKey FKey;
7006typedef struct FuncDef FuncDef;
7007typedef struct FuncDefHash FuncDefHash;
7008typedef struct IdList IdList;
7009typedef struct Index Index;
7010typedef struct IndexSample IndexSample;
7011typedef struct KeyClass KeyClass;
7012typedef struct KeyInfo KeyInfo;
7013typedef struct Lookaside Lookaside;
7014typedef struct LookasideSlot LookasideSlot;
7015typedef struct Module Module;
7016typedef struct NameContext NameContext;
7017typedef struct Parse Parse;
7018typedef struct RowSet RowSet;
7019typedef struct Savepoint Savepoint;
7020typedef struct Select Select;
7021typedef struct SrcList SrcList;
7022typedef struct StrAccum StrAccum;
7023typedef struct Table Table;
7024typedef struct TableLock TableLock;
7025typedef struct Token Token;
7026typedef struct Trigger Trigger;
7027typedef struct TriggerPrg TriggerPrg;
7028typedef struct TriggerStep TriggerStep;
7029typedef struct UnpackedRecord UnpackedRecord;
7030typedef struct VTable VTable;
7031typedef struct Walker Walker;
7032typedef struct WherePlan WherePlan;
7033typedef struct WhereInfo WhereInfo;
7034typedef struct WhereLevel WhereLevel;
7035
7036/*
7037** Defer sourcing vdbe.h and btree.h until after the "u8" and
7038** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7039** pointer types (i.e. FuncDef) defined above.
7040*/
7041/************** Include btree.h in the middle of sqliteInt.h *****************/
7042/************** Begin file btree.h *******************************************/
7043/*
7044** 2001 September 15
7045**
7046** The author disclaims copyright to this source code.  In place of
7047** a legal notice, here is a blessing:
7048**
7049**    May you do good and not evil.
7050**    May you find forgiveness for yourself and forgive others.
7051**    May you share freely, never taking more than you give.
7052**
7053*************************************************************************
7054** This header file defines the interface that the sqlite B-Tree file
7055** subsystem.  See comments in the source code for a detailed description
7056** of what each interface routine does.
7057*/
7058#ifndef _BTREE_H_
7059#define _BTREE_H_
7060
7061/* TODO: This definition is just included so other modules compile. It
7062** needs to be revisited.
7063*/
7064#define SQLITE_N_BTREE_META 10
7065
7066/*
7067** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7068** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7069*/
7070#ifndef SQLITE_DEFAULT_AUTOVACUUM
7071  #define SQLITE_DEFAULT_AUTOVACUUM 0
7072#endif
7073
7074#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7075#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7076#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7077
7078/*
7079** Forward declarations of structure
7080*/
7081typedef struct Btree Btree;
7082typedef struct BtCursor BtCursor;
7083typedef struct BtShared BtShared;
7084typedef struct BtreeMutexArray BtreeMutexArray;
7085
7086/*
7087** This structure records all of the Btrees that need to hold
7088** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7089** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7090** we can always lock and unlock them all quickly.
7091*/
7092struct BtreeMutexArray {
7093  int nMutex;
7094  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7095};
7096
7097
7098SQLITE_PRIVATE int sqlite3BtreeOpen(
7099  const char *zFilename,   /* Name of database file to open */
7100  sqlite3 *db,             /* Associated database connection */
7101  Btree **ppBtree,         /* Return open Btree* here */
7102  int flags,               /* Flags */
7103  int vfsFlags             /* Flags passed through to VFS open */
7104);
7105
7106/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7107** following values.
7108**
7109** NOTE:  These values must match the corresponding PAGER_ values in
7110** pager.h.
7111*/
7112#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7113#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7114#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7115#define BTREE_READONLY      8  /* Open the database in read-only mode */
7116#define BTREE_READWRITE    16  /* Open for both reading and writing */
7117#define BTREE_CREATE       32  /* Create the database if it does not exist */
7118
7119SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7120SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7121SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7122SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7123SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7124SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7125SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7126SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7127SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7128SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7129SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7130SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7131SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7132SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7133SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7134SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7135SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7136SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7137SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7138SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7139SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7140SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7141SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7142SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7143SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7144SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7145
7146SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7147SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7148SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7149
7150SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7151
7152/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7153** of the following flags:
7154*/
7155#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7156#define BTREE_ZERODATA   2    /* Table has keys only - no data */
7157#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7158
7159SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7160SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7161SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7162
7163SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7164SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7165
7166/*
7167** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7168** should be one of the following values. The integer values are assigned
7169** to constants so that the offset of the corresponding field in an
7170** SQLite database header may be found using the following formula:
7171**
7172**   offset = 36 + (idx * 4)
7173**
7174** For example, the free-page-count field is located at byte offset 36 of
7175** the database file header. The incr-vacuum-flag field is located at
7176** byte offset 64 (== 36+4*7).
7177*/
7178#define BTREE_FREE_PAGE_COUNT     0
7179#define BTREE_SCHEMA_VERSION      1
7180#define BTREE_FILE_FORMAT         2
7181#define BTREE_DEFAULT_CACHE_SIZE  3
7182#define BTREE_LARGEST_ROOT_PAGE   4
7183#define BTREE_TEXT_ENCODING       5
7184#define BTREE_USER_VERSION        6
7185#define BTREE_INCR_VACUUM         7
7186
7187SQLITE_PRIVATE int sqlite3BtreeCursor(
7188  Btree*,                              /* BTree containing table to open */
7189  int iTable,                          /* Index of root page */
7190  int wrFlag,                          /* 1 for writing.  0 for read-only */
7191  struct KeyInfo*,                     /* First argument to compare function */
7192  BtCursor *pCursor                    /* Space to write cursor structure */
7193);
7194SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7195SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7196
7197SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7198SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7199  BtCursor*,
7200  UnpackedRecord *pUnKey,
7201  i64 intKey,
7202  int bias,
7203  int *pRes
7204);
7205SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7206SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7207SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7208                                  const void *pData, int nData,
7209                                  int nZero, int bias, int seekResult);
7210SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7211SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7212SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7213SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7214SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7215SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7216SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7217SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7218SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7219SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7220SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7221SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7222SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7223
7224SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7225SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7226
7227SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7228SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7229SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7230
7231SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7232
7233#ifndef NDEBUG
7234SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7235#endif
7236
7237#ifndef SQLITE_OMIT_BTREECOUNT
7238SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7239#endif
7240
7241#ifdef SQLITE_TEST
7242SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7243SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7244#endif
7245
7246/*
7247** If we are not using shared cache, then there is no need to
7248** use mutexes to access the BtShared structures.  So make the
7249** Enter and Leave procedures no-ops.
7250*/
7251#ifndef SQLITE_OMIT_SHARED_CACHE
7252SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7253SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7254#else
7255# define sqlite3BtreeEnter(X)
7256# define sqlite3BtreeEnterAll(X)
7257#endif
7258
7259#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7260SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7261SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7262SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7263SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7264SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7265SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7266SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7267#ifndef NDEBUG
7268  /* These routines are used inside assert() statements only. */
7269SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7270SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7271#endif
7272#else
7273
7274# define sqlite3BtreeLeave(X)
7275# define sqlite3BtreeEnterCursor(X)
7276# define sqlite3BtreeLeaveCursor(X)
7277# define sqlite3BtreeLeaveAll(X)
7278# define sqlite3BtreeMutexArrayEnter(X)
7279# define sqlite3BtreeMutexArrayLeave(X)
7280# define sqlite3BtreeMutexArrayInsert(X,Y)
7281
7282# define sqlite3BtreeHoldsMutex(X) 1
7283# define sqlite3BtreeHoldsAllMutexes(X) 1
7284#endif
7285
7286
7287#endif /* _BTREE_H_ */
7288
7289/************** End of btree.h ***********************************************/
7290/************** Continuing where we left off in sqliteInt.h ******************/
7291/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7292/************** Begin file vdbe.h ********************************************/
7293/*
7294** 2001 September 15
7295**
7296** The author disclaims copyright to this source code.  In place of
7297** a legal notice, here is a blessing:
7298**
7299**    May you do good and not evil.
7300**    May you find forgiveness for yourself and forgive others.
7301**    May you share freely, never taking more than you give.
7302**
7303*************************************************************************
7304** Header file for the Virtual DataBase Engine (VDBE)
7305**
7306** This header defines the interface to the virtual database engine
7307** or VDBE.  The VDBE implements an abstract machine that runs a
7308** simple program to access and modify the underlying database.
7309*/
7310#ifndef _SQLITE_VDBE_H_
7311#define _SQLITE_VDBE_H_
7312
7313/*
7314** A single VDBE is an opaque structure named "Vdbe".  Only routines
7315** in the source file sqliteVdbe.c are allowed to see the insides
7316** of this structure.
7317*/
7318typedef struct Vdbe Vdbe;
7319
7320/*
7321** The names of the following types declared in vdbeInt.h are required
7322** for the VdbeOp definition.
7323*/
7324typedef struct VdbeFunc VdbeFunc;
7325typedef struct Mem Mem;
7326typedef struct SubProgram SubProgram;
7327
7328/*
7329** A single instruction of the virtual machine has an opcode
7330** and as many as three operands.  The instruction is recorded
7331** as an instance of the following structure:
7332*/
7333struct VdbeOp {
7334  u8 opcode;          /* What operation to perform */
7335  signed char p4type; /* One of the P4_xxx constants for p4 */
7336  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7337  u8 p5;              /* Fifth parameter is an unsigned character */
7338  int p1;             /* First operand */
7339  int p2;             /* Second parameter (often the jump destination) */
7340  int p3;             /* The third parameter */
7341  union {             /* fourth parameter */
7342    int i;                 /* Integer value if p4type==P4_INT32 */
7343    void *p;               /* Generic pointer */
7344    char *z;               /* Pointer to data for string (char array) types */
7345    i64 *pI64;             /* Used when p4type is P4_INT64 */
7346    double *pReal;         /* Used when p4type is P4_REAL */
7347    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7348    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7349    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7350    Mem *pMem;             /* Used when p4type is P4_MEM */
7351    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7352    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7353    int *ai;               /* Used when p4type is P4_INTARRAY */
7354    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7355  } p4;
7356#ifdef SQLITE_DEBUG
7357  char *zComment;          /* Comment to improve readability */
7358#endif
7359#ifdef VDBE_PROFILE
7360  int cnt;                 /* Number of times this instruction was executed */
7361  u64 cycles;              /* Total time spent executing this instruction */
7362#endif
7363};
7364typedef struct VdbeOp VdbeOp;
7365
7366
7367/*
7368** A sub-routine used to implement a trigger program.
7369*/
7370struct SubProgram {
7371  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7372  int nOp;                      /* Elements in aOp[] */
7373  int nMem;                     /* Number of memory cells required */
7374  int nCsr;                     /* Number of cursors required */
7375  int nRef;                     /* Number of pointers to this structure */
7376  void *token;                  /* id that may be used to recursive triggers */
7377};
7378
7379/*
7380** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7381** it takes up less space.
7382*/
7383struct VdbeOpList {
7384  u8 opcode;          /* What operation to perform */
7385  signed char p1;     /* First operand */
7386  signed char p2;     /* Second parameter (often the jump destination) */
7387  signed char p3;     /* Third parameter */
7388};
7389typedef struct VdbeOpList VdbeOpList;
7390
7391/*
7392** Allowed values of VdbeOp.p4type
7393*/
7394#define P4_NOTUSED    0   /* The P4 parameter is not used */
7395#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7396#define P4_STATIC   (-2)  /* Pointer to a static string */
7397#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7398#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7399#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7400#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7401#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7402#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7403#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7404#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7405#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7406#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7407#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7408#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7409#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7410
7411/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7412** is made.  That copy is freed when the Vdbe is finalized.  But if the
7413** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7414** gets freed when the Vdbe is finalized so it still should be obtained
7415** from a single sqliteMalloc().  But no copy is made and the calling
7416** function should *not* try to free the KeyInfo.
7417*/
7418#define P4_KEYINFO_HANDOFF (-16)
7419#define P4_KEYINFO_STATIC  (-17)
7420
7421/*
7422** The Vdbe.aColName array contains 5n Mem structures, where n is the
7423** number of columns of data returned by the statement.
7424*/
7425#define COLNAME_NAME     0
7426#define COLNAME_DECLTYPE 1
7427#define COLNAME_DATABASE 2
7428#define COLNAME_TABLE    3
7429#define COLNAME_COLUMN   4
7430#ifdef SQLITE_ENABLE_COLUMN_METADATA
7431# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7432#else
7433# ifdef SQLITE_OMIT_DECLTYPE
7434#   define COLNAME_N      1      /* Store only the name */
7435# else
7436#   define COLNAME_N      2      /* Store the name and decltype */
7437# endif
7438#endif
7439
7440/*
7441** The following macro converts a relative address in the p2 field
7442** of a VdbeOp structure into a negative number so that
7443** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7444** the macro again restores the address.
7445*/
7446#define ADDR(X)  (-1-(X))
7447
7448/*
7449** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7450** header file that defines a number for each opcode used by the VDBE.
7451*/
7452/************** Include opcodes.h in the middle of vdbe.h ********************/
7453/************** Begin file opcodes.h *****************************************/
7454/* Automatically generated.  Do not edit */
7455/* See the mkopcodeh.awk script for details */
7456#define OP_Goto                                 1
7457#define OP_Gosub                                2
7458#define OP_Return                               3
7459#define OP_Yield                                4
7460#define OP_HaltIfNull                           5
7461#define OP_Halt                                 6
7462#define OP_Integer                              7
7463#define OP_Int64                                8
7464#define OP_Real                               130   /* same as TK_FLOAT    */
7465#define OP_String8                             94   /* same as TK_STRING   */
7466#define OP_String                               9
7467#define OP_Null                                10
7468#define OP_Blob                                11
7469#define OP_Variable                            12
7470#define OP_Move                                13
7471#define OP_Copy                                14
7472#define OP_SCopy                               15
7473#define OP_ResultRow                           16
7474#define OP_Concat                              91   /* same as TK_CONCAT   */
7475#define OP_Add                                 86   /* same as TK_PLUS     */
7476#define OP_Subtract                            87   /* same as TK_MINUS    */
7477#define OP_Multiply                            88   /* same as TK_STAR     */
7478#define OP_Divide                              89   /* same as TK_SLASH    */
7479#define OP_Remainder                           90   /* same as TK_REM      */
7480#define OP_CollSeq                             17
7481#define OP_Function                            18
7482#define OP_BitAnd                              82   /* same as TK_BITAND   */
7483#define OP_BitOr                               83   /* same as TK_BITOR    */
7484#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7485#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7486#define OP_AddImm                              20
7487#define OP_MustBeInt                           21
7488#define OP_RealAffinity                        22
7489#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7490#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7491#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7492#define OP_ToInt                              144   /* same as TK_TO_INT   */
7493#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7494#define OP_Eq                                  76   /* same as TK_EQ       */
7495#define OP_Ne                                  75   /* same as TK_NE       */
7496#define OP_Lt                                  79   /* same as TK_LT       */
7497#define OP_Le                                  78   /* same as TK_LE       */
7498#define OP_Gt                                  77   /* same as TK_GT       */
7499#define OP_Ge                                  80   /* same as TK_GE       */
7500#define OP_Permutation                         23
7501#define OP_Compare                             24
7502#define OP_Jump                                25
7503#define OP_And                                 69   /* same as TK_AND      */
7504#define OP_Or                                  68   /* same as TK_OR       */
7505#define OP_Not                                 19   /* same as TK_NOT      */
7506#define OP_BitNot                              93   /* same as TK_BITNOT   */
7507#define OP_If                                  26
7508#define OP_IfNot                               27
7509#define OP_IsNull                              73   /* same as TK_ISNULL   */
7510#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7511#define OP_Column                              28
7512#define OP_Affinity                            29
7513#define OP_MakeRecord                          30
7514#define OP_Count                               31
7515#define OP_Savepoint                           32
7516#define OP_AutoCommit                          33
7517#define OP_Transaction                         34
7518#define OP_ReadCookie                          35
7519#define OP_SetCookie                           36
7520#define OP_VerifyCookie                        37
7521#define OP_OpenRead                            38
7522#define OP_OpenWrite                           39
7523#define OP_OpenAutoindex                       40
7524#define OP_OpenEphemeral                       41
7525#define OP_OpenPseudo                          42
7526#define OP_Close                               43
7527#define OP_SeekLt                              44
7528#define OP_SeekLe                              45
7529#define OP_SeekGe                              46
7530#define OP_SeekGt                              47
7531#define OP_Seek                                48
7532#define OP_NotFound                            49
7533#define OP_Found                               50
7534#define OP_IsUnique                            51
7535#define OP_NotExists                           52
7536#define OP_Sequence                            53
7537#define OP_NewRowid                            54
7538#define OP_Insert                              55
7539#define OP_InsertInt                           56
7540#define OP_Delete                              57
7541#define OP_ResetCount                          58
7542#define OP_RowKey                              59
7543#define OP_RowData                             60
7544#define OP_Rowid                               61
7545#define OP_NullRow                             62
7546#define OP_Last                                63
7547#define OP_Sort                                64
7548#define OP_Rewind                              65
7549#define OP_Prev                                66
7550#define OP_Next                                67
7551#define OP_IdxInsert                           70
7552#define OP_IdxDelete                           71
7553#define OP_IdxRowid                            72
7554#define OP_IdxLT                               81
7555#define OP_IdxGE                               92
7556#define OP_Destroy                             95
7557#define OP_Clear                               96
7558#define OP_CreateIndex                         97
7559#define OP_CreateTable                         98
7560#define OP_ParseSchema                         99
7561#define OP_LoadAnalysis                       100
7562#define OP_DropTable                          101
7563#define OP_DropIndex                          102
7564#define OP_DropTrigger                        103
7565#define OP_IntegrityCk                        104
7566#define OP_RowSetAdd                          105
7567#define OP_RowSetRead                         106
7568#define OP_RowSetTest                         107
7569#define OP_Program                            108
7570#define OP_Param                              109
7571#define OP_FkCounter                          110
7572#define OP_FkIfZero                           111
7573#define OP_MemMax                             112
7574#define OP_IfPos                              113
7575#define OP_IfNeg                              114
7576#define OP_IfZero                             115
7577#define OP_AggStep                            116
7578#define OP_AggFinal                           117
7579#define OP_Checkpoint                         118
7580#define OP_JournalMode                        119
7581#define OP_Vacuum                             120
7582#define OP_IncrVacuum                         121
7583#define OP_Expire                             122
7584#define OP_TableLock                          123
7585#define OP_VBegin                             124
7586#define OP_VCreate                            125
7587#define OP_VDestroy                           126
7588#define OP_VOpen                              127
7589#define OP_VFilter                            128
7590#define OP_VColumn                            129
7591#define OP_VNext                              131
7592#define OP_VRename                            132
7593#define OP_VUpdate                            133
7594#define OP_Pagecount                          134
7595#define OP_Trace                              135
7596#define OP_Noop                               136
7597#define OP_Explain                            137
7598
7599/* The following opcode values are never used */
7600#define OP_NotUsed_138                        138
7601#define OP_NotUsed_139                        139
7602#define OP_NotUsed_140                        140
7603
7604
7605/* Properties such as "out2" or "jump" that are specified in
7606** comments following the "case" for each opcode in the vdbe.c
7607** are encoded into bitvectors as follows:
7608*/
7609#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7610#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7611#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7612#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7613#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7614#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7615#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7616#define OPFLG_INITIALIZER {\
7617/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7618/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7619/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7620/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7621/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7622/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7623/*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7624/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7625/*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7626/*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7627/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7628/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7629/*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7630/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7631/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7632/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7633/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7634/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7635/* 144 */ 0x04, 0x04,}
7636
7637/************** End of opcodes.h *********************************************/
7638/************** Continuing where we left off in vdbe.h ***********************/
7639
7640/*
7641** Prototypes for the VDBE interface.  See comments on the implementation
7642** for a description of what each of these routines does.
7643*/
7644SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7645SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7646SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7647SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7648SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7649SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7650SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7651SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7652SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7653SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7654SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7655SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7656SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7657SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7658SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7659SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7660SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7661SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7662SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7663SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7664SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7665SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7666SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7667SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7668#ifdef SQLITE_DEBUG
7669SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7670SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7671#endif
7672SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7673SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7674SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7675SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7676SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7677SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7678SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7679SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7680SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7681SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7682SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7683SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7684#ifndef SQLITE_OMIT_TRACE
7685SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7686#endif
7687
7688SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7689SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7690SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7691
7692
7693#ifndef NDEBUG
7694SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7695# define VdbeComment(X)  sqlite3VdbeComment X
7696SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7697# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7698#else
7699# define VdbeComment(X)
7700# define VdbeNoopComment(X)
7701#endif
7702
7703#endif
7704
7705/************** End of vdbe.h ************************************************/
7706/************** Continuing where we left off in sqliteInt.h ******************/
7707/************** Include pager.h in the middle of sqliteInt.h *****************/
7708/************** Begin file pager.h *******************************************/
7709/*
7710** 2001 September 15
7711**
7712** The author disclaims copyright to this source code.  In place of
7713** a legal notice, here is a blessing:
7714**
7715**    May you do good and not evil.
7716**    May you find forgiveness for yourself and forgive others.
7717**    May you share freely, never taking more than you give.
7718**
7719*************************************************************************
7720** This header file defines the interface that the sqlite page cache
7721** subsystem.  The page cache subsystem reads and writes a file a page
7722** at a time and provides a journal for rollback.
7723*/
7724
7725#ifndef _PAGER_H_
7726#define _PAGER_H_
7727
7728/*
7729** Default maximum size for persistent journal files. A negative
7730** value means no limit. This value may be overridden using the
7731** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7732*/
7733#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7734  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7735#endif
7736
7737/*
7738** The type used to represent a page number.  The first page in a file
7739** is called page 1.  0 is used to represent "not a page".
7740*/
7741typedef u32 Pgno;
7742
7743/*
7744** Each open file is managed by a separate instance of the "Pager" structure.
7745*/
7746typedef struct Pager Pager;
7747
7748/*
7749** Handle type for pages.
7750*/
7751typedef struct PgHdr DbPage;
7752
7753/*
7754** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7755** reserved for working around a windows/posix incompatibility). It is
7756** used in the journal to signify that the remainder of the journal file
7757** is devoted to storing a master journal name - there are no more pages to
7758** roll back. See comments for function writeMasterJournal() in pager.c
7759** for details.
7760*/
7761#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7762
7763/*
7764** Allowed values for the flags parameter to sqlite3PagerOpen().
7765**
7766** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7767*/
7768#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7769#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7770
7771/*
7772** Valid values for the second argument to sqlite3PagerLockingMode().
7773*/
7774#define PAGER_LOCKINGMODE_QUERY      -1
7775#define PAGER_LOCKINGMODE_NORMAL      0
7776#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7777
7778/*
7779** Numeric constants that encode the journalmode.
7780*/
7781#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
7782#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7783#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7784#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7785#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7786#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7787#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
7788
7789/*
7790** The remainder of this file contains the declarations of the functions
7791** that make up the Pager sub-system API. See source code comments for
7792** a detailed description of each routine.
7793*/
7794
7795/* Open and close a Pager connection. */
7796SQLITE_PRIVATE int sqlite3PagerOpen(
7797  sqlite3_vfs*,
7798  Pager **ppPager,
7799  const char*,
7800  int,
7801  int,
7802  int,
7803  void(*)(DbPage*)
7804);
7805SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7806SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7807
7808/* Functions used to configure a Pager object. */
7809SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7810SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7811SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7812SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7813SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7814SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7815SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
7816SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
7817SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
7818SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7819SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7820
7821/* Functions used to obtain and release page references. */
7822SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7823#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7824SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7825SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7826SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7827
7828/* Operations on page references. */
7829SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7830SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7831SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7832SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7833SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7834SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7835
7836/* Functions used to manage pager transactions and savepoints. */
7837SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7838SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7839SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7840SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7841SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7842SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7843SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7844SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7845SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7846
7847SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
7848SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
7849SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
7850SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
7851SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
7852
7853/* Functions used to query pager state and configuration. */
7854SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7855SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7856SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
7857SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7858SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7859SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7860SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7861SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7862SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7863SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7864
7865/* Functions used to truncate the database file. */
7866SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7867
7868#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
7869SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
7870#endif
7871
7872/* Functions to support testing and debugging. */
7873#if !defined(NDEBUG) || defined(SQLITE_TEST)
7874SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7875SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7876#endif
7877#ifdef SQLITE_TEST
7878SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7879SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7880  void disable_simulated_io_errors(void);
7881  void enable_simulated_io_errors(void);
7882#else
7883# define disable_simulated_io_errors()
7884# define enable_simulated_io_errors()
7885#endif
7886
7887#endif /* _PAGER_H_ */
7888
7889/************** End of pager.h ***********************************************/
7890/************** Continuing where we left off in sqliteInt.h ******************/
7891/************** Include pcache.h in the middle of sqliteInt.h ****************/
7892/************** Begin file pcache.h ******************************************/
7893/*
7894** 2008 August 05
7895**
7896** The author disclaims copyright to this source code.  In place of
7897** a legal notice, here is a blessing:
7898**
7899**    May you do good and not evil.
7900**    May you find forgiveness for yourself and forgive others.
7901**    May you share freely, never taking more than you give.
7902**
7903*************************************************************************
7904** This header file defines the interface that the sqlite page cache
7905** subsystem.
7906*/
7907
7908#ifndef _PCACHE_H_
7909
7910typedef struct PgHdr PgHdr;
7911typedef struct PCache PCache;
7912
7913/*
7914** Every page in the cache is controlled by an instance of the following
7915** structure.
7916*/
7917struct PgHdr {
7918  void *pData;                   /* Content of this page */
7919  void *pExtra;                  /* Extra content */
7920  PgHdr *pDirty;                 /* Transient list of dirty pages */
7921  Pgno pgno;                     /* Page number for this page */
7922  Pager *pPager;                 /* The pager this page is part of */
7923#ifdef SQLITE_CHECK_PAGES
7924  u32 pageHash;                  /* Hash of page content */
7925#endif
7926  u16 flags;                     /* PGHDR flags defined below */
7927
7928  /**********************************************************************
7929  ** Elements above are public.  All that follows is private to pcache.c
7930  ** and should not be accessed by other modules.
7931  */
7932  i16 nRef;                      /* Number of users of this page */
7933  PCache *pCache;                /* Cache that owns this page */
7934
7935  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7936  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7937};
7938
7939/* Bit values for PgHdr.flags */
7940#define PGHDR_DIRTY             0x002  /* Page has changed */
7941#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7942                                       ** writing this page to the database */
7943#define PGHDR_NEED_READ         0x008  /* Content is unread */
7944#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7945#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7946
7947/* Initialize and shutdown the page cache subsystem */
7948SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7949SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7950
7951/* Page cache buffer management:
7952** These routines implement SQLITE_CONFIG_PAGECACHE.
7953*/
7954SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7955
7956/* Create a new pager cache.
7957** Under memory stress, invoke xStress to try to make pages clean.
7958** Only clean and unpinned pages can be reclaimed.
7959*/
7960SQLITE_PRIVATE void sqlite3PcacheOpen(
7961  int szPage,                    /* Size of every page */
7962  int szExtra,                   /* Extra space associated with each page */
7963  int bPurgeable,                /* True if pages are on backing store */
7964  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7965  void *pStress,                 /* Argument to xStress */
7966  PCache *pToInit                /* Preallocated space for the PCache */
7967);
7968
7969/* Modify the page-size after the cache has been created. */
7970SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7971
7972/* Return the size in bytes of a PCache object.  Used to preallocate
7973** storage space.
7974*/
7975SQLITE_PRIVATE int sqlite3PcacheSize(void);
7976
7977/* One release per successful fetch.  Page is pinned until released.
7978** Reference counted.
7979*/
7980SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7981SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7982
7983SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7984SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7985SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7986SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7987
7988/* Change a page number.  Used by incr-vacuum. */
7989SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7990
7991/* Remove all pages with pgno>x.  Reset the cache if x==0 */
7992SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7993
7994/* Get a list of all dirty pages in the cache, sorted by page number */
7995SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7996
7997/* Reset and close the cache object */
7998SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7999
8000/* Clear flags from pages of the page cache */
8001SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8002
8003/* Discard the contents of the cache */
8004SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8005
8006/* Return the total number of outstanding page references */
8007SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8008
8009/* Increment the reference count of an existing page */
8010SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8011
8012SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8013
8014/* Return the total number of pages stored in the cache */
8015SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8016
8017#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8018/* Iterate through all dirty pages currently stored in the cache. This
8019** interface is only available if SQLITE_CHECK_PAGES is defined when the
8020** library is built.
8021*/
8022SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8023#endif
8024
8025/* Set and get the suggested cache-size for the specified pager-cache.
8026**
8027** If no global maximum is configured, then the system attempts to limit
8028** the total number of pages cached by purgeable pager-caches to the sum
8029** of the suggested cache-sizes.
8030*/
8031SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8032#ifdef SQLITE_TEST
8033SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8034#endif
8035
8036#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8037/* Try to return memory used by the pcache module to the main memory heap */
8038SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8039#endif
8040
8041#ifdef SQLITE_TEST
8042SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8043#endif
8044
8045SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8046
8047#endif /* _PCACHE_H_ */
8048
8049/************** End of pcache.h **********************************************/
8050/************** Continuing where we left off in sqliteInt.h ******************/
8051
8052/************** Include os.h in the middle of sqliteInt.h ********************/
8053/************** Begin file os.h **********************************************/
8054/*
8055** 2001 September 16
8056**
8057** The author disclaims copyright to this source code.  In place of
8058** a legal notice, here is a blessing:
8059**
8060**    May you do good and not evil.
8061**    May you find forgiveness for yourself and forgive others.
8062**    May you share freely, never taking more than you give.
8063**
8064******************************************************************************
8065**
8066** This header file (together with is companion C source-code file
8067** "os.c") attempt to abstract the underlying operating system so that
8068** the SQLite library will work on both POSIX and windows systems.
8069**
8070** This header file is #include-ed by sqliteInt.h and thus ends up
8071** being included by every source file.
8072*/
8073#ifndef _SQLITE_OS_H_
8074#define _SQLITE_OS_H_
8075
8076/*
8077** Figure out if we are dealing with Unix, Windows, or some other
8078** operating system.  After the following block of preprocess macros,
8079** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8080** will defined to either 1 or 0.  One of the four will be 1.  The other
8081** three will be 0.
8082*/
8083#if defined(SQLITE_OS_OTHER)
8084# if SQLITE_OS_OTHER==1
8085#   undef SQLITE_OS_UNIX
8086#   define SQLITE_OS_UNIX 0
8087#   undef SQLITE_OS_WIN
8088#   define SQLITE_OS_WIN 0
8089#   undef SQLITE_OS_OS2
8090#   define SQLITE_OS_OS2 0
8091# else
8092#   undef SQLITE_OS_OTHER
8093# endif
8094#endif
8095#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8096# define SQLITE_OS_OTHER 0
8097# ifndef SQLITE_OS_WIN
8098#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8099#     define SQLITE_OS_WIN 1
8100#     define SQLITE_OS_UNIX 0
8101#     define SQLITE_OS_OS2 0
8102#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8103#     define SQLITE_OS_WIN 0
8104#     define SQLITE_OS_UNIX 0
8105#     define SQLITE_OS_OS2 1
8106#   else
8107#     define SQLITE_OS_WIN 0
8108#     define SQLITE_OS_UNIX 1
8109#     define SQLITE_OS_OS2 0
8110#  endif
8111# else
8112#  define SQLITE_OS_UNIX 0
8113#  define SQLITE_OS_OS2 0
8114# endif
8115#else
8116# ifndef SQLITE_OS_WIN
8117#  define SQLITE_OS_WIN 0
8118# endif
8119#endif
8120
8121/*
8122** Determine if we are dealing with WindowsCE - which has a much
8123** reduced API.
8124*/
8125#if defined(_WIN32_WCE)
8126# define SQLITE_OS_WINCE 1
8127#else
8128# define SQLITE_OS_WINCE 0
8129#endif
8130
8131
8132/*
8133** Define the maximum size of a temporary filename
8134*/
8135#if SQLITE_OS_WIN
8136# include <windows.h>
8137# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8138#elif SQLITE_OS_OS2
8139# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8140#  include <os2safe.h> /* has to be included before os2.h for linking to work */
8141# endif
8142# define INCL_DOSDATETIME
8143# define INCL_DOSFILEMGR
8144# define INCL_DOSERRORS
8145# define INCL_DOSMISC
8146# define INCL_DOSPROCESS
8147# define INCL_DOSMODULEMGR
8148# define INCL_DOSSEMAPHORES
8149# include <os2.h>
8150# include <uconv.h>
8151# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8152#else
8153# define SQLITE_TEMPNAME_SIZE 200
8154#endif
8155
8156/* If the SET_FULLSYNC macro is not defined above, then make it
8157** a no-op
8158*/
8159#ifndef SET_FULLSYNC
8160# define SET_FULLSYNC(x,y)
8161#endif
8162
8163/*
8164** The default size of a disk sector
8165*/
8166#ifndef SQLITE_DEFAULT_SECTOR_SIZE
8167# define SQLITE_DEFAULT_SECTOR_SIZE 512
8168#endif
8169
8170/*
8171** Temporary files are named starting with this prefix followed by 16 random
8172** alphanumeric characters, and no file extension. They are stored in the
8173** OS's standard temporary file directory, and are deleted prior to exit.
8174** If sqlite is being embedded in another program, you may wish to change the
8175** prefix to reflect your program's name, so that if your program exits
8176** prematurely, old temporary files can be easily identified. This can be done
8177** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8178**
8179** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8180** Mcafee started using SQLite in their anti-virus product and it
8181** started putting files with the "sqlite" name in the c:/temp folder.
8182** This annoyed many windows users.  Those users would then do a
8183** Google search for "sqlite", find the telephone numbers of the
8184** developers and call to wake them up at night and complain.
8185** For this reason, the default name prefix is changed to be "sqlite"
8186** spelled backwards.  So the temp files are still identified, but
8187** anybody smart enough to figure out the code is also likely smart
8188** enough to know that calling the developer will not help get rid
8189** of the file.
8190*/
8191#ifndef SQLITE_TEMP_FILE_PREFIX
8192# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8193#endif
8194
8195/*
8196** The following values may be passed as the second argument to
8197** sqlite3OsLock(). The various locks exhibit the following semantics:
8198**
8199** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8200** RESERVED:  A single process may hold a RESERVED lock on a file at
8201**            any time. Other processes may hold and obtain new SHARED locks.
8202** PENDING:   A single process may hold a PENDING lock on a file at
8203**            any one time. Existing SHARED locks may persist, but no new
8204**            SHARED locks may be obtained by other processes.
8205** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8206**
8207** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8208** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8209** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8210** sqlite3OsLock().
8211*/
8212#define NO_LOCK         0
8213#define SHARED_LOCK     1
8214#define RESERVED_LOCK   2
8215#define PENDING_LOCK    3
8216#define EXCLUSIVE_LOCK  4
8217
8218/*
8219** File Locking Notes:  (Mostly about windows but also some info for Unix)
8220**
8221** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8222** those functions are not available.  So we use only LockFile() and
8223** UnlockFile().
8224**
8225** LockFile() prevents not just writing but also reading by other processes.
8226** A SHARED_LOCK is obtained by locking a single randomly-chosen
8227** byte out of a specific range of bytes. The lock byte is obtained at
8228** random so two separate readers can probably access the file at the
8229** same time, unless they are unlucky and choose the same lock byte.
8230** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8231** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8232** a single byte of the file that is designated as the reserved lock byte.
8233** A PENDING_LOCK is obtained by locking a designated byte different from
8234** the RESERVED_LOCK byte.
8235**
8236** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8237** which means we can use reader/writer locks.  When reader/writer locks
8238** are used, the lock is placed on the same range of bytes that is used
8239** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8240** will support two or more Win95 readers or two or more WinNT readers.
8241** But a single Win95 reader will lock out all WinNT readers and a single
8242** WinNT reader will lock out all other Win95 readers.
8243**
8244** The following #defines specify the range of bytes used for locking.
8245** SHARED_SIZE is the number of bytes available in the pool from which
8246** a random byte is selected for a shared lock.  The pool of bytes for
8247** shared locks begins at SHARED_FIRST.
8248**
8249** The same locking strategy and
8250** byte ranges are used for Unix.  This leaves open the possiblity of having
8251** clients on win95, winNT, and unix all talking to the same shared file
8252** and all locking correctly.  To do so would require that samba (or whatever
8253** tool is being used for file sharing) implements locks correctly between
8254** windows and unix.  I'm guessing that isn't likely to happen, but by
8255** using the same locking range we are at least open to the possibility.
8256**
8257** Locking in windows is manditory.  For this reason, we cannot store
8258** actual data in the bytes used for locking.  The pager never allocates
8259** the pages involved in locking therefore.  SHARED_SIZE is selected so
8260** that all locks will fit on a single page even at the minimum page size.
8261** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8262** is set high so that we don't have to allocate an unused page except
8263** for very large databases.  But one should test the page skipping logic
8264** by setting PENDING_BYTE low and running the entire regression suite.
8265**
8266** Changing the value of PENDING_BYTE results in a subtly incompatible
8267** file format.  Depending on how it is changed, you might not notice
8268** the incompatibility right away, even running a full regression test.
8269** The default location of PENDING_BYTE is the first byte past the
8270** 1GB boundary.
8271**
8272*/
8273#ifdef SQLITE_OMIT_WSD
8274# define PENDING_BYTE     (0x40000000)
8275#else
8276# define PENDING_BYTE      sqlite3PendingByte
8277#endif
8278#define RESERVED_BYTE     (PENDING_BYTE+1)
8279#define SHARED_FIRST      (PENDING_BYTE+2)
8280#define SHARED_SIZE       510
8281
8282/*
8283** Wrapper around OS specific sqlite3_os_init() function.
8284*/
8285SQLITE_PRIVATE int sqlite3OsInit(void);
8286
8287/*
8288** Functions for accessing sqlite3_file methods
8289*/
8290SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8291SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8292SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8293SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8294SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8295SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8296SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8297SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8298SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8299SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8300#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8301SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8302SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8303SQLITE_PRIVATE int sqlite3OsShmOpen(sqlite3_file *id);
8304SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8305SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8306SQLITE_PRIVATE int sqlite3OsShmClose(sqlite3_file *id, int);
8307SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8308
8309/*
8310** Functions for accessing sqlite3_vfs methods
8311*/
8312SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8313SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8314SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8315SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8316#ifndef SQLITE_OMIT_LOAD_EXTENSION
8317SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8318SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8319SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8320SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8321#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8322SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8323SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8324SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8325
8326/*
8327** Convenience functions for opening and closing files using
8328** sqlite3_malloc() to obtain space for the file-handle structure.
8329*/
8330SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8331SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8332
8333#endif /* _SQLITE_OS_H_ */
8334
8335/************** End of os.h **************************************************/
8336/************** Continuing where we left off in sqliteInt.h ******************/
8337/************** Include mutex.h in the middle of sqliteInt.h *****************/
8338/************** Begin file mutex.h *******************************************/
8339/*
8340** 2007 August 28
8341**
8342** The author disclaims copyright to this source code.  In place of
8343** a legal notice, here is a blessing:
8344**
8345**    May you do good and not evil.
8346**    May you find forgiveness for yourself and forgive others.
8347**    May you share freely, never taking more than you give.
8348**
8349*************************************************************************
8350**
8351** This file contains the common header for all mutex implementations.
8352** The sqliteInt.h header #includes this file so that it is available
8353** to all source files.  We break it out in an effort to keep the code
8354** better organized.
8355**
8356** NOTE:  source files should *not* #include this header file directly.
8357** Source files should #include the sqliteInt.h file and let that file
8358** include this one indirectly.
8359*/
8360
8361
8362/*
8363** Figure out what version of the code to use.  The choices are
8364**
8365**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8366**                             mutexes implemention cannot be overridden
8367**                             at start-time.
8368**
8369**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8370**                             mutual exclusion is provided.  But this
8371**                             implementation can be overridden at
8372**                             start-time.
8373**
8374**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8375**
8376**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8377**
8378**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8379*/
8380#if !SQLITE_THREADSAFE
8381# define SQLITE_MUTEX_OMIT
8382#endif
8383#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8384#  if SQLITE_OS_UNIX
8385#    define SQLITE_MUTEX_PTHREADS
8386#  elif SQLITE_OS_WIN
8387#    define SQLITE_MUTEX_W32
8388#  elif SQLITE_OS_OS2
8389#    define SQLITE_MUTEX_OS2
8390#  else
8391#    define SQLITE_MUTEX_NOOP
8392#  endif
8393#endif
8394
8395#ifdef SQLITE_MUTEX_OMIT
8396/*
8397** If this is a no-op implementation, implement everything as macros.
8398*/
8399#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8400#define sqlite3_mutex_free(X)
8401#define sqlite3_mutex_enter(X)
8402#define sqlite3_mutex_try(X)      SQLITE_OK
8403#define sqlite3_mutex_leave(X)
8404#define sqlite3_mutex_held(X)     1
8405#define sqlite3_mutex_notheld(X)  1
8406#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8407#define sqlite3MutexInit()        SQLITE_OK
8408#define sqlite3MutexEnd()
8409#endif /* defined(SQLITE_MUTEX_OMIT) */
8410
8411/************** End of mutex.h ***********************************************/
8412/************** Continuing where we left off in sqliteInt.h ******************/
8413
8414
8415/*
8416** Each database file to be accessed by the system is an instance
8417** of the following structure.  There are normally two of these structures
8418** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8419** aDb[1] is the database file used to hold temporary tables.  Additional
8420** databases may be attached.
8421*/
8422struct Db {
8423  char *zName;         /* Name of this database */
8424  Btree *pBt;          /* The B*Tree structure for this database file */
8425  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8426  u8 safety_level;     /* How aggressive at syncing data to disk */
8427  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8428};
8429
8430/*
8431** An instance of the following structure stores a database schema.
8432**
8433** If there are no virtual tables configured in this schema, the
8434** Schema.db variable is set to NULL. After the first virtual table
8435** has been added, it is set to point to the database connection
8436** used to create the connection. Once a virtual table has been
8437** added to the Schema structure and the Schema.db variable populated,
8438** only that database connection may use the Schema to prepare
8439** statements.
8440*/
8441struct Schema {
8442  int schema_cookie;   /* Database schema version number for this file */
8443  Hash tblHash;        /* All tables indexed by name */
8444  Hash idxHash;        /* All (named) indices indexed by name */
8445  Hash trigHash;       /* All triggers indexed by name */
8446  Hash fkeyHash;       /* All foreign keys by referenced table name */
8447  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8448  u8 file_format;      /* Schema format version for this file */
8449  u8 enc;              /* Text encoding used by this database */
8450  u16 flags;           /* Flags associated with this schema */
8451  int cache_size;      /* Number of pages to use in the cache */
8452#ifndef SQLITE_OMIT_VIRTUALTABLE
8453  sqlite3 *db;         /* "Owner" connection. See comment above */
8454#endif
8455};
8456
8457/*
8458** These macros can be used to test, set, or clear bits in the
8459** Db.pSchema->flags field.
8460*/
8461#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8462#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8463#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8464#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8465
8466/*
8467** Allowed values for the DB.pSchema->flags field.
8468**
8469** The DB_SchemaLoaded flag is set after the database schema has been
8470** read into internal hash tables.
8471**
8472** DB_UnresetViews means that one or more views have column names that
8473** have been filled out.  If the schema changes, these column names might
8474** changes and so the view will need to be reset.
8475*/
8476#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8477#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8478#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8479
8480/*
8481** The number of different kinds of things that can be limited
8482** using the sqlite3_limit() interface.
8483*/
8484#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8485
8486/*
8487** Lookaside malloc is a set of fixed-size buffers that can be used
8488** to satisfy small transient memory allocation requests for objects
8489** associated with a particular database connection.  The use of
8490** lookaside malloc provides a significant performance enhancement
8491** (approx 10%) by avoiding numerous malloc/free requests while parsing
8492** SQL statements.
8493**
8494** The Lookaside structure holds configuration information about the
8495** lookaside malloc subsystem.  Each available memory allocation in
8496** the lookaside subsystem is stored on a linked list of LookasideSlot
8497** objects.
8498**
8499** Lookaside allocations are only allowed for objects that are associated
8500** with a particular database connection.  Hence, schema information cannot
8501** be stored in lookaside because in shared cache mode the schema information
8502** is shared by multiple database connections.  Therefore, while parsing
8503** schema information, the Lookaside.bEnabled flag is cleared so that
8504** lookaside allocations are not used to construct the schema objects.
8505*/
8506struct Lookaside {
8507  u16 sz;                 /* Size of each buffer in bytes */
8508  u8 bEnabled;            /* False to disable new lookaside allocations */
8509  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8510  int nOut;               /* Number of buffers currently checked out */
8511  int mxOut;              /* Highwater mark for nOut */
8512  LookasideSlot *pFree;   /* List of available buffers */
8513  void *pStart;           /* First byte of available memory space */
8514  void *pEnd;             /* First byte past end of available space */
8515};
8516struct LookasideSlot {
8517  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8518};
8519
8520/*
8521** A hash table for function definitions.
8522**
8523** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8524** Collisions are on the FuncDef.pHash chain.
8525*/
8526struct FuncDefHash {
8527  FuncDef *a[23];       /* Hash table for functions */
8528};
8529
8530/*
8531** Each database connection is an instance of the following structure.
8532**
8533** The sqlite.lastRowid records the last insert rowid generated by an
8534** insert statement.  Inserts on views do not affect its value.  Each
8535** trigger has its own context, so that lastRowid can be updated inside
8536** triggers as usual.  The previous value will be restored once the trigger
8537** exits.  Upon entering a before or instead of trigger, lastRowid is no
8538** longer (since after version 2.8.12) reset to -1.
8539**
8540** The sqlite.nChange does not count changes within triggers and keeps no
8541** context.  It is reset at start of sqlite3_exec.
8542** The sqlite.lsChange represents the number of changes made by the last
8543** insert, update, or delete statement.  It remains constant throughout the
8544** length of a statement and is then updated by OP_SetCounts.  It keeps a
8545** context stack just like lastRowid so that the count of changes
8546** within a trigger is not seen outside the trigger.  Changes to views do not
8547** affect the value of lsChange.
8548** The sqlite.csChange keeps track of the number of current changes (since
8549** the last statement) and is used to update sqlite_lsChange.
8550**
8551** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8552** store the most recent error code and, if applicable, string. The
8553** internal function sqlite3Error() is used to set these variables
8554** consistently.
8555*/
8556struct sqlite3 {
8557  sqlite3_vfs *pVfs;            /* OS Interface */
8558  int nDb;                      /* Number of backends currently in use */
8559  Db *aDb;                      /* All backends */
8560  int flags;                    /* Miscellaneous flags. See below */
8561  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8562  int errCode;                  /* Most recent error code (SQLITE_*) */
8563  int errMask;                  /* & result codes with this before returning */
8564  u8 autoCommit;                /* The auto-commit flag. */
8565  u8 temp_store;                /* 1: file 2: memory 0: default */
8566  u8 mallocFailed;              /* True if we have seen a malloc failure */
8567  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8568  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8569  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8570  u8 suppressErr;               /* Do not issue error messages if true */
8571  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8572  int nTable;                   /* Number of tables in the database */
8573  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8574  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8575  u32 magic;                    /* Magic number for detect library misuse */
8576  int nChange;                  /* Value returned by sqlite3_changes() */
8577  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8578  sqlite3_mutex *mutex;         /* Connection mutex */
8579  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8580  struct sqlite3InitInfo {      /* Information used during initialization */
8581    int iDb;                    /* When back is being initialized */
8582    int newTnum;                /* Rootpage of table being initialized */
8583    u8 busy;                    /* TRUE if currently initializing */
8584    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8585  } init;
8586  int nExtension;               /* Number of loaded extensions */
8587  void **aExtension;            /* Array of shared library handles */
8588  struct Vdbe *pVdbe;           /* List of active virtual machines */
8589  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8590  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8591  void (*xTrace)(void*,const char*);        /* Trace function */
8592  void *pTraceArg;                          /* Argument to the trace function */
8593  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8594  void *pProfileArg;                        /* Argument to profile function */
8595  void *pCommitArg;                 /* Argument to xCommitCallback() */
8596  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8597  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8598  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8599  void *pUpdateArg;
8600  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8601#ifndef SQLITE_OMIT_WAL
8602  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8603  void *pWalArg;
8604#endif
8605  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8606  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8607  void *pCollNeededArg;
8608  sqlite3_value *pErr;          /* Most recent error message */
8609  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8610  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8611  union {
8612    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8613    double notUsed1;            /* Spacer */
8614  } u1;
8615  Lookaside lookaside;          /* Lookaside malloc configuration */
8616#ifndef SQLITE_OMIT_AUTHORIZATION
8617  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8618                                /* Access authorization function */
8619  void *pAuthArg;               /* 1st argument to the access auth function */
8620#endif
8621#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8622  int (*xProgress)(void *);     /* The progress callback */
8623  void *pProgressArg;           /* Argument to the progress callback */
8624  int nProgressOps;             /* Number of opcodes for progress callback */
8625#endif
8626#ifndef SQLITE_OMIT_VIRTUALTABLE
8627  Hash aModule;                 /* populated by sqlite3_create_module() */
8628  Table *pVTab;                 /* vtab with active Connect/Create method */
8629  VTable **aVTrans;             /* Virtual tables with open transactions */
8630  int nVTrans;                  /* Allocated size of aVTrans */
8631  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8632#endif
8633  FuncDefHash aFunc;            /* Hash table of connection functions */
8634  Hash aCollSeq;                /* All collating sequences */
8635  BusyHandler busyHandler;      /* Busy callback */
8636  int busyTimeout;              /* Busy handler timeout, in msec */
8637  Db aDbStatic[2];              /* Static space for the 2 default backends */
8638  Savepoint *pSavepoint;        /* List of active savepoints */
8639  int nSavepoint;               /* Number of non-transaction savepoints */
8640  int nStatement;               /* Number of nested statement-transactions  */
8641  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8642  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8643
8644#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8645  /* The following variables are all protected by the STATIC_MASTER
8646  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8647  **
8648  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8649  ** unlock so that it can proceed.
8650  **
8651  ** When X.pBlockingConnection==Y, that means that something that X tried
8652  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8653  ** held by Y.
8654  */
8655  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8656  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8657  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8658  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8659  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8660#endif
8661};
8662
8663/*
8664** A macro to discover the encoding of a database.
8665*/
8666#define ENC(db) ((db)->aDb[0].pSchema->enc)
8667
8668/*
8669** Possible values for the sqlite3.flags.
8670*/
8671#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8672#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8673#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8674#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8675#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8676                                          /*   DELETE, or UPDATE and return */
8677                                          /*   the count using a callback. */
8678#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8679                                          /*   result set is empty */
8680#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8681#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8682#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8683#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8684                                          ** accessing read-only databases */
8685#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8686#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8687#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8688#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8689#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8690#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8691#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8692#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8693#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8694#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8695#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8696
8697/*
8698** Bits of the sqlite3.flags field that are used by the
8699** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8700** These must be the low-order bits of the flags field.
8701*/
8702#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8703#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8704#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8705#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8706#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8707#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
8708#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
8709
8710/*
8711** Possible values for the sqlite.magic field.
8712** The numbers are obtained at random and have no special meaning, other
8713** than being distinct from one another.
8714*/
8715#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8716#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8717#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8718#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8719#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8720
8721/*
8722** Each SQL function is defined by an instance of the following
8723** structure.  A pointer to this structure is stored in the sqlite.aFunc
8724** hash table.  When multiple functions have the same name, the hash table
8725** points to a linked list of these structures.
8726*/
8727struct FuncDef {
8728  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8729  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8730  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8731  void *pUserData;     /* User data parameter */
8732  FuncDef *pNext;      /* Next function with same name */
8733  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8734  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8735  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8736  char *zName;         /* SQL name of the function. */
8737  FuncDef *pHash;      /* Next with a different name but the same hash */
8738};
8739
8740/*
8741** Possible values for FuncDef.flags
8742*/
8743#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8744#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8745#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8746#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8747#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8748#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8749#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8750
8751/*
8752** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8753** used to create the initializers for the FuncDef structures.
8754**
8755**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8756**     Used to create a scalar function definition of a function zName
8757**     implemented by C function xFunc that accepts nArg arguments. The
8758**     value passed as iArg is cast to a (void*) and made available
8759**     as the user-data (sqlite3_user_data()) for the function. If
8760**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8761**
8762**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8763**     Used to create an aggregate function definition implemented by
8764**     the C functions xStep and xFinal. The first four parameters
8765**     are interpreted in the same way as the first 4 parameters to
8766**     FUNCTION().
8767**
8768**   LIKEFUNC(zName, nArg, pArg, flags)
8769**     Used to create a scalar function definition of a function zName
8770**     that accepts nArg arguments and is implemented by a call to C
8771**     function likeFunc. Argument pArg is cast to a (void *) and made
8772**     available as the function user-data (sqlite3_user_data()). The
8773**     FuncDef.flags variable is set to the value passed as the flags
8774**     parameter.
8775*/
8776#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8777  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8778   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8779#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8780  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8781   pArg, 0, xFunc, 0, 0, #zName, 0}
8782#define LIKEFUNC(zName, nArg, arg, flags) \
8783  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8784#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8785  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8786   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8787
8788/*
8789** All current savepoints are stored in a linked list starting at
8790** sqlite3.pSavepoint. The first element in the list is the most recently
8791** opened savepoint. Savepoints are added to the list by the vdbe
8792** OP_Savepoint instruction.
8793*/
8794struct Savepoint {
8795  char *zName;                        /* Savepoint name (nul-terminated) */
8796  i64 nDeferredCons;                  /* Number of deferred fk violations */
8797  Savepoint *pNext;                   /* Parent savepoint (if any) */
8798};
8799
8800/*
8801** The following are used as the second parameter to sqlite3Savepoint(),
8802** and as the P1 argument to the OP_Savepoint instruction.
8803*/
8804#define SAVEPOINT_BEGIN      0
8805#define SAVEPOINT_RELEASE    1
8806#define SAVEPOINT_ROLLBACK   2
8807
8808
8809/*
8810** Each SQLite module (virtual table definition) is defined by an
8811** instance of the following structure, stored in the sqlite3.aModule
8812** hash table.
8813*/
8814struct Module {
8815  const sqlite3_module *pModule;       /* Callback pointers */
8816  const char *zName;                   /* Name passed to create_module() */
8817  void *pAux;                          /* pAux passed to create_module() */
8818  void (*xDestroy)(void *);            /* Module destructor function */
8819};
8820
8821/*
8822** information about each column of an SQL table is held in an instance
8823** of this structure.
8824*/
8825struct Column {
8826  char *zName;     /* Name of this column */
8827  Expr *pDflt;     /* Default value of this column */
8828  char *zDflt;     /* Original text of the default value */
8829  char *zType;     /* Data type for this column */
8830  char *zColl;     /* Collating sequence.  If NULL, use the default */
8831  u8 notNull;      /* True if there is a NOT NULL constraint */
8832  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8833  char affinity;   /* One of the SQLITE_AFF_... values */
8834#ifndef SQLITE_OMIT_VIRTUALTABLE
8835  u8 isHidden;     /* True if this column is 'hidden' */
8836#endif
8837};
8838
8839/*
8840** A "Collating Sequence" is defined by an instance of the following
8841** structure. Conceptually, a collating sequence consists of a name and
8842** a comparison routine that defines the order of that sequence.
8843**
8844** There may two separate implementations of the collation function, one
8845** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8846** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8847** native byte order. When a collation sequence is invoked, SQLite selects
8848** the version that will require the least expensive encoding
8849** translations, if any.
8850**
8851** The CollSeq.pUser member variable is an extra parameter that passed in
8852** as the first argument to the UTF-8 comparison function, xCmp.
8853** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8854** xCmp16.
8855**
8856** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8857** collating sequence is undefined.  Indices built on an undefined
8858** collating sequence may not be read or written.
8859*/
8860struct CollSeq {
8861  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8862  u8 enc;               /* Text encoding handled by xCmp() */
8863  u8 type;              /* One of the SQLITE_COLL_... values below */
8864  void *pUser;          /* First argument to xCmp() */
8865  int (*xCmp)(void*,int, const void*, int, const void*);
8866  void (*xDel)(void*);  /* Destructor for pUser */
8867};
8868
8869/*
8870** Allowed values of CollSeq.type:
8871*/
8872#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8873#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8874#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8875#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8876
8877/*
8878** A sort order can be either ASC or DESC.
8879*/
8880#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8881#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8882
8883/*
8884** Column affinity types.
8885**
8886** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8887** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8888** the speed a little by numbering the values consecutively.
8889**
8890** But rather than start with 0 or 1, we begin with 'a'.  That way,
8891** when multiple affinity types are concatenated into a string and
8892** used as the P4 operand, they will be more readable.
8893**
8894** Note also that the numeric types are grouped together so that testing
8895** for a numeric type is a single comparison.
8896*/
8897#define SQLITE_AFF_TEXT     'a'
8898#define SQLITE_AFF_NONE     'b'
8899#define SQLITE_AFF_NUMERIC  'c'
8900#define SQLITE_AFF_INTEGER  'd'
8901#define SQLITE_AFF_REAL     'e'
8902
8903#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8904
8905/*
8906** The SQLITE_AFF_MASK values masks off the significant bits of an
8907** affinity value.
8908*/
8909#define SQLITE_AFF_MASK     0x67
8910
8911/*
8912** Additional bit values that can be ORed with an affinity without
8913** changing the affinity.
8914*/
8915#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8916#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8917#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8918
8919/*
8920** An object of this type is created for each virtual table present in
8921** the database schema.
8922**
8923** If the database schema is shared, then there is one instance of this
8924** structure for each database connection (sqlite3*) that uses the shared
8925** schema. This is because each database connection requires its own unique
8926** instance of the sqlite3_vtab* handle used to access the virtual table
8927** implementation. sqlite3_vtab* handles can not be shared between
8928** database connections, even when the rest of the in-memory database
8929** schema is shared, as the implementation often stores the database
8930** connection handle passed to it via the xConnect() or xCreate() method
8931** during initialization internally. This database connection handle may
8932** then used by the virtual table implementation to access real tables
8933** within the database. So that they appear as part of the callers
8934** transaction, these accesses need to be made via the same database
8935** connection as that used to execute SQL operations on the virtual table.
8936**
8937** All VTable objects that correspond to a single table in a shared
8938** database schema are initially stored in a linked-list pointed to by
8939** the Table.pVTable member variable of the corresponding Table object.
8940** When an sqlite3_prepare() operation is required to access the virtual
8941** table, it searches the list for the VTable that corresponds to the
8942** database connection doing the preparing so as to use the correct
8943** sqlite3_vtab* handle in the compiled query.
8944**
8945** When an in-memory Table object is deleted (for example when the
8946** schema is being reloaded for some reason), the VTable objects are not
8947** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
8948** immediately. Instead, they are moved from the Table.pVTable list to
8949** another linked list headed by the sqlite3.pDisconnect member of the
8950** corresponding sqlite3 structure. They are then deleted/xDisconnected
8951** next time a statement is prepared using said sqlite3*. This is done
8952** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8953** Refer to comments above function sqlite3VtabUnlockList() for an
8954** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8955** list without holding the corresponding sqlite3.mutex mutex.
8956**
8957** The memory for objects of this type is always allocated by
8958** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
8959** the first argument.
8960*/
8961struct VTable {
8962  sqlite3 *db;              /* Database connection associated with this table */
8963  Module *pMod;             /* Pointer to module implementation */
8964  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8965  int nRef;                 /* Number of pointers to this structure */
8966  VTable *pNext;            /* Next in linked list (see above) */
8967};
8968
8969/*
8970** Each SQL table is represented in memory by an instance of the
8971** following structure.
8972**
8973** Table.zName is the name of the table.  The case of the original
8974** CREATE TABLE statement is stored, but case is not significant for
8975** comparisons.
8976**
8977** Table.nCol is the number of columns in this table.  Table.aCol is a
8978** pointer to an array of Column structures, one for each column.
8979**
8980** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8981** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8982** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8983** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8984** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8985** is generated for each row of the table.  TF_HasPrimaryKey is set if
8986** the table has any PRIMARY KEY, INTEGER or otherwise.
8987**
8988** Table.tnum is the page number for the root BTree page of the table in the
8989** database file.  If Table.iDb is the index of the database table backend
8990** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8991** holds temporary tables and indices.  If TF_Ephemeral is set
8992** then the table is stored in a file that is automatically deleted
8993** when the VDBE cursor to the table is closed.  In this case Table.tnum
8994** refers VDBE cursor number that holds the table open, not to the root
8995** page number.  Transient tables are used to hold the results of a
8996** sub-query that appears instead of a real table name in the FROM clause
8997** of a SELECT statement.
8998*/
8999struct Table {
9000  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
9001  char *zName;         /* Name of the table or view */
9002  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9003  int nCol;            /* Number of columns in this table */
9004  Column *aCol;        /* Information about each column */
9005  Index *pIndex;       /* List of SQL indexes on this table. */
9006  int tnum;            /* Root BTree node for this table (see note above) */
9007  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9008  u16 nRef;            /* Number of pointers to this Table */
9009  u8 tabFlags;         /* Mask of TF_* values */
9010  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9011  FKey *pFKey;         /* Linked list of all foreign keys in this table */
9012  char *zColAff;       /* String defining the affinity of each column */
9013#ifndef SQLITE_OMIT_CHECK
9014  Expr *pCheck;        /* The AND of all CHECK constraints */
9015#endif
9016#ifndef SQLITE_OMIT_ALTERTABLE
9017  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9018#endif
9019#ifndef SQLITE_OMIT_VIRTUALTABLE
9020  VTable *pVTable;     /* List of VTable objects. */
9021  int nModuleArg;      /* Number of arguments to the module */
9022  char **azModuleArg;  /* Text of all module args. [0] is module name */
9023#endif
9024  Trigger *pTrigger;   /* List of triggers stored in pSchema */
9025  Schema *pSchema;     /* Schema that contains this table */
9026  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9027};
9028
9029/*
9030** Allowed values for Tabe.tabFlags.
9031*/
9032#define TF_Readonly        0x01    /* Read-only system table */
9033#define TF_Ephemeral       0x02    /* An ephemeral table */
9034#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9035#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9036#define TF_Virtual         0x10    /* Is a virtual table */
9037#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9038
9039
9040
9041/*
9042** Test to see whether or not a table is a virtual table.  This is
9043** done as a macro so that it will be optimized out when virtual
9044** table support is omitted from the build.
9045*/
9046#ifndef SQLITE_OMIT_VIRTUALTABLE
9047#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9048#  define IsHiddenColumn(X) ((X)->isHidden)
9049#else
9050#  define IsVirtual(X)      0
9051#  define IsHiddenColumn(X) 0
9052#endif
9053
9054/*
9055** Each foreign key constraint is an instance of the following structure.
9056**
9057** A foreign key is associated with two tables.  The "from" table is
9058** the table that contains the REFERENCES clause that creates the foreign
9059** key.  The "to" table is the table that is named in the REFERENCES clause.
9060** Consider this example:
9061**
9062**     CREATE TABLE ex1(
9063**       a INTEGER PRIMARY KEY,
9064**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9065**     );
9066**
9067** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9068**
9069** Each REFERENCES clause generates an instance of the following structure
9070** which is attached to the from-table.  The to-table need not exist when
9071** the from-table is created.  The existence of the to-table is not checked.
9072*/
9073struct FKey {
9074  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9075  FKey *pNextFrom;  /* Next foreign key in pFrom */
9076  char *zTo;        /* Name of table that the key points to (aka: Parent) */
9077  FKey *pNextTo;    /* Next foreign key on table named zTo */
9078  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9079  int nCol;         /* Number of columns in this key */
9080  /* EV: R-30323-21917 */
9081  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9082  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9083  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9084  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9085    int iFrom;         /* Index of column in pFrom */
9086    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9087  } aCol[1];        /* One entry for each of nCol column s */
9088};
9089
9090/*
9091** SQLite supports many different ways to resolve a constraint
9092** error.  ROLLBACK processing means that a constraint violation
9093** causes the operation in process to fail and for the current transaction
9094** to be rolled back.  ABORT processing means the operation in process
9095** fails and any prior changes from that one operation are backed out,
9096** but the transaction is not rolled back.  FAIL processing means that
9097** the operation in progress stops and returns an error code.  But prior
9098** changes due to the same operation are not backed out and no rollback
9099** occurs.  IGNORE means that the particular row that caused the constraint
9100** error is not inserted or updated.  Processing continues and no error
9101** is returned.  REPLACE means that preexisting database rows that caused
9102** a UNIQUE constraint violation are removed so that the new insert or
9103** update can proceed.  Processing continues and no error is reported.
9104**
9105** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9106** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9107** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9108** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9109** referenced table row is propagated into the row that holds the
9110** foreign key.
9111**
9112** The following symbolic values are used to record which type
9113** of action to take.
9114*/
9115#define OE_None     0   /* There is no constraint to check */
9116#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9117#define OE_Abort    2   /* Back out changes but do no rollback transaction */
9118#define OE_Fail     3   /* Stop the operation but leave all prior changes */
9119#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9120#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9121
9122#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9123#define OE_SetNull  7   /* Set the foreign key value to NULL */
9124#define OE_SetDflt  8   /* Set the foreign key value to its default */
9125#define OE_Cascade  9   /* Cascade the changes */
9126
9127#define OE_Default  99  /* Do whatever the default action is */
9128
9129
9130/*
9131** An instance of the following structure is passed as the first
9132** argument to sqlite3VdbeKeyCompare and is used to control the
9133** comparison of the two index keys.
9134*/
9135struct KeyInfo {
9136  sqlite3 *db;        /* The database connection */
9137  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9138  u16 nField;         /* Number of entries in aColl[] */
9139  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9140  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9141};
9142
9143/*
9144** An instance of the following structure holds information about a
9145** single index record that has already been parsed out into individual
9146** values.
9147**
9148** A record is an object that contains one or more fields of data.
9149** Records are used to store the content of a table row and to store
9150** the key of an index.  A blob encoding of a record is created by
9151** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9152** OP_Column opcode.
9153**
9154** This structure holds a record that has already been disassembled
9155** into its constituent fields.
9156*/
9157struct UnpackedRecord {
9158  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9159  u16 nField;         /* Number of entries in apMem[] */
9160  u16 flags;          /* Boolean settings.  UNPACKED_... below */
9161  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9162  Mem *aMem;          /* Values */
9163};
9164
9165/*
9166** Allowed values of UnpackedRecord.flags
9167*/
9168#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9169#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9170#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9171#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9172#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9173#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9174
9175/*
9176** Each SQL index is represented in memory by an
9177** instance of the following structure.
9178**
9179** The columns of the table that are to be indexed are described
9180** by the aiColumn[] field of this structure.  For example, suppose
9181** we have the following table and index:
9182**
9183**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9184**     CREATE INDEX Ex2 ON Ex1(c3,c1);
9185**
9186** In the Table structure describing Ex1, nCol==3 because there are
9187** three columns in the table.  In the Index structure describing
9188** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9189** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
9190** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9191** The second column to be indexed (c1) has an index of 0 in
9192** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9193**
9194** The Index.onError field determines whether or not the indexed columns
9195** must be unique and what to do if they are not.  When Index.onError=OE_None,
9196** it means this is not a unique index.  Otherwise it is a unique index
9197** and the value of Index.onError indicate the which conflict resolution
9198** algorithm to employ whenever an attempt is made to insert a non-unique
9199** element.
9200*/
9201struct Index {
9202  char *zName;     /* Name of this index */
9203  int nColumn;     /* Number of columns in the table used by this index */
9204  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9205  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9206  Table *pTable;   /* The SQL table being indexed */
9207  int tnum;        /* Page containing root of this index in database file */
9208  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9209  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9210  char *zColAff;   /* String defining the affinity of each column */
9211  Index *pNext;    /* The next index associated with the same table */
9212  Schema *pSchema; /* Schema containing this index */
9213  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9214  char **azColl;   /* Array of collation sequence names for index */
9215  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9216};
9217
9218/*
9219** Each sample stored in the sqlite_stat2 table is represented in memory
9220** using a structure of this type.
9221*/
9222struct IndexSample {
9223  union {
9224    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9225    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9226  } u;
9227  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9228  u8 nByte;         /* Size in byte of text or blob. */
9229};
9230
9231/*
9232** Each token coming out of the lexer is an instance of
9233** this structure.  Tokens are also used as part of an expression.
9234**
9235** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9236** may contain random values.  Do not make any assumptions about Token.dyn
9237** and Token.n when Token.z==0.
9238*/
9239struct Token {
9240  const char *z;     /* Text of the token.  Not NULL-terminated! */
9241  unsigned int n;    /* Number of characters in this token */
9242};
9243
9244/*
9245** An instance of this structure contains information needed to generate
9246** code for a SELECT that contains aggregate functions.
9247**
9248** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9249** pointer to this structure.  The Expr.iColumn field is the index in
9250** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9251** code for that node.
9252**
9253** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9254** original Select structure that describes the SELECT statement.  These
9255** fields do not need to be freed when deallocating the AggInfo structure.
9256*/
9257struct AggInfo {
9258  u8 directMode;          /* Direct rendering mode means take data directly
9259                          ** from source tables rather than from accumulators */
9260  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9261                          ** than the source table */
9262  int sortingIdx;         /* Cursor number of the sorting index */
9263  ExprList *pGroupBy;     /* The group by clause */
9264  int nSortingColumn;     /* Number of columns in the sorting index */
9265  struct AggInfo_col {    /* For each column used in source tables */
9266    Table *pTab;             /* Source table */
9267    int iTable;              /* Cursor number of the source table */
9268    int iColumn;             /* Column number within the source table */
9269    int iSorterColumn;       /* Column number in the sorting index */
9270    int iMem;                /* Memory location that acts as accumulator */
9271    Expr *pExpr;             /* The original expression */
9272  } *aCol;
9273  int nColumn;            /* Number of used entries in aCol[] */
9274  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9275  int nAccumulator;       /* Number of columns that show through to the output.
9276                          ** Additional columns are used only as parameters to
9277                          ** aggregate functions */
9278  struct AggInfo_func {   /* For each aggregate function */
9279    Expr *pExpr;             /* Expression encoding the function */
9280    FuncDef *pFunc;          /* The aggregate function implementation */
9281    int iMem;                /* Memory location that acts as accumulator */
9282    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9283  } *aFunc;
9284  int nFunc;              /* Number of entries in aFunc[] */
9285  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9286};
9287
9288/*
9289** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9290** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9291** than 32767 we have to make it 32-bit.  16-bit is preferred because
9292** it uses less memory in the Expr object, which is a big memory user
9293** in systems with lots of prepared statements.  And few applications
9294** need more than about 10 or 20 variables.  But some extreme users want
9295** to have prepared statements with over 32767 variables, and for them
9296** the option is available (at compile-time).
9297*/
9298#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9299typedef i16 ynVar;
9300#else
9301typedef int ynVar;
9302#endif
9303
9304/*
9305** Each node of an expression in the parse tree is an instance
9306** of this structure.
9307**
9308** Expr.op is the opcode. The integer parser token codes are reused
9309** as opcodes here. For example, the parser defines TK_GE to be an integer
9310** code representing the ">=" operator. This same integer code is reused
9311** to represent the greater-than-or-equal-to operator in the expression
9312** tree.
9313**
9314** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9315** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9316** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9317** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9318** then Expr.token contains the name of the function.
9319**
9320** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9321** binary operator. Either or both may be NULL.
9322**
9323** Expr.x.pList is a list of arguments if the expression is an SQL function,
9324** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9325** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9326** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9327** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9328** valid.
9329**
9330** An expression of the form ID or ID.ID refers to a column in a table.
9331** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9332** the integer cursor number of a VDBE cursor pointing to that table and
9333** Expr.iColumn is the column number for the specific column.  If the
9334** expression is used as a result in an aggregate SELECT, then the
9335** value is also stored in the Expr.iAgg column in the aggregate so that
9336** it can be accessed after all aggregates are computed.
9337**
9338** If the expression is an unbound variable marker (a question mark
9339** character '?' in the original SQL) then the Expr.iTable holds the index
9340** number for that variable.
9341**
9342** If the expression is a subquery then Expr.iColumn holds an integer
9343** register number containing the result of the subquery.  If the
9344** subquery gives a constant result, then iTable is -1.  If the subquery
9345** gives a different answer at different times during statement processing
9346** then iTable is the address of a subroutine that computes the subquery.
9347**
9348** If the Expr is of type OP_Column, and the table it is selecting from
9349** is a disk table or the "old.*" pseudo-table, then pTab points to the
9350** corresponding table definition.
9351**
9352** ALLOCATION NOTES:
9353**
9354** Expr objects can use a lot of memory space in database schema.  To
9355** help reduce memory requirements, sometimes an Expr object will be
9356** truncated.  And to reduce the number of memory allocations, sometimes
9357** two or more Expr objects will be stored in a single memory allocation,
9358** together with Expr.zToken strings.
9359**
9360** If the EP_Reduced and EP_TokenOnly flags are set when
9361** an Expr object is truncated.  When EP_Reduced is set, then all
9362** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9363** are contained within the same memory allocation.  Note, however, that
9364** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9365** allocated, regardless of whether or not EP_Reduced is set.
9366*/
9367struct Expr {
9368  u8 op;                 /* Operation performed by this node */
9369  char affinity;         /* The affinity of the column or 0 if not a column */
9370  u16 flags;             /* Various flags.  EP_* See below */
9371  union {
9372    char *zToken;          /* Token value. Zero terminated and dequoted */
9373    int iValue;            /* Integer value if EP_IntValue */
9374  } u;
9375
9376  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9377  ** space is allocated for the fields below this point. An attempt to
9378  ** access them will result in a segfault or malfunction.
9379  *********************************************************************/
9380
9381  Expr *pLeft;           /* Left subnode */
9382  Expr *pRight;          /* Right subnode */
9383  union {
9384    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9385    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9386  } x;
9387  CollSeq *pColl;        /* The collation type of the column or 0 */
9388
9389  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9390  ** space is allocated for the fields below this point. An attempt to
9391  ** access them will result in a segfault or malfunction.
9392  *********************************************************************/
9393
9394  int iTable;            /* TK_COLUMN: cursor number of table holding column
9395                         ** TK_REGISTER: register number
9396                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9397  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9398                         ** TK_VARIABLE: variable number (always >= 1). */
9399  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9400  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9401  u8 flags2;             /* Second set of flags.  EP2_... */
9402  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9403  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9404  Table *pTab;           /* Table for TK_COLUMN expressions. */
9405#if SQLITE_MAX_EXPR_DEPTH>0
9406  int nHeight;           /* Height of the tree headed by this node */
9407#endif
9408};
9409
9410/*
9411** The following are the meanings of bits in the Expr.flags field.
9412*/
9413#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9414#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9415#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9416#define EP_Error      0x0008  /* Expression contains one or more errors */
9417#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9418#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9419#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9420#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9421#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9422#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9423#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9424#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9425
9426#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9427#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9428#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9429
9430/*
9431** The following are the meanings of bits in the Expr.flags2 field.
9432*/
9433#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9434#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9435
9436/*
9437** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9438** flag on an expression structure.  This flag is used for VV&A only.  The
9439** routine is implemented as a macro that only works when in debugging mode,
9440** so as not to burden production code.
9441*/
9442#ifdef SQLITE_DEBUG
9443# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9444#else
9445# define ExprSetIrreducible(X)
9446#endif
9447
9448/*
9449** These macros can be used to test, set, or clear bits in the
9450** Expr.flags field.
9451*/
9452#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9453#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9454#define ExprSetProperty(E,P)     (E)->flags|=(P)
9455#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9456
9457/*
9458** Macros to determine the number of bytes required by a normal Expr
9459** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9460** and an Expr struct with the EP_TokenOnly flag set.
9461*/
9462#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9463#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9464#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9465
9466/*
9467** Flags passed to the sqlite3ExprDup() function. See the header comment
9468** above sqlite3ExprDup() for details.
9469*/
9470#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9471
9472/*
9473** A list of expressions.  Each expression may optionally have a
9474** name.  An expr/name combination can be used in several ways, such
9475** as the list of "expr AS ID" fields following a "SELECT" or in the
9476** list of "ID = expr" items in an UPDATE.  A list of expressions can
9477** also be used as the argument to a function, in which case the a.zName
9478** field is not used.
9479*/
9480struct ExprList {
9481  int nExpr;             /* Number of expressions on the list */
9482  int nAlloc;            /* Number of entries allocated below */
9483  int iECursor;          /* VDBE Cursor associated with this ExprList */
9484  struct ExprList_item {
9485    Expr *pExpr;           /* The list of expressions */
9486    char *zName;           /* Token associated with this expression */
9487    char *zSpan;           /* Original text of the expression */
9488    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9489    u8 done;               /* A flag to indicate when processing is finished */
9490    u16 iCol;              /* For ORDER BY, column number in result set */
9491    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9492  } *a;                  /* One entry for each expression */
9493};
9494
9495/*
9496** An instance of this structure is used by the parser to record both
9497** the parse tree for an expression and the span of input text for an
9498** expression.
9499*/
9500struct ExprSpan {
9501  Expr *pExpr;          /* The expression parse tree */
9502  const char *zStart;   /* First character of input text */
9503  const char *zEnd;     /* One character past the end of input text */
9504};
9505
9506/*
9507** An instance of this structure can hold a simple list of identifiers,
9508** such as the list "a,b,c" in the following statements:
9509**
9510**      INSERT INTO t(a,b,c) VALUES ...;
9511**      CREATE INDEX idx ON t(a,b,c);
9512**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9513**
9514** The IdList.a.idx field is used when the IdList represents the list of
9515** column names after a table name in an INSERT statement.  In the statement
9516**
9517**     INSERT INTO t(a,b,c) ...
9518**
9519** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9520*/
9521struct IdList {
9522  struct IdList_item {
9523    char *zName;      /* Name of the identifier */
9524    int idx;          /* Index in some Table.aCol[] of a column named zName */
9525  } *a;
9526  int nId;         /* Number of identifiers on the list */
9527  int nAlloc;      /* Number of entries allocated for a[] below */
9528};
9529
9530/*
9531** The bitmask datatype defined below is used for various optimizations.
9532**
9533** Changing this from a 64-bit to a 32-bit type limits the number of
9534** tables in a join to 32 instead of 64.  But it also reduces the size
9535** of the library by 738 bytes on ix86.
9536*/
9537typedef u64 Bitmask;
9538
9539/*
9540** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9541*/
9542#define BMS  ((int)(sizeof(Bitmask)*8))
9543
9544/*
9545** The following structure describes the FROM clause of a SELECT statement.
9546** Each table or subquery in the FROM clause is a separate element of
9547** the SrcList.a[] array.
9548**
9549** With the addition of multiple database support, the following structure
9550** can also be used to describe a particular table such as the table that
9551** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9552** such a table must be a simple name: ID.  But in SQLite, the table can
9553** now be identified by a database name, a dot, then the table name: ID.ID.
9554**
9555** The jointype starts out showing the join type between the current table
9556** and the next table on the list.  The parser builds the list this way.
9557** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9558** jointype expresses the join between the table and the previous table.
9559**
9560** In the colUsed field, the high-order bit (bit 63) is set if the table
9561** contains more than 63 columns and the 64-th or later column is used.
9562*/
9563struct SrcList {
9564  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9565  i16 nAlloc;      /* Number of entries allocated in a[] below */
9566  struct SrcList_item {
9567    char *zDatabase;  /* Name of database holding this table */
9568    char *zName;      /* Name of the table */
9569    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9570    Table *pTab;      /* An SQL table corresponding to zName */
9571    Select *pSelect;  /* A SELECT statement used in place of a table name */
9572    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9573    u8 jointype;      /* Type of join between this able and the previous */
9574    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9575    int iCursor;      /* The VDBE cursor number used to access this table */
9576    Expr *pOn;        /* The ON clause of a join */
9577    IdList *pUsing;   /* The USING clause of a join */
9578    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9579    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9580    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9581  } a[1];             /* One entry for each identifier on the list */
9582};
9583
9584/*
9585** Permitted values of the SrcList.a.jointype field
9586*/
9587#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9588#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9589#define JT_NATURAL   0x0004    /* True for a "natural" join */
9590#define JT_LEFT      0x0008    /* Left outer join */
9591#define JT_RIGHT     0x0010    /* Right outer join */
9592#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9593#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9594
9595
9596/*
9597** A WherePlan object holds information that describes a lookup
9598** strategy.
9599**
9600** This object is intended to be opaque outside of the where.c module.
9601** It is included here only so that that compiler will know how big it
9602** is.  None of the fields in this object should be used outside of
9603** the where.c module.
9604**
9605** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9606** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9607** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9608** case that more than one of these conditions is true.
9609*/
9610struct WherePlan {
9611  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9612  u32 nEq;                       /* Number of == constraints */
9613  union {
9614    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9615    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9616    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9617  } u;
9618};
9619
9620/*
9621** For each nested loop in a WHERE clause implementation, the WhereInfo
9622** structure contains a single instance of this structure.  This structure
9623** is intended to be private the the where.c module and should not be
9624** access or modified by other modules.
9625**
9626** The pIdxInfo field is used to help pick the best index on a
9627** virtual table.  The pIdxInfo pointer contains indexing
9628** information for the i-th table in the FROM clause before reordering.
9629** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9630** All other information in the i-th WhereLevel object for the i-th table
9631** after FROM clause ordering.
9632*/
9633struct WhereLevel {
9634  WherePlan plan;       /* query plan for this element of the FROM clause */
9635  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9636  int iTabCur;          /* The VDBE cursor used to access the table */
9637  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9638  int addrBrk;          /* Jump here to break out of the loop */
9639  int addrNxt;          /* Jump here to start the next IN combination */
9640  int addrCont;         /* Jump here to continue with the next loop cycle */
9641  int addrFirst;        /* First instruction of interior of the loop */
9642  u8 iFrom;             /* Which entry in the FROM clause */
9643  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9644  int p1, p2;           /* Operands of the opcode used to ends the loop */
9645  union {               /* Information that depends on plan.wsFlags */
9646    struct {
9647      int nIn;              /* Number of entries in aInLoop[] */
9648      struct InLoop {
9649        int iCur;              /* The VDBE cursor used by this IN operator */
9650        int addrInTop;         /* Top of the IN loop */
9651      } *aInLoop;           /* Information about each nested IN operator */
9652    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9653  } u;
9654
9655  /* The following field is really not part of the current level.  But
9656  ** we need a place to cache virtual table index information for each
9657  ** virtual table in the FROM clause and the WhereLevel structure is
9658  ** a convenient place since there is one WhereLevel for each FROM clause
9659  ** element.
9660  */
9661  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9662};
9663
9664/*
9665** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9666** and the WhereInfo.wctrlFlags member.
9667*/
9668#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9669#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9670#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9671#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9672#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9673#define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9674#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9675#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9676#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9677
9678/*
9679** The WHERE clause processing routine has two halves.  The
9680** first part does the start of the WHERE loop and the second
9681** half does the tail of the WHERE loop.  An instance of
9682** this structure is returned by the first half and passed
9683** into the second half to give some continuity.
9684*/
9685struct WhereInfo {
9686  Parse *pParse;       /* Parsing and code generating context */
9687  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9688  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9689  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9690  SrcList *pTabList;             /* List of tables in the join */
9691  int iTop;                      /* The very beginning of the WHERE loop */
9692  int iContinue;                 /* Jump here to continue with next record */
9693  int iBreak;                    /* Jump here to break out of the loop */
9694  int nLevel;                    /* Number of nested loop */
9695  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9696  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
9697  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9698};
9699
9700/*
9701** A NameContext defines a context in which to resolve table and column
9702** names.  The context consists of a list of tables (the pSrcList) field and
9703** a list of named expression (pEList).  The named expression list may
9704** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9705** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9706** pEList corresponds to the result set of a SELECT and is NULL for
9707** other statements.
9708**
9709** NameContexts can be nested.  When resolving names, the inner-most
9710** context is searched first.  If no match is found, the next outer
9711** context is checked.  If there is still no match, the next context
9712** is checked.  This process continues until either a match is found
9713** or all contexts are check.  When a match is found, the nRef member of
9714** the context containing the match is incremented.
9715**
9716** Each subquery gets a new NameContext.  The pNext field points to the
9717** NameContext in the parent query.  Thus the process of scanning the
9718** NameContext list corresponds to searching through successively outer
9719** subqueries looking for a match.
9720*/
9721struct NameContext {
9722  Parse *pParse;       /* The parser */
9723  SrcList *pSrcList;   /* One or more tables used to resolve names */
9724  ExprList *pEList;    /* Optional list of named expressions */
9725  int nRef;            /* Number of names resolved by this context */
9726  int nErr;            /* Number of errors encountered while resolving names */
9727  u8 allowAgg;         /* Aggregate functions allowed here */
9728  u8 hasAgg;           /* True if aggregates are seen */
9729  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9730  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9731  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9732  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9733};
9734
9735/*
9736** An instance of the following structure contains all information
9737** needed to generate code for a single SELECT statement.
9738**
9739** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9740** If there is a LIMIT clause, the parser sets nLimit to the value of the
9741** limit and nOffset to the value of the offset (or 0 if there is not
9742** offset).  But later on, nLimit and nOffset become the memory locations
9743** in the VDBE that record the limit and offset counters.
9744**
9745** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9746** These addresses must be stored so that we can go back and fill in
9747** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9748** the number of columns in P2 can be computed at the same time
9749** as the OP_OpenEphm instruction is coded because not
9750** enough information about the compound query is known at that point.
9751** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9752** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9753** sequences for the ORDER BY clause.
9754*/
9755struct Select {
9756  ExprList *pEList;      /* The fields of the result */
9757  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9758  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9759  u16 selFlags;          /* Various SF_* values */
9760  SrcList *pSrc;         /* The FROM clause */
9761  Expr *pWhere;          /* The WHERE clause */
9762  ExprList *pGroupBy;    /* The GROUP BY clause */
9763  Expr *pHaving;         /* The HAVING clause */
9764  ExprList *pOrderBy;    /* The ORDER BY clause */
9765  Select *pPrior;        /* Prior select in a compound select statement */
9766  Select *pNext;         /* Next select to the left in a compound */
9767  Select *pRightmost;    /* Right-most select in a compound select statement */
9768  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9769  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9770  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9771  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9772};
9773
9774/*
9775** Allowed values for Select.selFlags.  The "SF" prefix stands for
9776** "Select Flag".
9777*/
9778#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9779#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9780#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9781#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9782#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9783#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9784
9785
9786/*
9787** The results of a select can be distributed in several ways.  The
9788** "SRT" prefix means "SELECT Result Type".
9789*/
9790#define SRT_Union        1  /* Store result as keys in an index */
9791#define SRT_Except       2  /* Remove result from a UNION index */
9792#define SRT_Exists       3  /* Store 1 if the result is not empty */
9793#define SRT_Discard      4  /* Do not save the results anywhere */
9794
9795/* The ORDER BY clause is ignored for all of the above */
9796#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9797
9798#define SRT_Output       5  /* Output each row of result */
9799#define SRT_Mem          6  /* Store result in a memory cell */
9800#define SRT_Set          7  /* Store results as keys in an index */
9801#define SRT_Table        8  /* Store result as data with an automatic rowid */
9802#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9803#define SRT_Coroutine   10  /* Generate a single row of result */
9804
9805/*
9806** A structure used to customize the behavior of sqlite3Select(). See
9807** comments above sqlite3Select() for details.
9808*/
9809typedef struct SelectDest SelectDest;
9810struct SelectDest {
9811  u8 eDest;         /* How to dispose of the results */
9812  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9813  int iParm;        /* A parameter used by the eDest disposal method */
9814  int iMem;         /* Base register where results are written */
9815  int nMem;         /* Number of registers allocated */
9816};
9817
9818/*
9819** During code generation of statements that do inserts into AUTOINCREMENT
9820** tables, the following information is attached to the Table.u.autoInc.p
9821** pointer of each autoincrement table to record some side information that
9822** the code generator needs.  We have to keep per-table autoincrement
9823** information in case inserts are down within triggers.  Triggers do not
9824** normally coordinate their activities, but we do need to coordinate the
9825** loading and saving of autoincrement information.
9826*/
9827struct AutoincInfo {
9828  AutoincInfo *pNext;   /* Next info block in a list of them all */
9829  Table *pTab;          /* Table this info block refers to */
9830  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9831  int regCtr;           /* Memory register holding the rowid counter */
9832};
9833
9834/*
9835** Size of the column cache
9836*/
9837#ifndef SQLITE_N_COLCACHE
9838# define SQLITE_N_COLCACHE 10
9839#endif
9840
9841/*
9842** At least one instance of the following structure is created for each
9843** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9844** statement. All such objects are stored in the linked list headed at
9845** Parse.pTriggerPrg and deleted once statement compilation has been
9846** completed.
9847**
9848** A Vdbe sub-program that implements the body and WHEN clause of trigger
9849** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9850** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9851** The Parse.pTriggerPrg list never contains two entries with the same
9852** values for both pTrigger and orconf.
9853**
9854** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9855** accessed (or set to 0 for triggers fired as a result of INSERT
9856** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9857** a mask of new.* columns used by the program.
9858*/
9859struct TriggerPrg {
9860  Trigger *pTrigger;      /* Trigger this program was coded from */
9861  int orconf;             /* Default ON CONFLICT policy */
9862  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9863  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9864  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9865};
9866
9867/*
9868** An SQL parser context.  A copy of this structure is passed through
9869** the parser and down into all the parser action routine in order to
9870** carry around information that is global to the entire parse.
9871**
9872** The structure is divided into two parts.  When the parser and code
9873** generate call themselves recursively, the first part of the structure
9874** is constant but the second part is reset at the beginning and end of
9875** each recursion.
9876**
9877** The nTableLock and aTableLock variables are only used if the shared-cache
9878** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9879** used to store the set of table-locks required by the statement being
9880** compiled. Function sqlite3TableLock() is used to add entries to the
9881** list.
9882*/
9883struct Parse {
9884  sqlite3 *db;         /* The main database structure */
9885  int rc;              /* Return code from execution */
9886  char *zErrMsg;       /* An error message */
9887  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9888  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9889  u8 nameClash;        /* A permanent table name clashes with temp table name */
9890  u8 checkSchema;      /* Causes schema cookie check after an error */
9891  u8 nested;           /* Number of nested calls to the parser/code generator */
9892  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9893  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9894  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9895  int aTempReg[8];     /* Holding area for temporary registers */
9896  int nRangeReg;       /* Size of the temporary register block */
9897  int iRangeReg;       /* First register in temporary register block */
9898  int nErr;            /* Number of errors seen */
9899  int nTab;            /* Number of previously allocated VDBE cursors */
9900  int nMem;            /* Number of memory cells used so far */
9901  int nSet;            /* Number of sets used so far */
9902  int ckBase;          /* Base register of data during check constraints */
9903  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9904  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9905  u8 nColCache;        /* Number of entries in the column cache */
9906  u8 iColCache;        /* Next entry of the cache to replace */
9907  struct yColCache {
9908    int iTable;           /* Table cursor number */
9909    int iColumn;          /* Table column number */
9910    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9911    int iLevel;           /* Nesting level */
9912    int iReg;             /* Reg with value of this column. 0 means none. */
9913    int lru;              /* Least recently used entry has the smallest value */
9914  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9915  u32 writeMask;       /* Start a write transaction on these databases */
9916  u32 cookieMask;      /* Bitmask of schema verified databases */
9917  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9918  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9919  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9920  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9921#ifndef SQLITE_OMIT_SHARED_CACHE
9922  int nTableLock;        /* Number of locks in aTableLock */
9923  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9924#endif
9925  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9926  int regRoot;         /* Register holding root page number for new objects */
9927  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9928  int nMaxArg;         /* Max args passed to user function by sub-program */
9929
9930  /* Information used while coding trigger programs. */
9931  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9932  Table *pTriggerTab;  /* Table triggers are being coded for */
9933  u32 oldmask;         /* Mask of old.* columns referenced */
9934  u32 newmask;         /* Mask of new.* columns referenced */
9935  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9936  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9937  u8 disableTriggers;  /* True to disable triggers */
9938  double nQueryLoop;   /* Estimated number of iterations of a query */
9939
9940  /* Above is constant between recursions.  Below is reset before and after
9941  ** each recursion */
9942
9943  int nVar;            /* Number of '?' variables seen in the SQL so far */
9944  int nVarExpr;        /* Number of used slots in apVarExpr[] */
9945  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9946  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9947  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9948  int nAlias;          /* Number of aliased result set columns */
9949  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9950  int *aAlias;         /* Register used to hold aliased result */
9951  u8 explain;          /* True if the EXPLAIN flag is found on the query */
9952  Token sNameToken;    /* Token with unqualified schema object name */
9953  Token sLastToken;    /* The last token parsed */
9954  const char *zTail;   /* All SQL text past the last semicolon parsed */
9955  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9956  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9957  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9958#ifndef SQLITE_OMIT_VIRTUALTABLE
9959  Token sArg;                /* Complete text of a module argument */
9960  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9961  int nVtabLock;             /* Number of virtual tables to lock */
9962  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9963#endif
9964  int nHeight;            /* Expression tree height of current sub-select */
9965  Table *pZombieTab;      /* List of Table objects to delete after code gen */
9966  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9967};
9968
9969#ifdef SQLITE_OMIT_VIRTUALTABLE
9970  #define IN_DECLARE_VTAB 0
9971#else
9972  #define IN_DECLARE_VTAB (pParse->declareVtab)
9973#endif
9974
9975/*
9976** An instance of the following structure can be declared on a stack and used
9977** to save the Parse.zAuthContext value so that it can be restored later.
9978*/
9979struct AuthContext {
9980  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9981  Parse *pParse;              /* The Parse structure */
9982};
9983
9984/*
9985** Bitfield flags for P5 value in OP_Insert and OP_Delete
9986*/
9987#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9988#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9989#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9990#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9991#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9992#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9993
9994/*
9995 * Each trigger present in the database schema is stored as an instance of
9996 * struct Trigger.
9997 *
9998 * Pointers to instances of struct Trigger are stored in two ways.
9999 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10000 *    database). This allows Trigger structures to be retrieved by name.
10001 * 2. All triggers associated with a single table form a linked list, using the
10002 *    pNext member of struct Trigger. A pointer to the first element of the
10003 *    linked list is stored as the "pTrigger" member of the associated
10004 *    struct Table.
10005 *
10006 * The "step_list" member points to the first element of a linked list
10007 * containing the SQL statements specified as the trigger program.
10008 */
10009struct Trigger {
10010  char *zName;            /* The name of the trigger                        */
10011  char *table;            /* The table or view to which the trigger applies */
10012  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10013  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10014  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10015  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10016                             the <column-list> is stored here */
10017  Schema *pSchema;        /* Schema containing the trigger */
10018  Schema *pTabSchema;     /* Schema containing the table */
10019  TriggerStep *step_list; /* Link list of trigger program steps             */
10020  Trigger *pNext;         /* Next trigger associated with the table */
10021};
10022
10023/*
10024** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10025** determine which.
10026**
10027** If there are multiple triggers, you might of some BEFORE and some AFTER.
10028** In that cases, the constants below can be ORed together.
10029*/
10030#define TRIGGER_BEFORE  1
10031#define TRIGGER_AFTER   2
10032
10033/*
10034 * An instance of struct TriggerStep is used to store a single SQL statement
10035 * that is a part of a trigger-program.
10036 *
10037 * Instances of struct TriggerStep are stored in a singly linked list (linked
10038 * using the "pNext" member) referenced by the "step_list" member of the
10039 * associated struct Trigger instance. The first element of the linked list is
10040 * the first step of the trigger-program.
10041 *
10042 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10043 * "SELECT" statement. The meanings of the other members is determined by the
10044 * value of "op" as follows:
10045 *
10046 * (op == TK_INSERT)
10047 * orconf    -> stores the ON CONFLICT algorithm
10048 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10049 *              this stores a pointer to the SELECT statement. Otherwise NULL.
10050 * target    -> A token holding the quoted name of the table to insert into.
10051 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10052 *              this stores values to be inserted. Otherwise NULL.
10053 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
10054 *              statement, then this stores the column-names to be
10055 *              inserted into.
10056 *
10057 * (op == TK_DELETE)
10058 * target    -> A token holding the quoted name of the table to delete from.
10059 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10060 *              Otherwise NULL.
10061 *
10062 * (op == TK_UPDATE)
10063 * target    -> A token holding the quoted name of the table to update rows of.
10064 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10065 *              Otherwise NULL.
10066 * pExprList -> A list of the columns to update and the expressions to update
10067 *              them to. See sqlite3Update() documentation of "pChanges"
10068 *              argument.
10069 *
10070 */
10071struct TriggerStep {
10072  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10073  u8 orconf;           /* OE_Rollback etc. */
10074  Trigger *pTrig;      /* The trigger that this step is a part of */
10075  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10076  Token target;        /* Target table for DELETE, UPDATE, INSERT */
10077  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10078  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10079  IdList *pIdList;     /* Column names for INSERT */
10080  TriggerStep *pNext;  /* Next in the link-list */
10081  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10082};
10083
10084/*
10085** The following structure contains information used by the sqliteFix...
10086** routines as they walk the parse tree to make database references
10087** explicit.
10088*/
10089typedef struct DbFixer DbFixer;
10090struct DbFixer {
10091  Parse *pParse;      /* The parsing context.  Error messages written here */
10092  const char *zDb;    /* Make sure all objects are contained in this database */
10093  const char *zType;  /* Type of the container - used for error messages */
10094  const Token *pName; /* Name of the container - used for error messages */
10095};
10096
10097/*
10098** An objected used to accumulate the text of a string where we
10099** do not necessarily know how big the string will be in the end.
10100*/
10101struct StrAccum {
10102  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10103  char *zBase;         /* A base allocation.  Not from malloc. */
10104  char *zText;         /* The string collected so far */
10105  int  nChar;          /* Length of the string so far */
10106  int  nAlloc;         /* Amount of space allocated in zText */
10107  int  mxAlloc;        /* Maximum allowed string length */
10108  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10109  u8   useMalloc;      /* True if zText is enlargeable using realloc */
10110  u8   tooBig;         /* Becomes true if string size exceeds limits */
10111};
10112
10113/*
10114** A pointer to this structure is used to communicate information
10115** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10116*/
10117typedef struct {
10118  sqlite3 *db;        /* The database being initialized */
10119  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10120  char **pzErrMsg;    /* Error message stored here */
10121  int rc;             /* Result code stored here */
10122} InitData;
10123
10124/*
10125** Structure containing global configuration data for the SQLite library.
10126**
10127** This structure also contains some state information.
10128*/
10129struct Sqlite3Config {
10130  int bMemstat;                     /* True to enable memory status */
10131  int bCoreMutex;                   /* True to enable core mutexing */
10132  int bFullMutex;                   /* True to enable full mutexing */
10133  int mxStrlen;                     /* Maximum string length */
10134  int szLookaside;                  /* Default lookaside buffer size */
10135  int nLookaside;                   /* Default lookaside buffer count */
10136  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10137  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10138  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10139  void *pHeap;                      /* Heap storage space */
10140  int nHeap;                        /* Size of pHeap[] */
10141  int mnReq, mxReq;                 /* Min and max heap requests sizes */
10142  void *pScratch;                   /* Scratch memory */
10143  int szScratch;                    /* Size of each scratch buffer */
10144  int nScratch;                     /* Number of scratch buffers */
10145  void *pPage;                      /* Page cache memory */
10146  int szPage;                       /* Size of each page in pPage[] */
10147  int nPage;                        /* Number of pages in pPage[] */
10148  int mxParserStack;                /* maximum depth of the parser stack */
10149  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10150  /* The above might be initialized to non-zero.  The following need to always
10151  ** initially be zero, however. */
10152  int isInit;                       /* True after initialization has finished */
10153  int inProgress;                   /* True while initialization in progress */
10154  int isMutexInit;                  /* True after mutexes are initialized */
10155  int isMallocInit;                 /* True after malloc is initialized */
10156  int isPCacheInit;                 /* True after malloc is initialized */
10157  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10158  int nRefInitMutex;                /* Number of users of pInitMutex */
10159  void (*xLog)(void*,int,const char*); /* Function for logging */
10160  void *pLogArg;                       /* First argument to xLog() */
10161};
10162
10163/*
10164** Context pointer passed down through the tree-walk.
10165*/
10166struct Walker {
10167  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10168  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10169  Parse *pParse;                            /* Parser context.  */
10170  union {                                   /* Extra data for callback */
10171    NameContext *pNC;                          /* Naming context */
10172    int i;                                     /* Integer value */
10173  } u;
10174};
10175
10176/* Forward declarations */
10177SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10178SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10179SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10180SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10181SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10182
10183/*
10184** Return code from the parse-tree walking primitives and their
10185** callbacks.
10186*/
10187#define WRC_Continue    0   /* Continue down into children */
10188#define WRC_Prune       1   /* Omit children but continue walking siblings */
10189#define WRC_Abort       2   /* Abandon the tree walk */
10190
10191/*
10192** Assuming zIn points to the first byte of a UTF-8 character,
10193** advance zIn to point to the first byte of the next UTF-8 character.
10194*/
10195#define SQLITE_SKIP_UTF8(zIn) {                        \
10196  if( (*(zIn++))>=0xc0 ){                              \
10197    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10198  }                                                    \
10199}
10200
10201/*
10202** The SQLITE_*_BKPT macros are substitutes for the error codes with
10203** the same name but without the _BKPT suffix.  These macros invoke
10204** routines that report the line-number on which the error originated
10205** using sqlite3_log().  The routines also provide a convenient place
10206** to set a debugger breakpoint.
10207*/
10208SQLITE_PRIVATE int sqlite3CorruptError(int);
10209SQLITE_PRIVATE int sqlite3MisuseError(int);
10210SQLITE_PRIVATE int sqlite3CantopenError(int);
10211#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10212#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10213#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10214
10215
10216/*
10217** FTS4 is really an extension for FTS3.  It is enabled using the
10218** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10219** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10220*/
10221#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10222# define SQLITE_ENABLE_FTS3
10223#endif
10224
10225/*
10226** The ctype.h header is needed for non-ASCII systems.  It is also
10227** needed by FTS3 when FTS3 is included in the amalgamation.
10228*/
10229#if !defined(SQLITE_ASCII) || \
10230    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10231# include <ctype.h>
10232#endif
10233
10234/*
10235** The following macros mimic the standard library functions toupper(),
10236** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10237** sqlite versions only work for ASCII characters, regardless of locale.
10238*/
10239#ifdef SQLITE_ASCII
10240# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10241# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10242# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10243# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10244# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10245# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10246# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10247#else
10248# define sqlite3Toupper(x)   toupper((unsigned char)(x))
10249# define sqlite3Isspace(x)   isspace((unsigned char)(x))
10250# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10251# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10252# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10253# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10254# define sqlite3Tolower(x)   tolower((unsigned char)(x))
10255#endif
10256
10257/*
10258** Internal function prototypes
10259*/
10260SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10261SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10262SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10263#define sqlite3StrNICmp sqlite3_strnicmp
10264
10265SQLITE_PRIVATE int sqlite3MallocInit(void);
10266SQLITE_PRIVATE void sqlite3MallocEnd(void);
10267SQLITE_PRIVATE void *sqlite3Malloc(int);
10268SQLITE_PRIVATE void *sqlite3MallocZero(int);
10269SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10270SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10271SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10272SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10273SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10274SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10275SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10276SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10277SQLITE_PRIVATE int sqlite3MallocSize(void*);
10278SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10279SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10280SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10281SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10282SQLITE_PRIVATE void sqlite3PageFree(void*);
10283SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10284SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10285SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10286
10287/*
10288** On systems with ample stack space and that support alloca(), make
10289** use of alloca() to obtain space for large automatic objects.  By default,
10290** obtain space from malloc().
10291**
10292** The alloca() routine never returns NULL.  This will cause code paths
10293** that deal with sqlite3StackAlloc() failures to be unreachable.
10294*/
10295#ifdef SQLITE_USE_ALLOCA
10296# define sqlite3StackAllocRaw(D,N)   alloca(N)
10297# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10298# define sqlite3StackFree(D,P)
10299#else
10300# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10301# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10302# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10303#endif
10304
10305#ifdef SQLITE_ENABLE_MEMSYS3
10306SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10307#endif
10308#ifdef SQLITE_ENABLE_MEMSYS5
10309SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10310#endif
10311
10312
10313#ifndef SQLITE_MUTEX_OMIT
10314SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10315SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10316SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10317SQLITE_PRIVATE   int sqlite3MutexInit(void);
10318SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10319#endif
10320
10321SQLITE_PRIVATE int sqlite3StatusValue(int);
10322SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10323SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10324
10325#ifndef SQLITE_OMIT_FLOATING_POINT
10326SQLITE_PRIVATE   int sqlite3IsNaN(double);
10327#else
10328# define sqlite3IsNaN(X)  0
10329#endif
10330
10331SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10332#ifndef SQLITE_OMIT_TRACE
10333SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10334#endif
10335SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10336SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10337SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10338#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10339SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10340#endif
10341#if defined(SQLITE_TEST)
10342SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10343#endif
10344SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10345SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10346SQLITE_PRIVATE int sqlite3Dequote(char*);
10347SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10348SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10349SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10350SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10351SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10352SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10353SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10354SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10355SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10356SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10357SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10358SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10359SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10360SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10361SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10362SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10363SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10364SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10365SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10366SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10367SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10368SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10369SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10370SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10371SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10372SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10373SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10374SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10375SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10376SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10377SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10378SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10379SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10380SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10381SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10382SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10383
10384SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10385SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10386SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10387SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10388SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10389SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10390SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10391
10392SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10393SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10394SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10395SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10396SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10397
10398SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10399
10400#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10401SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10402#else
10403# define sqlite3ViewGetColumnNames(A,B) 0
10404#endif
10405
10406SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10407SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10408#ifndef SQLITE_OMIT_AUTOINCREMENT
10409SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10410SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10411#else
10412# define sqlite3AutoincrementBegin(X)
10413# define sqlite3AutoincrementEnd(X)
10414#endif
10415SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10416SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10417SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10418SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10419SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10420SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10421SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10422                                      Token*, Select*, Expr*, IdList*);
10423SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10424SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10425SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10426SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10427SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10428SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10429SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10430                        Token*, int, int);
10431SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10432SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10433SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10434                         Expr*,ExprList*,int,Expr*,Expr*);
10435SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10436SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10437SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10438SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10439#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10440SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10441#endif
10442SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10443SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10444SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10445SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10446SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10447SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10448SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10449SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10450SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10451SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10452SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10453SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10454SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10455SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10456SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10457SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10458SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10459SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10460SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10461SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10462SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10463SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10464SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10465SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10466SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10467SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10468SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10469SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10470SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10471SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10472SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10473SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10474SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10475SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10476SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10477SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10478SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10479SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10480SQLITE_PRIVATE void sqlite3PrngResetState(void);
10481SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10482SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10483SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10484SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10485SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10486SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10487SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10488SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10489SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10490SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10491SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10492SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10493SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10494SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10495SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10496SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10497SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10498SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10499SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10500                                     int*,int,int,int,int,int*);
10501SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10502SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10503SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10504SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10505SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10506SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10507SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10508SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10509SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10510SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10511SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10512SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10513SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10514SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10515SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10516SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10517SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10518SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10519SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10520
10521#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10522SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10523#endif
10524
10525#ifndef SQLITE_OMIT_TRIGGER
10526SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10527                           Expr*,int, int);
10528SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10529SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10530SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10531SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10532SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10533SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10534                            int, int, int);
10535SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10536  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10537SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10538SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10539SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10540                                        ExprList*,Select*,u8);
10541SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10542SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10543SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10544SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10545SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10546# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10547#else
10548# define sqlite3TriggersExist(B,C,D,E,F) 0
10549# define sqlite3DeleteTrigger(A,B)
10550# define sqlite3DropTriggerPtr(A,B)
10551# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10552# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10553# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10554# define sqlite3TriggerList(X, Y) 0
10555# define sqlite3ParseToplevel(p) p
10556# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10557#endif
10558
10559SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10560SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10561SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10562#ifndef SQLITE_OMIT_AUTHORIZATION
10563SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10564SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10565SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10566SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10567SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10568#else
10569# define sqlite3AuthRead(a,b,c,d)
10570# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10571# define sqlite3AuthContextPush(a,b,c)
10572# define sqlite3AuthContextPop(a)  ((void)(a))
10573#endif
10574SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10575SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10576SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10577                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10578SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10579SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10580SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10581SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10582SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10583SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10584SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10585SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10586SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10587SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10588SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10589SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10590
10591/*
10592** Routines to read and write variable-length integers.  These used to
10593** be defined locally, but now we use the varint routines in the util.c
10594** file.  Code should use the MACRO forms below, as the Varint32 versions
10595** are coded to assume the single byte case is already handled (which
10596** the MACRO form does).
10597*/
10598SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10599SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10600SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10601SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10602SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10603
10604/*
10605** The header of a record consists of a sequence variable-length integers.
10606** These integers are almost always small and are encoded as a single byte.
10607** The following macros take advantage this fact to provide a fast encode
10608** and decode of the integers in a record header.  It is faster for the common
10609** case where the integer is a single byte.  It is a little slower when the
10610** integer is two or more bytes.  But overall it is faster.
10611**
10612** The following expressions are equivalent:
10613**
10614**     x = sqlite3GetVarint32( A, &B );
10615**     x = sqlite3PutVarint32( A, B );
10616**
10617**     x = getVarint32( A, B );
10618**     x = putVarint32( A, B );
10619**
10620*/
10621#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10622#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10623#define getVarint    sqlite3GetVarint
10624#define putVarint    sqlite3PutVarint
10625
10626
10627SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10628SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10629SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10630SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10631SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10632SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10633SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10634SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10635SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10636SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10637SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10638SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10639SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10640SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10641SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10642SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10643SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10644SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10645
10646SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10647SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10648SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10649                        void(*)(void*));
10650SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10651SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10652SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10653#ifdef SQLITE_ENABLE_STAT2
10654SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10655#endif
10656SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10657SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10658#ifndef SQLITE_AMALGAMATION
10659SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10660SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10661SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10662SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10663SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10664#ifndef SQLITE_OMIT_WSD
10665SQLITE_PRIVATE int sqlite3PendingByte;
10666#endif
10667#endif
10668SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10669SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10670SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10671SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10672SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10673SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10674SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10675SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10676SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10677SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10678SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10679SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10680SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10681SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10682SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10683SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10684SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10685SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10686SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10687SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10688SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10689SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10690SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10691SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10692SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10693SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10694SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10695SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10696SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10697SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10698SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10699SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10700  void (*)(sqlite3_context*,int,sqlite3_value **),
10701  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10702SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10703SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10704
10705SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10706SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10707SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10708SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10709SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10710SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10711
10712SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10713SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10714
10715/*
10716** The interface to the LEMON-generated parser
10717*/
10718SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10719SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10720SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10721#ifdef YYTRACKMAXSTACKDEPTH
10722SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10723#endif
10724
10725SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10726#ifndef SQLITE_OMIT_LOAD_EXTENSION
10727SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10728#else
10729# define sqlite3CloseExtensions(X)
10730#endif
10731
10732#ifndef SQLITE_OMIT_SHARED_CACHE
10733SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10734#else
10735  #define sqlite3TableLock(v,w,x,y,z)
10736#endif
10737
10738#ifdef SQLITE_TEST
10739SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10740#endif
10741
10742#ifdef SQLITE_OMIT_VIRTUALTABLE
10743#  define sqlite3VtabClear(Y)
10744#  define sqlite3VtabSync(X,Y) SQLITE_OK
10745#  define sqlite3VtabRollback(X)
10746#  define sqlite3VtabCommit(X)
10747#  define sqlite3VtabInSync(db) 0
10748#  define sqlite3VtabLock(X)
10749#  define sqlite3VtabUnlock(X)
10750#  define sqlite3VtabUnlockList(X)
10751#else
10752SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10753SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10754SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10755SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10756SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10757SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10758SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10759#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10760#endif
10761SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10762SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10763SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10764SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10765SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10766SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10767SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10768SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10769SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10770SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10771SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10772SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10773SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10774SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10775SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10776SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10777SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10778SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10779SQLITE_PRIVATE const char *sqlite3JournalModename(int);
10780SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
10781SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
10782
10783/* Declarations for functions in fkey.c. All of these are replaced by
10784** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10785** key functionality is available. If OMIT_TRIGGER is defined but
10786** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10787** this case foreign keys are parsed, but no other functionality is
10788** provided (enforcement of FK constraints requires the triggers sub-system).
10789*/
10790#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10791SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10792SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10793SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10794SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10795SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10796SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10797#else
10798  #define sqlite3FkActions(a,b,c,d)
10799  #define sqlite3FkCheck(a,b,c,d)
10800  #define sqlite3FkDropTable(a,b,c)
10801  #define sqlite3FkOldmask(a,b)      0
10802  #define sqlite3FkRequired(a,b,c,d) 0
10803#endif
10804#ifndef SQLITE_OMIT_FOREIGN_KEY
10805SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10806#else
10807  #define sqlite3FkDelete(a)
10808#endif
10809
10810
10811/*
10812** Available fault injectors.  Should be numbered beginning with 0.
10813*/
10814#define SQLITE_FAULTINJECTOR_MALLOC     0
10815#define SQLITE_FAULTINJECTOR_COUNT      1
10816
10817/*
10818** The interface to the code in fault.c used for identifying "benign"
10819** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10820** is not defined.
10821*/
10822#ifndef SQLITE_OMIT_BUILTIN_TEST
10823SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10824SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10825#else
10826  #define sqlite3BeginBenignMalloc()
10827  #define sqlite3EndBenignMalloc()
10828#endif
10829
10830#define IN_INDEX_ROWID           1
10831#define IN_INDEX_EPH             2
10832#define IN_INDEX_INDEX           3
10833SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10834
10835#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10836SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10837SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10838SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10839#else
10840  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10841#endif
10842
10843SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10844SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10845SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10846
10847#if SQLITE_MAX_EXPR_DEPTH>0
10848SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10849SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10850SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10851#else
10852  #define sqlite3ExprSetHeight(x,y)
10853  #define sqlite3SelectExprHeight(x) 0
10854  #define sqlite3ExprCheckHeight(x,y)
10855#endif
10856
10857SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10858SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10859
10860#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10861SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10862SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10863SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10864#else
10865  #define sqlite3ConnectionBlocked(x,y)
10866  #define sqlite3ConnectionUnlocked(x)
10867  #define sqlite3ConnectionClosed(x)
10868#endif
10869
10870#ifdef SQLITE_DEBUG
10871SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10872#endif
10873
10874/*
10875** If the SQLITE_ENABLE IOTRACE exists then the global variable
10876** sqlite3IoTrace is a pointer to a printf-like routine used to
10877** print I/O tracing messages.
10878*/
10879#ifdef SQLITE_ENABLE_IOTRACE
10880# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10881SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10882SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10883#else
10884# define IOTRACE(A)
10885# define sqlite3VdbeIOTraceSql(X)
10886#endif
10887
10888/*
10889** These routines are available for the mem2.c debugging memory allocator
10890** only.  They are used to verify that different "types" of memory
10891** allocations are properly tracked by the system.
10892**
10893** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
10894** the MEMTYPE_* macros defined below.  The type must be a bitmask with
10895** a single bit set.
10896**
10897** sqlite3MemdebugHasType() returns true if any of the bits in its second
10898** argument match the type set by the previous sqlite3MemdebugSetType().
10899** sqlite3MemdebugHasType() is intended for use inside assert() statements.
10900** For example:
10901**
10902**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
10903**
10904** Perhaps the most important point is the difference between MEMTYPE_HEAP
10905** and MEMTYPE_DB.  If an allocation is MEMTYPE_DB, that means it might have
10906** been allocated by lookaside, except the allocation was too large or
10907** lookaside was already full.  It is important to verify that allocations
10908** that might have been satisfied by lookaside are not passed back to
10909** non-lookaside free() routines.  Asserts such as the example above are
10910** placed on the non-lookaside free() routines to verify this constraint.
10911**
10912** All of this is no-op for a production build.  It only comes into
10913** play when the SQLITE_MEMDEBUG compile-time option is used.
10914*/
10915#ifdef SQLITE_MEMDEBUG
10916SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
10917SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
10918#else
10919# define sqlite3MemdebugSetType(X,Y)  /* no-op */
10920# define sqlite3MemdebugHasType(X,Y)  1
10921#endif
10922#define MEMTYPE_HEAP     0x01    /* General heap allocations */
10923#define MEMTYPE_DB       0x02    /* Associated with a database connection */
10924#define MEMTYPE_SCRATCH  0x04    /* Scratch allocations */
10925#define MEMTYPE_PCACHE   0x08    /* Page cache allocations */
10926
10927#endif /* _SQLITEINT_H_ */
10928
10929/************** End of sqliteInt.h *******************************************/
10930/************** Begin file global.c ******************************************/
10931/*
10932** 2008 June 13
10933**
10934** The author disclaims copyright to this source code.  In place of
10935** a legal notice, here is a blessing:
10936**
10937**    May you do good and not evil.
10938**    May you find forgiveness for yourself and forgive others.
10939**    May you share freely, never taking more than you give.
10940**
10941*************************************************************************
10942**
10943** This file contains definitions of global variables and contants.
10944*/
10945
10946/* An array to map all upper-case characters into their corresponding
10947** lower-case character.
10948**
10949** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10950** handle case conversions for the UTF character set since the tables
10951** involved are nearly as big or bigger than SQLite itself.
10952*/
10953SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10954#ifdef SQLITE_ASCII
10955      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10956     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10957     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10958     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10959    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10960    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10961    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10962    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10963    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10964    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10965    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10966    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10967    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10968    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10969    252,253,254,255
10970#endif
10971#ifdef SQLITE_EBCDIC
10972      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10973     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10974     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10975     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10976     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10977     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10978     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10979    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10980    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10981    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10982    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10983    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10984    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10985    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10986    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10987    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10988#endif
10989};
10990
10991/*
10992** The following 256 byte lookup table is used to support SQLites built-in
10993** equivalents to the following standard library functions:
10994**
10995**   isspace()                        0x01
10996**   isalpha()                        0x02
10997**   isdigit()                        0x04
10998**   isalnum()                        0x06
10999**   isxdigit()                       0x08
11000**   toupper()                        0x20
11001**   SQLite identifier character      0x40
11002**
11003** Bit 0x20 is set if the mapped character requires translation to upper
11004** case. i.e. if the character is a lower-case ASCII character.
11005** If x is a lower-case ASCII character, then its upper-case equivalent
11006** is (x - 0x20). Therefore toupper() can be implemented as:
11007**
11008**   (x & ~(map[x]&0x20))
11009**
11010** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11011** array. tolower() is used more often than toupper() by SQLite.
11012**
11013** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11014** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11015** non-ASCII UTF character. Hence the test for whether or not a character is
11016** part of an identifier is 0x46.
11017**
11018** SQLite's versions are identical to the standard versions assuming a
11019** locale of "C". They are implemented as macros in sqliteInt.h.
11020*/
11021#ifdef SQLITE_ASCII
11022SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11023  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11024  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11025  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11026  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11027  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11028  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11029  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11030  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11031
11032  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11033  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11034  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11035  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11036  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11037  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11038  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11039  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11040
11041  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11042  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11043  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11044  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11045  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11046  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11047  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11048  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11049
11050  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11051  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11052  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11053  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11054  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11055  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11056  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11057  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11058};
11059#endif
11060
11061
11062
11063/*
11064** The following singleton contains the global configuration for
11065** the SQLite library.
11066*/
11067SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11068   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11069   1,                         /* bCoreMutex */
11070   SQLITE_THREADSAFE==1,      /* bFullMutex */
11071   0x7ffffffe,                /* mxStrlen */
11072   100,                       /* szLookaside */
11073   500,                       /* nLookaside */
11074   {0,0,0,0,0,0,0,0},         /* m */
11075   {0,0,0,0,0,0,0,0,0},       /* mutex */
11076   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11077   (void*)0,                  /* pHeap */
11078   0,                         /* nHeap */
11079   0, 0,                      /* mnHeap, mxHeap */
11080   (void*)0,                  /* pScratch */
11081   0,                         /* szScratch */
11082   0,                         /* nScratch */
11083   (void*)0,                  /* pPage */
11084   0,                         /* szPage */
11085   0,                         /* nPage */
11086   0,                         /* mxParserStack */
11087   0,                         /* sharedCacheEnabled */
11088   /* All the rest should always be initialized to zero */
11089   0,                         /* isInit */
11090   0,                         /* inProgress */
11091   0,                         /* isMutexInit */
11092   0,                         /* isMallocInit */
11093   0,                         /* isPCacheInit */
11094   0,                         /* pInitMutex */
11095   0,                         /* nRefInitMutex */
11096   0,                         /* xLog */
11097   0,                         /* pLogArg */
11098};
11099
11100
11101/*
11102** Hash table for global functions - functions common to all
11103** database connections.  After initialization, this table is
11104** read-only.
11105*/
11106SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11107
11108/*
11109** The value of the "pending" byte must be 0x40000000 (1 byte past the
11110** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11111** the database page that contains the pending byte.  It never attempts
11112** to read or write that page.  The pending byte page is set assign
11113** for use by the VFS layers as space for managing file locks.
11114**
11115** During testing, it is often desirable to move the pending byte to
11116** a different position in the file.  This allows code that has to
11117** deal with the pending byte to run on files that are much smaller
11118** than 1 GiB.  The sqlite3_test_control() interface can be used to
11119** move the pending byte.
11120**
11121** IMPORTANT:  Changing the pending byte to any value other than
11122** 0x40000000 results in an incompatible database file format!
11123** Changing the pending byte during operating results in undefined
11124** and dileterious behavior.
11125*/
11126#ifndef SQLITE_OMIT_WSD
11127SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11128#endif
11129
11130/*
11131** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11132** created by mkopcodeh.awk during compilation.  Data is obtained
11133** from the comments following the "case OP_xxxx:" statements in
11134** the vdbe.c file.
11135*/
11136SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11137
11138/************** End of global.c **********************************************/
11139/************** Begin file ctime.c *******************************************/
11140/*
11141** 2010 February 23
11142**
11143** The author disclaims copyright to this source code.  In place of
11144** a legal notice, here is a blessing:
11145**
11146**    May you do good and not evil.
11147**    May you find forgiveness for yourself and forgive others.
11148**    May you share freely, never taking more than you give.
11149**
11150*************************************************************************
11151**
11152** This file implements routines used to report what compile-time options
11153** SQLite was built with.
11154*/
11155
11156#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11157
11158
11159/*
11160** An array of names of all compile-time options.  This array should
11161** be sorted A-Z.
11162**
11163** This array looks large, but in a typical installation actually uses
11164** only a handful of compile-time options, so most times this array is usually
11165** rather short and uses little memory space.
11166*/
11167static const char * const azCompileOpt[] = {
11168
11169/* These macros are provided to "stringify" the value of the define
11170** for those options in which the value is meaningful. */
11171#define CTIMEOPT_VAL_(opt) #opt
11172#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11173
11174#ifdef SQLITE_32BIT_ROWID
11175  "32BIT_ROWID",
11176#endif
11177#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11178  "4_BYTE_ALIGNED_MALLOC",
11179#endif
11180#ifdef SQLITE_CASE_SENSITIVE_LIKE
11181  "CASE_SENSITIVE_LIKE",
11182#endif
11183#ifdef SQLITE_CHECK_PAGES
11184  "CHECK_PAGES",
11185#endif
11186#ifdef SQLITE_COVERAGE_TEST
11187  "COVERAGE_TEST",
11188#endif
11189#ifdef SQLITE_DEBUG
11190  "DEBUG",
11191#endif
11192#ifdef SQLITE_DEFAULT_LOCKING_MODE
11193  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11194#endif
11195#ifdef SQLITE_DISABLE_DIRSYNC
11196  "DISABLE_DIRSYNC",
11197#endif
11198#ifdef SQLITE_DISABLE_LFS
11199  "DISABLE_LFS",
11200#endif
11201#ifdef SQLITE_ENABLE_ATOMIC_WRITE
11202  "ENABLE_ATOMIC_WRITE",
11203#endif
11204#ifdef SQLITE_ENABLE_CEROD
11205  "ENABLE_CEROD",
11206#endif
11207#ifdef SQLITE_ENABLE_COLUMN_METADATA
11208  "ENABLE_COLUMN_METADATA",
11209#endif
11210#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11211  "ENABLE_EXPENSIVE_ASSERT",
11212#endif
11213#ifdef SQLITE_ENABLE_FTS1
11214  "ENABLE_FTS1",
11215#endif
11216#ifdef SQLITE_ENABLE_FTS2
11217  "ENABLE_FTS2",
11218#endif
11219#ifdef SQLITE_ENABLE_FTS3
11220  "ENABLE_FTS3",
11221#endif
11222#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11223  "ENABLE_FTS3_PARENTHESIS",
11224#endif
11225#ifdef SQLITE_ENABLE_FTS4
11226  "ENABLE_FTS4",
11227#endif
11228#ifdef SQLITE_ENABLE_ICU
11229  "ENABLE_ICU",
11230#endif
11231#ifdef SQLITE_ENABLE_IOTRACE
11232  "ENABLE_IOTRACE",
11233#endif
11234#ifdef SQLITE_ENABLE_LOAD_EXTENSION
11235  "ENABLE_LOAD_EXTENSION",
11236#endif
11237#ifdef SQLITE_ENABLE_LOCKING_STYLE
11238  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11239#endif
11240#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11241  "ENABLE_MEMORY_MANAGEMENT",
11242#endif
11243#ifdef SQLITE_ENABLE_MEMSYS3
11244  "ENABLE_MEMSYS3",
11245#endif
11246#ifdef SQLITE_ENABLE_MEMSYS5
11247  "ENABLE_MEMSYS5",
11248#endif
11249#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11250  "ENABLE_OVERSIZE_CELL_CHECK",
11251#endif
11252#ifdef SQLITE_ENABLE_RTREE
11253  "ENABLE_RTREE",
11254#endif
11255#ifdef SQLITE_ENABLE_STAT2
11256  "ENABLE_STAT2",
11257#endif
11258#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11259  "ENABLE_UNLOCK_NOTIFY",
11260#endif
11261#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11262  "ENABLE_UPDATE_DELETE_LIMIT",
11263#endif
11264#ifdef SQLITE_HAS_CODEC
11265  "HAS_CODEC",
11266#endif
11267#ifdef SQLITE_HAVE_ISNAN
11268  "HAVE_ISNAN",
11269#endif
11270#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11271  "HOMEGROWN_RECURSIVE_MUTEX",
11272#endif
11273#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11274  "IGNORE_AFP_LOCK_ERRORS",
11275#endif
11276#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11277  "IGNORE_FLOCK_LOCK_ERRORS",
11278#endif
11279#ifdef SQLITE_INT64_TYPE
11280  "INT64_TYPE",
11281#endif
11282#ifdef SQLITE_LOCK_TRACE
11283  "LOCK_TRACE",
11284#endif
11285#ifdef SQLITE_MEMDEBUG
11286  "MEMDEBUG",
11287#endif
11288#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11289  "MIXED_ENDIAN_64BIT_FLOAT",
11290#endif
11291#ifdef SQLITE_NO_SYNC
11292  "NO_SYNC",
11293#endif
11294#ifdef SQLITE_OMIT_ALTERTABLE
11295  "OMIT_ALTERTABLE",
11296#endif
11297#ifdef SQLITE_OMIT_ANALYZE
11298  "OMIT_ANALYZE",
11299#endif
11300#ifdef SQLITE_OMIT_ATTACH
11301  "OMIT_ATTACH",
11302#endif
11303#ifdef SQLITE_OMIT_AUTHORIZATION
11304  "OMIT_AUTHORIZATION",
11305#endif
11306#ifdef SQLITE_OMIT_AUTOINCREMENT
11307  "OMIT_AUTOINCREMENT",
11308#endif
11309#ifdef SQLITE_OMIT_AUTOINIT
11310  "OMIT_AUTOINIT",
11311#endif
11312#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11313  "OMIT_AUTOMATIC_INDEX",
11314#endif
11315#ifdef SQLITE_OMIT_AUTOVACUUM
11316  "OMIT_AUTOVACUUM",
11317#endif
11318#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11319  "OMIT_BETWEEN_OPTIMIZATION",
11320#endif
11321#ifdef SQLITE_OMIT_BLOB_LITERAL
11322  "OMIT_BLOB_LITERAL",
11323#endif
11324#ifdef SQLITE_OMIT_BTREECOUNT
11325  "OMIT_BTREECOUNT",
11326#endif
11327#ifdef SQLITE_OMIT_BUILTIN_TEST
11328  "OMIT_BUILTIN_TEST",
11329#endif
11330#ifdef SQLITE_OMIT_CAST
11331  "OMIT_CAST",
11332#endif
11333#ifdef SQLITE_OMIT_CHECK
11334  "OMIT_CHECK",
11335#endif
11336#ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11337  "OMIT_COMPILEOPTION_DIAGS",
11338#endif
11339#ifdef SQLITE_OMIT_COMPLETE
11340  "OMIT_COMPLETE",
11341#endif
11342#ifdef SQLITE_OMIT_COMPOUND_SELECT
11343  "OMIT_COMPOUND_SELECT",
11344#endif
11345#ifdef SQLITE_OMIT_DATETIME_FUNCS
11346  "OMIT_DATETIME_FUNCS",
11347#endif
11348#ifdef SQLITE_OMIT_DECLTYPE
11349  "OMIT_DECLTYPE",
11350#endif
11351#ifdef SQLITE_OMIT_DEPRECATED
11352  "OMIT_DEPRECATED",
11353#endif
11354#ifdef SQLITE_OMIT_DISKIO
11355  "OMIT_DISKIO",
11356#endif
11357#ifdef SQLITE_OMIT_EXPLAIN
11358  "OMIT_EXPLAIN",
11359#endif
11360#ifdef SQLITE_OMIT_FLAG_PRAGMAS
11361  "OMIT_FLAG_PRAGMAS",
11362#endif
11363#ifdef SQLITE_OMIT_FLOATING_POINT
11364  "OMIT_FLOATING_POINT",
11365#endif
11366#ifdef SQLITE_OMIT_FOREIGN_KEY
11367  "OMIT_FOREIGN_KEY",
11368#endif
11369#ifdef SQLITE_OMIT_GET_TABLE
11370  "OMIT_GET_TABLE",
11371#endif
11372#ifdef SQLITE_OMIT_GLOBALRECOVER
11373  "OMIT_GLOBALRECOVER",
11374#endif
11375#ifdef SQLITE_OMIT_INCRBLOB
11376  "OMIT_INCRBLOB",
11377#endif
11378#ifdef SQLITE_OMIT_INTEGRITY_CHECK
11379  "OMIT_INTEGRITY_CHECK",
11380#endif
11381#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11382  "OMIT_LIKE_OPTIMIZATION",
11383#endif
11384#ifdef SQLITE_OMIT_LOAD_EXTENSION
11385  "OMIT_LOAD_EXTENSION",
11386#endif
11387#ifdef SQLITE_OMIT_LOCALTIME
11388  "OMIT_LOCALTIME",
11389#endif
11390#ifdef SQLITE_OMIT_LOOKASIDE
11391  "OMIT_LOOKASIDE",
11392#endif
11393#ifdef SQLITE_OMIT_MEMORYDB
11394  "OMIT_MEMORYDB",
11395#endif
11396#ifdef SQLITE_OMIT_OR_OPTIMIZATION
11397  "OMIT_OR_OPTIMIZATION",
11398#endif
11399#ifdef SQLITE_OMIT_PAGER_PRAGMAS
11400  "OMIT_PAGER_PRAGMAS",
11401#endif
11402#ifdef SQLITE_OMIT_PRAGMA
11403  "OMIT_PRAGMA",
11404#endif
11405#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11406  "OMIT_PROGRESS_CALLBACK",
11407#endif
11408#ifdef SQLITE_OMIT_QUICKBALANCE
11409  "OMIT_QUICKBALANCE",
11410#endif
11411#ifdef SQLITE_OMIT_REINDEX
11412  "OMIT_REINDEX",
11413#endif
11414#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11415  "OMIT_SCHEMA_PRAGMAS",
11416#endif
11417#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11418  "OMIT_SCHEMA_VERSION_PRAGMAS",
11419#endif
11420#ifdef SQLITE_OMIT_SHARED_CACHE
11421  "OMIT_SHARED_CACHE",
11422#endif
11423#ifdef SQLITE_OMIT_SUBQUERY
11424  "OMIT_SUBQUERY",
11425#endif
11426#ifdef SQLITE_OMIT_TCL_VARIABLE
11427  "OMIT_TCL_VARIABLE",
11428#endif
11429#ifdef SQLITE_OMIT_TEMPDB
11430  "OMIT_TEMPDB",
11431#endif
11432#ifdef SQLITE_OMIT_TRACE
11433  "OMIT_TRACE",
11434#endif
11435#ifdef SQLITE_OMIT_TRIGGER
11436  "OMIT_TRIGGER",
11437#endif
11438#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11439  "OMIT_TRUNCATE_OPTIMIZATION",
11440#endif
11441#ifdef SQLITE_OMIT_UTF16
11442  "OMIT_UTF16",
11443#endif
11444#ifdef SQLITE_OMIT_VACUUM
11445  "OMIT_VACUUM",
11446#endif
11447#ifdef SQLITE_OMIT_VIEW
11448  "OMIT_VIEW",
11449#endif
11450#ifdef SQLITE_OMIT_VIRTUALTABLE
11451  "OMIT_VIRTUALTABLE",
11452#endif
11453#ifdef SQLITE_OMIT_WSD
11454  "OMIT_WSD",
11455#endif
11456#ifdef SQLITE_OMIT_XFER_OPT
11457  "OMIT_XFER_OPT",
11458#endif
11459#ifdef SQLITE_PERFORMANCE_TRACE
11460  "PERFORMANCE_TRACE",
11461#endif
11462#ifdef SQLITE_PROXY_DEBUG
11463  "PROXY_DEBUG",
11464#endif
11465#ifdef SQLITE_SECURE_DELETE
11466  "SECURE_DELETE",
11467#endif
11468#ifdef SQLITE_SMALL_STACK
11469  "SMALL_STACK",
11470#endif
11471#ifdef SQLITE_SOUNDEX
11472  "SOUNDEX",
11473#endif
11474#ifdef SQLITE_TCL
11475  "TCL",
11476#endif
11477#ifdef SQLITE_TEMP_STORE
11478  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11479#endif
11480#ifdef SQLITE_TEST
11481  "TEST",
11482#endif
11483#ifdef SQLITE_THREADSAFE
11484  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11485#endif
11486#ifdef SQLITE_USE_ALLOCA
11487  "USE_ALLOCA",
11488#endif
11489#ifdef SQLITE_ZERO_MALLOC
11490  "ZERO_MALLOC"
11491#endif
11492};
11493
11494/*
11495** Given the name of a compile-time option, return true if that option
11496** was used and false if not.
11497**
11498** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11499** is not required for a match.
11500*/
11501SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11502  int i, n;
11503  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11504  n = sqlite3Strlen30(zOptName);
11505
11506  /* Since ArraySize(azCompileOpt) is normally in single digits, a
11507  ** linear search is adequate.  No need for a binary search. */
11508  for(i=0; i<ArraySize(azCompileOpt); i++){
11509    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11510       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11511  }
11512  return 0;
11513}
11514
11515/*
11516** Return the N-th compile-time option string.  If N is out of range,
11517** return a NULL pointer.
11518*/
11519SQLITE_API const char *sqlite3_compileoption_get(int N){
11520  if( N>=0 && N<ArraySize(azCompileOpt) ){
11521    return azCompileOpt[N];
11522  }
11523  return 0;
11524}
11525
11526#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11527
11528/************** End of ctime.c ***********************************************/
11529/************** Begin file status.c ******************************************/
11530/*
11531** 2008 June 18
11532**
11533** The author disclaims copyright to this source code.  In place of
11534** a legal notice, here is a blessing:
11535**
11536**    May you do good and not evil.
11537**    May you find forgiveness for yourself and forgive others.
11538**    May you share freely, never taking more than you give.
11539**
11540*************************************************************************
11541**
11542** This module implements the sqlite3_status() interface and related
11543** functionality.
11544*/
11545
11546/*
11547** Variables in which to record status information.
11548*/
11549typedef struct sqlite3StatType sqlite3StatType;
11550static SQLITE_WSD struct sqlite3StatType {
11551  int nowValue[9];         /* Current value */
11552  int mxValue[9];          /* Maximum value */
11553} sqlite3Stat = { {0,}, {0,} };
11554
11555
11556/* The "wsdStat" macro will resolve to the status information
11557** state vector.  If writable static data is unsupported on the target,
11558** we have to locate the state vector at run-time.  In the more common
11559** case where writable static data is supported, wsdStat can refer directly
11560** to the "sqlite3Stat" state vector declared above.
11561*/
11562#ifdef SQLITE_OMIT_WSD
11563# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11564# define wsdStat x[0]
11565#else
11566# define wsdStatInit
11567# define wsdStat sqlite3Stat
11568#endif
11569
11570/*
11571** Return the current value of a status parameter.
11572*/
11573SQLITE_PRIVATE int sqlite3StatusValue(int op){
11574  wsdStatInit;
11575  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11576  return wsdStat.nowValue[op];
11577}
11578
11579/*
11580** Add N to the value of a status record.  It is assumed that the
11581** caller holds appropriate locks.
11582*/
11583SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11584  wsdStatInit;
11585  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11586  wsdStat.nowValue[op] += N;
11587  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11588    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11589  }
11590}
11591
11592/*
11593** Set the value of a status to X.
11594*/
11595SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11596  wsdStatInit;
11597  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11598  wsdStat.nowValue[op] = X;
11599  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11600    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11601  }
11602}
11603
11604/*
11605** Query status information.
11606**
11607** This implementation assumes that reading or writing an aligned
11608** 32-bit integer is an atomic operation.  If that assumption is not true,
11609** then this routine is not threadsafe.
11610*/
11611SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11612  wsdStatInit;
11613  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11614    return SQLITE_MISUSE_BKPT;
11615  }
11616  *pCurrent = wsdStat.nowValue[op];
11617  *pHighwater = wsdStat.mxValue[op];
11618  if( resetFlag ){
11619    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11620  }
11621  return SQLITE_OK;
11622}
11623
11624/*
11625** Query status information for a single database connection
11626*/
11627SQLITE_API int sqlite3_db_status(
11628  sqlite3 *db,          /* The database connection whose status is desired */
11629  int op,               /* Status verb */
11630  int *pCurrent,        /* Write current value here */
11631  int *pHighwater,      /* Write high-water mark here */
11632  int resetFlag         /* Reset high-water mark if true */
11633){
11634  switch( op ){
11635    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11636      *pCurrent = db->lookaside.nOut;
11637      *pHighwater = db->lookaside.mxOut;
11638      if( resetFlag ){
11639        db->lookaside.mxOut = db->lookaside.nOut;
11640      }
11641      break;
11642    }
11643
11644    /*
11645    ** Return an approximation for the amount of memory currently used
11646    ** by all pagers associated with the given database connection.  The
11647    ** highwater mark is meaningless and is returned as zero.
11648    */
11649    case SQLITE_DBSTATUS_CACHE_USED: {
11650      int totalUsed = 0;
11651      int i;
11652      for(i=0; i<db->nDb; i++){
11653        Btree *pBt = db->aDb[i].pBt;
11654        if( pBt ){
11655          Pager *pPager = sqlite3BtreePager(pBt);
11656          totalUsed += sqlite3PagerMemUsed(pPager);
11657        }
11658      }
11659      *pCurrent = totalUsed;
11660      *pHighwater = 0;
11661      break;
11662    }
11663    default: {
11664      return SQLITE_ERROR;
11665    }
11666  }
11667  return SQLITE_OK;
11668}
11669
11670/************** End of status.c **********************************************/
11671/************** Begin file date.c ********************************************/
11672/*
11673** 2003 October 31
11674**
11675** The author disclaims copyright to this source code.  In place of
11676** a legal notice, here is a blessing:
11677**
11678**    May you do good and not evil.
11679**    May you find forgiveness for yourself and forgive others.
11680**    May you share freely, never taking more than you give.
11681**
11682*************************************************************************
11683** This file contains the C functions that implement date and time
11684** functions for SQLite.
11685**
11686** There is only one exported symbol in this file - the function
11687** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11688** All other code has file scope.
11689**
11690** SQLite processes all times and dates as Julian Day numbers.  The
11691** dates and times are stored as the number of days since noon
11692** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11693** calendar system.
11694**
11695** 1970-01-01 00:00:00 is JD 2440587.5
11696** 2000-01-01 00:00:00 is JD 2451544.5
11697**
11698** This implemention requires years to be expressed as a 4-digit number
11699** which means that only dates between 0000-01-01 and 9999-12-31 can
11700** be represented, even though julian day numbers allow a much wider
11701** range of dates.
11702**
11703** The Gregorian calendar system is used for all dates and times,
11704** even those that predate the Gregorian calendar.  Historians usually
11705** use the Julian calendar for dates prior to 1582-10-15 and for some
11706** dates afterwards, depending on locale.  Beware of this difference.
11707**
11708** The conversion algorithms are implemented based on descriptions
11709** in the following text:
11710**
11711**      Jean Meeus
11712**      Astronomical Algorithms, 2nd Edition, 1998
11713**      ISBM 0-943396-61-1
11714**      Willmann-Bell, Inc
11715**      Richmond, Virginia (USA)
11716*/
11717#include <time.h>
11718
11719#ifndef SQLITE_OMIT_DATETIME_FUNCS
11720
11721/*
11722** On recent Windows platforms, the localtime_s() function is available
11723** as part of the "Secure CRT". It is essentially equivalent to
11724** localtime_r() available under most POSIX platforms, except that the
11725** order of the parameters is reversed.
11726**
11727** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11728**
11729** If the user has not indicated to use localtime_r() or localtime_s()
11730** already, check for an MSVC build environment that provides
11731** localtime_s().
11732*/
11733#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11734     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11735#define HAVE_LOCALTIME_S 1
11736#endif
11737
11738/*
11739** A structure for holding a single date and time.
11740*/
11741typedef struct DateTime DateTime;
11742struct DateTime {
11743  sqlite3_int64 iJD; /* The julian day number times 86400000 */
11744  int Y, M, D;       /* Year, month, and day */
11745  int h, m;          /* Hour and minutes */
11746  int tz;            /* Timezone offset in minutes */
11747  double s;          /* Seconds */
11748  char validYMD;     /* True (1) if Y,M,D are valid */
11749  char validHMS;     /* True (1) if h,m,s are valid */
11750  char validJD;      /* True (1) if iJD is valid */
11751  char validTZ;      /* True (1) if tz is valid */
11752};
11753
11754
11755/*
11756** Convert zDate into one or more integers.  Additional arguments
11757** come in groups of 5 as follows:
11758**
11759**       N       number of digits in the integer
11760**       min     minimum allowed value of the integer
11761**       max     maximum allowed value of the integer
11762**       nextC   first character after the integer
11763**       pVal    where to write the integers value.
11764**
11765** Conversions continue until one with nextC==0 is encountered.
11766** The function returns the number of successful conversions.
11767*/
11768static int getDigits(const char *zDate, ...){
11769  va_list ap;
11770  int val;
11771  int N;
11772  int min;
11773  int max;
11774  int nextC;
11775  int *pVal;
11776  int cnt = 0;
11777  va_start(ap, zDate);
11778  do{
11779    N = va_arg(ap, int);
11780    min = va_arg(ap, int);
11781    max = va_arg(ap, int);
11782    nextC = va_arg(ap, int);
11783    pVal = va_arg(ap, int*);
11784    val = 0;
11785    while( N-- ){
11786      if( !sqlite3Isdigit(*zDate) ){
11787        goto end_getDigits;
11788      }
11789      val = val*10 + *zDate - '0';
11790      zDate++;
11791    }
11792    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11793      goto end_getDigits;
11794    }
11795    *pVal = val;
11796    zDate++;
11797    cnt++;
11798  }while( nextC );
11799end_getDigits:
11800  va_end(ap);
11801  return cnt;
11802}
11803
11804/*
11805** Read text from z[] and convert into a floating point number.  Return
11806** the number of digits converted.
11807*/
11808#define getValue sqlite3AtoF
11809
11810/*
11811** Parse a timezone extension on the end of a date-time.
11812** The extension is of the form:
11813**
11814**        (+/-)HH:MM
11815**
11816** Or the "zulu" notation:
11817**
11818**        Z
11819**
11820** If the parse is successful, write the number of minutes
11821** of change in p->tz and return 0.  If a parser error occurs,
11822** return non-zero.
11823**
11824** A missing specifier is not considered an error.
11825*/
11826static int parseTimezone(const char *zDate, DateTime *p){
11827  int sgn = 0;
11828  int nHr, nMn;
11829  int c;
11830  while( sqlite3Isspace(*zDate) ){ zDate++; }
11831  p->tz = 0;
11832  c = *zDate;
11833  if( c=='-' ){
11834    sgn = -1;
11835  }else if( c=='+' ){
11836    sgn = +1;
11837  }else if( c=='Z' || c=='z' ){
11838    zDate++;
11839    goto zulu_time;
11840  }else{
11841    return c!=0;
11842  }
11843  zDate++;
11844  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11845    return 1;
11846  }
11847  zDate += 5;
11848  p->tz = sgn*(nMn + nHr*60);
11849zulu_time:
11850  while( sqlite3Isspace(*zDate) ){ zDate++; }
11851  return *zDate!=0;
11852}
11853
11854/*
11855** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11856** The HH, MM, and SS must each be exactly 2 digits.  The
11857** fractional seconds FFFF can be one or more digits.
11858**
11859** Return 1 if there is a parsing error and 0 on success.
11860*/
11861static int parseHhMmSs(const char *zDate, DateTime *p){
11862  int h, m, s;
11863  double ms = 0.0;
11864  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11865    return 1;
11866  }
11867  zDate += 5;
11868  if( *zDate==':' ){
11869    zDate++;
11870    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11871      return 1;
11872    }
11873    zDate += 2;
11874    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11875      double rScale = 1.0;
11876      zDate++;
11877      while( sqlite3Isdigit(*zDate) ){
11878        ms = ms*10.0 + *zDate - '0';
11879        rScale *= 10.0;
11880        zDate++;
11881      }
11882      ms /= rScale;
11883    }
11884  }else{
11885    s = 0;
11886  }
11887  p->validJD = 0;
11888  p->validHMS = 1;
11889  p->h = h;
11890  p->m = m;
11891  p->s = s + ms;
11892  if( parseTimezone(zDate, p) ) return 1;
11893  p->validTZ = (p->tz!=0)?1:0;
11894  return 0;
11895}
11896
11897/*
11898** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11899** that the YYYY-MM-DD is according to the Gregorian calendar.
11900**
11901** Reference:  Meeus page 61
11902*/
11903static void computeJD(DateTime *p){
11904  int Y, M, D, A, B, X1, X2;
11905
11906  if( p->validJD ) return;
11907  if( p->validYMD ){
11908    Y = p->Y;
11909    M = p->M;
11910    D = p->D;
11911  }else{
11912    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11913    M = 1;
11914    D = 1;
11915  }
11916  if( M<=2 ){
11917    Y--;
11918    M += 12;
11919  }
11920  A = Y/100;
11921  B = 2 - A + (A/4);
11922  X1 = 36525*(Y+4716)/100;
11923  X2 = 306001*(M+1)/10000;
11924  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11925  p->validJD = 1;
11926  if( p->validHMS ){
11927    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11928    if( p->validTZ ){
11929      p->iJD -= p->tz*60000;
11930      p->validYMD = 0;
11931      p->validHMS = 0;
11932      p->validTZ = 0;
11933    }
11934  }
11935}
11936
11937/*
11938** Parse dates of the form
11939**
11940**     YYYY-MM-DD HH:MM:SS.FFF
11941**     YYYY-MM-DD HH:MM:SS
11942**     YYYY-MM-DD HH:MM
11943**     YYYY-MM-DD
11944**
11945** Write the result into the DateTime structure and return 0
11946** on success and 1 if the input string is not a well-formed
11947** date.
11948*/
11949static int parseYyyyMmDd(const char *zDate, DateTime *p){
11950  int Y, M, D, neg;
11951
11952  if( zDate[0]=='-' ){
11953    zDate++;
11954    neg = 1;
11955  }else{
11956    neg = 0;
11957  }
11958  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11959    return 1;
11960  }
11961  zDate += 10;
11962  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11963  if( parseHhMmSs(zDate, p)==0 ){
11964    /* We got the time */
11965  }else if( *zDate==0 ){
11966    p->validHMS = 0;
11967  }else{
11968    return 1;
11969  }
11970  p->validJD = 0;
11971  p->validYMD = 1;
11972  p->Y = neg ? -Y : Y;
11973  p->M = M;
11974  p->D = D;
11975  if( p->validTZ ){
11976    computeJD(p);
11977  }
11978  return 0;
11979}
11980
11981/*
11982** Set the time to the current time reported by the VFS
11983*/
11984static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11985  sqlite3 *db = sqlite3_context_db_handle(context);
11986  sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
11987  p->validJD = 1;
11988}
11989
11990/*
11991** Attempt to parse the given string into a Julian Day Number.  Return
11992** the number of errors.
11993**
11994** The following are acceptable forms for the input string:
11995**
11996**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11997**      DDDD.DD
11998**      now
11999**
12000** In the first form, the +/-HH:MM is always optional.  The fractional
12001** seconds extension (the ".FFF") is optional.  The seconds portion
12002** (":SS.FFF") is option.  The year and date can be omitted as long
12003** as there is a time string.  The time string can be omitted as long
12004** as there is a year and date.
12005*/
12006static int parseDateOrTime(
12007  sqlite3_context *context,
12008  const char *zDate,
12009  DateTime *p
12010){
12011  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
12012  if( parseYyyyMmDd(zDate,p)==0 ){
12013    return 0;
12014  }else if( parseHhMmSs(zDate, p)==0 ){
12015    return 0;
12016  }else if( sqlite3StrICmp(zDate,"now")==0){
12017    setDateTimeToCurrent(context, p);
12018    return 0;
12019  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
12020    double r;
12021    getValue(zDate, &r);
12022    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12023    p->validJD = 1;
12024    return 0;
12025  }
12026  return 1;
12027}
12028
12029/*
12030** Compute the Year, Month, and Day from the julian day number.
12031*/
12032static void computeYMD(DateTime *p){
12033  int Z, A, B, C, D, E, X1;
12034  if( p->validYMD ) return;
12035  if( !p->validJD ){
12036    p->Y = 2000;
12037    p->M = 1;
12038    p->D = 1;
12039  }else{
12040    Z = (int)((p->iJD + 43200000)/86400000);
12041    A = (int)((Z - 1867216.25)/36524.25);
12042    A = Z + 1 + A - (A/4);
12043    B = A + 1524;
12044    C = (int)((B - 122.1)/365.25);
12045    D = (36525*C)/100;
12046    E = (int)((B-D)/30.6001);
12047    X1 = (int)(30.6001*E);
12048    p->D = B - D - X1;
12049    p->M = E<14 ? E-1 : E-13;
12050    p->Y = p->M>2 ? C - 4716 : C - 4715;
12051  }
12052  p->validYMD = 1;
12053}
12054
12055/*
12056** Compute the Hour, Minute, and Seconds from the julian day number.
12057*/
12058static void computeHMS(DateTime *p){
12059  int s;
12060  if( p->validHMS ) return;
12061  computeJD(p);
12062  s = (int)((p->iJD + 43200000) % 86400000);
12063  p->s = s/1000.0;
12064  s = (int)p->s;
12065  p->s -= s;
12066  p->h = s/3600;
12067  s -= p->h*3600;
12068  p->m = s/60;
12069  p->s += s - p->m*60;
12070  p->validHMS = 1;
12071}
12072
12073/*
12074** Compute both YMD and HMS
12075*/
12076static void computeYMD_HMS(DateTime *p){
12077  computeYMD(p);
12078  computeHMS(p);
12079}
12080
12081/*
12082** Clear the YMD and HMS and the TZ
12083*/
12084static void clearYMD_HMS_TZ(DateTime *p){
12085  p->validYMD = 0;
12086  p->validHMS = 0;
12087  p->validTZ = 0;
12088}
12089
12090#ifndef SQLITE_OMIT_LOCALTIME
12091/*
12092** Compute the difference (in milliseconds)
12093** between localtime and UTC (a.k.a. GMT)
12094** for the time value p where p is in UTC.
12095*/
12096static sqlite3_int64 localtimeOffset(DateTime *p){
12097  DateTime x, y;
12098  time_t t;
12099  x = *p;
12100  computeYMD_HMS(&x);
12101  if( x.Y<1971 || x.Y>=2038 ){
12102    x.Y = 2000;
12103    x.M = 1;
12104    x.D = 1;
12105    x.h = 0;
12106    x.m = 0;
12107    x.s = 0.0;
12108  } else {
12109    int s = (int)(x.s + 0.5);
12110    x.s = s;
12111  }
12112  x.tz = 0;
12113  x.validJD = 0;
12114  computeJD(&x);
12115  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12116#ifdef HAVE_LOCALTIME_R
12117  {
12118    struct tm sLocal;
12119    localtime_r(&t, &sLocal);
12120    y.Y = sLocal.tm_year + 1900;
12121    y.M = sLocal.tm_mon + 1;
12122    y.D = sLocal.tm_mday;
12123    y.h = sLocal.tm_hour;
12124    y.m = sLocal.tm_min;
12125    y.s = sLocal.tm_sec;
12126  }
12127#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12128  {
12129    struct tm sLocal;
12130    localtime_s(&sLocal, &t);
12131    y.Y = sLocal.tm_year + 1900;
12132    y.M = sLocal.tm_mon + 1;
12133    y.D = sLocal.tm_mday;
12134    y.h = sLocal.tm_hour;
12135    y.m = sLocal.tm_min;
12136    y.s = sLocal.tm_sec;
12137  }
12138#else
12139  {
12140    struct tm *pTm;
12141    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12142    pTm = localtime(&t);
12143    y.Y = pTm->tm_year + 1900;
12144    y.M = pTm->tm_mon + 1;
12145    y.D = pTm->tm_mday;
12146    y.h = pTm->tm_hour;
12147    y.m = pTm->tm_min;
12148    y.s = pTm->tm_sec;
12149    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12150  }
12151#endif
12152  y.validYMD = 1;
12153  y.validHMS = 1;
12154  y.validJD = 0;
12155  y.validTZ = 0;
12156  computeJD(&y);
12157  return y.iJD - x.iJD;
12158}
12159#endif /* SQLITE_OMIT_LOCALTIME */
12160
12161/*
12162** Process a modifier to a date-time stamp.  The modifiers are
12163** as follows:
12164**
12165**     NNN days
12166**     NNN hours
12167**     NNN minutes
12168**     NNN.NNNN seconds
12169**     NNN months
12170**     NNN years
12171**     start of month
12172**     start of year
12173**     start of week
12174**     start of day
12175**     weekday N
12176**     unixepoch
12177**     localtime
12178**     utc
12179**
12180** Return 0 on success and 1 if there is any kind of error.
12181*/
12182static int parseModifier(const char *zMod, DateTime *p){
12183  int rc = 1;
12184  int n;
12185  double r;
12186  char *z, zBuf[30];
12187  z = zBuf;
12188  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12189    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12190  }
12191  z[n] = 0;
12192  switch( z[0] ){
12193#ifndef SQLITE_OMIT_LOCALTIME
12194    case 'l': {
12195      /*    localtime
12196      **
12197      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12198      ** show local time.
12199      */
12200      if( strcmp(z, "localtime")==0 ){
12201        computeJD(p);
12202        p->iJD += localtimeOffset(p);
12203        clearYMD_HMS_TZ(p);
12204        rc = 0;
12205      }
12206      break;
12207    }
12208#endif
12209    case 'u': {
12210      /*
12211      **    unixepoch
12212      **
12213      ** Treat the current value of p->iJD as the number of
12214      ** seconds since 1970.  Convert to a real julian day number.
12215      */
12216      if( strcmp(z, "unixepoch")==0 && p->validJD ){
12217        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
12218        clearYMD_HMS_TZ(p);
12219        rc = 0;
12220      }
12221#ifndef SQLITE_OMIT_LOCALTIME
12222      else if( strcmp(z, "utc")==0 ){
12223        sqlite3_int64 c1;
12224        computeJD(p);
12225        c1 = localtimeOffset(p);
12226        p->iJD -= c1;
12227        clearYMD_HMS_TZ(p);
12228        p->iJD += c1 - localtimeOffset(p);
12229        rc = 0;
12230      }
12231#endif
12232      break;
12233    }
12234    case 'w': {
12235      /*
12236      **    weekday N
12237      **
12238      ** Move the date to the same time on the next occurrence of
12239      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12240      ** date is already on the appropriate weekday, this is a no-op.
12241      */
12242      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12243                 && (n=(int)r)==r && n>=0 && r<7 ){
12244        sqlite3_int64 Z;
12245        computeYMD_HMS(p);
12246        p->validTZ = 0;
12247        p->validJD = 0;
12248        computeJD(p);
12249        Z = ((p->iJD + 129600000)/86400000) % 7;
12250        if( Z>n ) Z -= 7;
12251        p->iJD += (n - Z)*86400000;
12252        clearYMD_HMS_TZ(p);
12253        rc = 0;
12254      }
12255      break;
12256    }
12257    case 's': {
12258      /*
12259      **    start of TTTTT
12260      **
12261      ** Move the date backwards to the beginning of the current day,
12262      ** or month or year.
12263      */
12264      if( strncmp(z, "start of ", 9)!=0 ) break;
12265      z += 9;
12266      computeYMD(p);
12267      p->validHMS = 1;
12268      p->h = p->m = 0;
12269      p->s = 0.0;
12270      p->validTZ = 0;
12271      p->validJD = 0;
12272      if( strcmp(z,"month")==0 ){
12273        p->D = 1;
12274        rc = 0;
12275      }else if( strcmp(z,"year")==0 ){
12276        computeYMD(p);
12277        p->M = 1;
12278        p->D = 1;
12279        rc = 0;
12280      }else if( strcmp(z,"day")==0 ){
12281        rc = 0;
12282      }
12283      break;
12284    }
12285    case '+':
12286    case '-':
12287    case '0':
12288    case '1':
12289    case '2':
12290    case '3':
12291    case '4':
12292    case '5':
12293    case '6':
12294    case '7':
12295    case '8':
12296    case '9': {
12297      double rRounder;
12298      n = getValue(z, &r);
12299      assert( n>=1 );
12300      if( z[n]==':' ){
12301        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12302        ** specified number of hours, minutes, seconds, and fractional seconds
12303        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12304        ** omitted.
12305        */
12306        const char *z2 = z;
12307        DateTime tx;
12308        sqlite3_int64 day;
12309        if( !sqlite3Isdigit(*z2) ) z2++;
12310        memset(&tx, 0, sizeof(tx));
12311        if( parseHhMmSs(z2, &tx) ) break;
12312        computeJD(&tx);
12313        tx.iJD -= 43200000;
12314        day = tx.iJD/86400000;
12315        tx.iJD -= day*86400000;
12316        if( z[0]=='-' ) tx.iJD = -tx.iJD;
12317        computeJD(p);
12318        clearYMD_HMS_TZ(p);
12319        p->iJD += tx.iJD;
12320        rc = 0;
12321        break;
12322      }
12323      z += n;
12324      while( sqlite3Isspace(*z) ) z++;
12325      n = sqlite3Strlen30(z);
12326      if( n>10 || n<3 ) break;
12327      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12328      computeJD(p);
12329      rc = 0;
12330      rRounder = r<0 ? -0.5 : +0.5;
12331      if( n==3 && strcmp(z,"day")==0 ){
12332        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12333      }else if( n==4 && strcmp(z,"hour")==0 ){
12334        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12335      }else if( n==6 && strcmp(z,"minute")==0 ){
12336        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12337      }else if( n==6 && strcmp(z,"second")==0 ){
12338        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12339      }else if( n==5 && strcmp(z,"month")==0 ){
12340        int x, y;
12341        computeYMD_HMS(p);
12342        p->M += (int)r;
12343        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12344        p->Y += x;
12345        p->M -= x*12;
12346        p->validJD = 0;
12347        computeJD(p);
12348        y = (int)r;
12349        if( y!=r ){
12350          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12351        }
12352      }else if( n==4 && strcmp(z,"year")==0 ){
12353        int y = (int)r;
12354        computeYMD_HMS(p);
12355        p->Y += y;
12356        p->validJD = 0;
12357        computeJD(p);
12358        if( y!=r ){
12359          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12360        }
12361      }else{
12362        rc = 1;
12363      }
12364      clearYMD_HMS_TZ(p);
12365      break;
12366    }
12367    default: {
12368      break;
12369    }
12370  }
12371  return rc;
12372}
12373
12374/*
12375** Process time function arguments.  argv[0] is a date-time stamp.
12376** argv[1] and following are modifiers.  Parse them all and write
12377** the resulting time into the DateTime structure p.  Return 0
12378** on success and 1 if there are any errors.
12379**
12380** If there are zero parameters (if even argv[0] is undefined)
12381** then assume a default value of "now" for argv[0].
12382*/
12383static int isDate(
12384  sqlite3_context *context,
12385  int argc,
12386  sqlite3_value **argv,
12387  DateTime *p
12388){
12389  int i;
12390  const unsigned char *z;
12391  int eType;
12392  memset(p, 0, sizeof(*p));
12393  if( argc==0 ){
12394    setDateTimeToCurrent(context, p);
12395  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12396                   || eType==SQLITE_INTEGER ){
12397    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12398    p->validJD = 1;
12399  }else{
12400    z = sqlite3_value_text(argv[0]);
12401    if( !z || parseDateOrTime(context, (char*)z, p) ){
12402      return 1;
12403    }
12404  }
12405  for(i=1; i<argc; i++){
12406    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12407      return 1;
12408    }
12409  }
12410  return 0;
12411}
12412
12413
12414/*
12415** The following routines implement the various date and time functions
12416** of SQLite.
12417*/
12418
12419/*
12420**    julianday( TIMESTRING, MOD, MOD, ...)
12421**
12422** Return the julian day number of the date specified in the arguments
12423*/
12424static void juliandayFunc(
12425  sqlite3_context *context,
12426  int argc,
12427  sqlite3_value **argv
12428){
12429  DateTime x;
12430  if( isDate(context, argc, argv, &x)==0 ){
12431    computeJD(&x);
12432    sqlite3_result_double(context, x.iJD/86400000.0);
12433  }
12434}
12435
12436/*
12437**    datetime( TIMESTRING, MOD, MOD, ...)
12438**
12439** Return YYYY-MM-DD HH:MM:SS
12440*/
12441static void datetimeFunc(
12442  sqlite3_context *context,
12443  int argc,
12444  sqlite3_value **argv
12445){
12446  DateTime x;
12447  if( isDate(context, argc, argv, &x)==0 ){
12448    char zBuf[100];
12449    computeYMD_HMS(&x);
12450    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12451                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12452    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12453  }
12454}
12455
12456/*
12457**    time( TIMESTRING, MOD, MOD, ...)
12458**
12459** Return HH:MM:SS
12460*/
12461static void timeFunc(
12462  sqlite3_context *context,
12463  int argc,
12464  sqlite3_value **argv
12465){
12466  DateTime x;
12467  if( isDate(context, argc, argv, &x)==0 ){
12468    char zBuf[100];
12469    computeHMS(&x);
12470    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12471    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12472  }
12473}
12474
12475/*
12476**    date( TIMESTRING, MOD, MOD, ...)
12477**
12478** Return YYYY-MM-DD
12479*/
12480static void dateFunc(
12481  sqlite3_context *context,
12482  int argc,
12483  sqlite3_value **argv
12484){
12485  DateTime x;
12486  if( isDate(context, argc, argv, &x)==0 ){
12487    char zBuf[100];
12488    computeYMD(&x);
12489    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12490    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12491  }
12492}
12493
12494/*
12495**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12496**
12497** Return a string described by FORMAT.  Conversions as follows:
12498**
12499**   %d  day of month
12500**   %f  ** fractional seconds  SS.SSS
12501**   %H  hour 00-24
12502**   %j  day of year 000-366
12503**   %J  ** Julian day number
12504**   %m  month 01-12
12505**   %M  minute 00-59
12506**   %s  seconds since 1970-01-01
12507**   %S  seconds 00-59
12508**   %w  day of week 0-6  sunday==0
12509**   %W  week of year 00-53
12510**   %Y  year 0000-9999
12511**   %%  %
12512*/
12513static void strftimeFunc(
12514  sqlite3_context *context,
12515  int argc,
12516  sqlite3_value **argv
12517){
12518  DateTime x;
12519  u64 n;
12520  size_t i,j;
12521  char *z;
12522  sqlite3 *db;
12523  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12524  char zBuf[100];
12525  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12526  db = sqlite3_context_db_handle(context);
12527  for(i=0, n=1; zFmt[i]; i++, n++){
12528    if( zFmt[i]=='%' ){
12529      switch( zFmt[i+1] ){
12530        case 'd':
12531        case 'H':
12532        case 'm':
12533        case 'M':
12534        case 'S':
12535        case 'W':
12536          n++;
12537          /* fall thru */
12538        case 'w':
12539        case '%':
12540          break;
12541        case 'f':
12542          n += 8;
12543          break;
12544        case 'j':
12545          n += 3;
12546          break;
12547        case 'Y':
12548          n += 8;
12549          break;
12550        case 's':
12551        case 'J':
12552          n += 50;
12553          break;
12554        default:
12555          return;  /* ERROR.  return a NULL */
12556      }
12557      i++;
12558    }
12559  }
12560  testcase( n==sizeof(zBuf)-1 );
12561  testcase( n==sizeof(zBuf) );
12562  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12563  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12564  if( n<sizeof(zBuf) ){
12565    z = zBuf;
12566  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12567    sqlite3_result_error_toobig(context);
12568    return;
12569  }else{
12570    z = sqlite3DbMallocRaw(db, (int)n);
12571    if( z==0 ){
12572      sqlite3_result_error_nomem(context);
12573      return;
12574    }
12575  }
12576  computeJD(&x);
12577  computeYMD_HMS(&x);
12578  for(i=j=0; zFmt[i]; i++){
12579    if( zFmt[i]!='%' ){
12580      z[j++] = zFmt[i];
12581    }else{
12582      i++;
12583      switch( zFmt[i] ){
12584        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12585        case 'f': {
12586          double s = x.s;
12587          if( s>59.999 ) s = 59.999;
12588          sqlite3_snprintf(7, &z[j],"%06.3f", s);
12589          j += sqlite3Strlen30(&z[j]);
12590          break;
12591        }
12592        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12593        case 'W': /* Fall thru */
12594        case 'j': {
12595          int nDay;             /* Number of days since 1st day of year */
12596          DateTime y = x;
12597          y.validJD = 0;
12598          y.M = 1;
12599          y.D = 1;
12600          computeJD(&y);
12601          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12602          if( zFmt[i]=='W' ){
12603            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12604            wd = (int)(((x.iJD+43200000)/86400000)%7);
12605            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12606            j += 2;
12607          }else{
12608            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12609            j += 3;
12610          }
12611          break;
12612        }
12613        case 'J': {
12614          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12615          j+=sqlite3Strlen30(&z[j]);
12616          break;
12617        }
12618        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12619        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12620        case 's': {
12621          sqlite3_snprintf(30,&z[j],"%lld",
12622                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
12623          j += sqlite3Strlen30(&z[j]);
12624          break;
12625        }
12626        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12627        case 'w': {
12628          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12629          break;
12630        }
12631        case 'Y': {
12632          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12633          break;
12634        }
12635        default:   z[j++] = '%'; break;
12636      }
12637    }
12638  }
12639  z[j] = 0;
12640  sqlite3_result_text(context, z, -1,
12641                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12642}
12643
12644/*
12645** current_time()
12646**
12647** This function returns the same value as time('now').
12648*/
12649static void ctimeFunc(
12650  sqlite3_context *context,
12651  int NotUsed,
12652  sqlite3_value **NotUsed2
12653){
12654  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12655  timeFunc(context, 0, 0);
12656}
12657
12658/*
12659** current_date()
12660**
12661** This function returns the same value as date('now').
12662*/
12663static void cdateFunc(
12664  sqlite3_context *context,
12665  int NotUsed,
12666  sqlite3_value **NotUsed2
12667){
12668  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12669  dateFunc(context, 0, 0);
12670}
12671
12672/*
12673** current_timestamp()
12674**
12675** This function returns the same value as datetime('now').
12676*/
12677static void ctimestampFunc(
12678  sqlite3_context *context,
12679  int NotUsed,
12680  sqlite3_value **NotUsed2
12681){
12682  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12683  datetimeFunc(context, 0, 0);
12684}
12685#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12686
12687#ifdef SQLITE_OMIT_DATETIME_FUNCS
12688/*
12689** If the library is compiled to omit the full-scale date and time
12690** handling (to get a smaller binary), the following minimal version
12691** of the functions current_time(), current_date() and current_timestamp()
12692** are included instead. This is to support column declarations that
12693** include "DEFAULT CURRENT_TIME" etc.
12694**
12695** This function uses the C-library functions time(), gmtime()
12696** and strftime(). The format string to pass to strftime() is supplied
12697** as the user-data for the function.
12698*/
12699static void currentTimeFunc(
12700  sqlite3_context *context,
12701  int argc,
12702  sqlite3_value **argv
12703){
12704  time_t t;
12705  char *zFormat = (char *)sqlite3_user_data(context);
12706  sqlite3 *db;
12707  sqlite3_int64 iT;
12708  char zBuf[20];
12709
12710  UNUSED_PARAMETER(argc);
12711  UNUSED_PARAMETER(argv);
12712
12713  db = sqlite3_context_db_handle(context);
12714  sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
12715  t = iT/1000 - 10000*(sqlite3_int64)21086676;
12716#ifdef HAVE_GMTIME_R
12717  {
12718    struct tm sNow;
12719    gmtime_r(&t, &sNow);
12720    strftime(zBuf, 20, zFormat, &sNow);
12721  }
12722#else
12723  {
12724    struct tm *pTm;
12725    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12726    pTm = gmtime(&t);
12727    strftime(zBuf, 20, zFormat, pTm);
12728    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12729  }
12730#endif
12731
12732  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12733}
12734#endif
12735
12736/*
12737** This function registered all of the above C functions as SQL
12738** functions.  This should be the only routine in this file with
12739** external linkage.
12740*/
12741SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12742  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12743#ifndef SQLITE_OMIT_DATETIME_FUNCS
12744    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12745    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12746    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12747    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12748    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12749    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12750    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12751    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12752#else
12753    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12754    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
12755    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12756#endif
12757  };
12758  int i;
12759  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12760  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12761
12762  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12763    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12764  }
12765}
12766
12767/************** End of date.c ************************************************/
12768/************** Begin file os.c **********************************************/
12769/*
12770** 2005 November 29
12771**
12772** The author disclaims copyright to this source code.  In place of
12773** a legal notice, here is a blessing:
12774**
12775**    May you do good and not evil.
12776**    May you find forgiveness for yourself and forgive others.
12777**    May you share freely, never taking more than you give.
12778**
12779******************************************************************************
12780**
12781** This file contains OS interface code that is common to all
12782** architectures.
12783*/
12784#define _SQLITE_OS_C_ 1
12785#undef _SQLITE_OS_C_
12786
12787/*
12788** The default SQLite sqlite3_vfs implementations do not allocate
12789** memory (actually, os_unix.c allocates a small amount of memory
12790** from within OsOpen()), but some third-party implementations may.
12791** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12792** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12793**
12794** The following functions are instrumented for malloc() failure
12795** testing:
12796**
12797**     sqlite3OsOpen()
12798**     sqlite3OsRead()
12799**     sqlite3OsWrite()
12800**     sqlite3OsSync()
12801**     sqlite3OsLock()
12802**
12803*/
12804#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12805  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12806    void *pTstAlloc = sqlite3Malloc(10);                             \
12807    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12808    sqlite3_free(pTstAlloc);                                         \
12809  }
12810#else
12811  #define DO_OS_MALLOC_TEST(x)
12812#endif
12813
12814/*
12815** The following routines are convenience wrappers around methods
12816** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12817** of this would be completely automatic if SQLite were coded using
12818** C++ instead of plain old C.
12819*/
12820SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12821  int rc = SQLITE_OK;
12822  if( pId->pMethods ){
12823    rc = pId->pMethods->xClose(pId);
12824    pId->pMethods = 0;
12825  }
12826  return rc;
12827}
12828SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12829  DO_OS_MALLOC_TEST(id);
12830  return id->pMethods->xRead(id, pBuf, amt, offset);
12831}
12832SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12833  DO_OS_MALLOC_TEST(id);
12834  return id->pMethods->xWrite(id, pBuf, amt, offset);
12835}
12836SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12837  return id->pMethods->xTruncate(id, size);
12838}
12839SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12840  DO_OS_MALLOC_TEST(id);
12841  return id->pMethods->xSync(id, flags);
12842}
12843SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12844  DO_OS_MALLOC_TEST(id);
12845  return id->pMethods->xFileSize(id, pSize);
12846}
12847SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12848  DO_OS_MALLOC_TEST(id);
12849  return id->pMethods->xLock(id, lockType);
12850}
12851SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12852  return id->pMethods->xUnlock(id, lockType);
12853}
12854SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12855  DO_OS_MALLOC_TEST(id);
12856  return id->pMethods->xCheckReservedLock(id, pResOut);
12857}
12858SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12859  return id->pMethods->xFileControl(id, op, pArg);
12860}
12861SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12862  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12863  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12864}
12865SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12866  return id->pMethods->xDeviceCharacteristics(id);
12867}
12868SQLITE_PRIVATE int sqlite3OsShmOpen(sqlite3_file *id){
12869  return id->pMethods->xShmOpen(id);
12870}
12871SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
12872  return id->pMethods->xShmLock(id, offset, n, flags);
12873}
12874SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
12875  id->pMethods->xShmBarrier(id);
12876}
12877SQLITE_PRIVATE int sqlite3OsShmClose(sqlite3_file *id, int deleteFlag){
12878  return id->pMethods->xShmClose(id, deleteFlag);
12879}
12880SQLITE_PRIVATE int sqlite3OsShmMap(
12881  sqlite3_file *id,
12882  int iPage,
12883  int pgsz,
12884  int isWrite,
12885  void volatile **pp
12886){
12887  return id->pMethods->xShmMap(id, iPage, pgsz, isWrite, pp);
12888}
12889
12890/*
12891** The next group of routines are convenience wrappers around the
12892** VFS methods.
12893*/
12894SQLITE_PRIVATE int sqlite3OsOpen(
12895  sqlite3_vfs *pVfs,
12896  const char *zPath,
12897  sqlite3_file *pFile,
12898  int flags,
12899  int *pFlagsOut
12900){
12901  int rc;
12902  DO_OS_MALLOC_TEST(0);
12903  /* 0x7f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12904  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12905  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12906  ** reaching the VFS. */
12907  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f3f, pFlagsOut);
12908  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12909  return rc;
12910}
12911SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12912  return pVfs->xDelete(pVfs, zPath, dirSync);
12913}
12914SQLITE_PRIVATE int sqlite3OsAccess(
12915  sqlite3_vfs *pVfs,
12916  const char *zPath,
12917  int flags,
12918  int *pResOut
12919){
12920  DO_OS_MALLOC_TEST(0);
12921  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12922}
12923SQLITE_PRIVATE int sqlite3OsFullPathname(
12924  sqlite3_vfs *pVfs,
12925  const char *zPath,
12926  int nPathOut,
12927  char *zPathOut
12928){
12929  zPathOut[0] = 0;
12930  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12931}
12932#ifndef SQLITE_OMIT_LOAD_EXTENSION
12933SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12934  return pVfs->xDlOpen(pVfs, zPath);
12935}
12936SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12937  pVfs->xDlError(pVfs, nByte, zBufOut);
12938}
12939SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12940  return pVfs->xDlSym(pVfs, pHdle, zSym);
12941}
12942SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12943  pVfs->xDlClose(pVfs, pHandle);
12944}
12945#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12946SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12947  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12948}
12949SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12950  return pVfs->xSleep(pVfs, nMicro);
12951}
12952SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
12953  int rc;
12954  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
12955    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
12956  }else{
12957    double r;
12958    rc = pVfs->xCurrentTime(pVfs, &r);
12959    *pTimeOut = (sqlite3_int64)(r*86400000.0);
12960  }
12961  return rc;
12962}
12963
12964SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12965  sqlite3_vfs *pVfs,
12966  const char *zFile,
12967  sqlite3_file **ppFile,
12968  int flags,
12969  int *pOutFlags
12970){
12971  int rc = SQLITE_NOMEM;
12972  sqlite3_file *pFile;
12973  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12974  if( pFile ){
12975    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12976    if( rc!=SQLITE_OK ){
12977      sqlite3_free(pFile);
12978    }else{
12979      *ppFile = pFile;
12980    }
12981  }
12982  return rc;
12983}
12984SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12985  int rc = SQLITE_OK;
12986  assert( pFile );
12987  rc = sqlite3OsClose(pFile);
12988  sqlite3_free(pFile);
12989  return rc;
12990}
12991
12992/*
12993** This function is a wrapper around the OS specific implementation of
12994** sqlite3_os_init(). The purpose of the wrapper is to provide the
12995** ability to simulate a malloc failure, so that the handling of an
12996** error in sqlite3_os_init() by the upper layers can be tested.
12997*/
12998SQLITE_PRIVATE int sqlite3OsInit(void){
12999  void *p = sqlite3_malloc(10);
13000  if( p==0 ) return SQLITE_NOMEM;
13001  sqlite3_free(p);
13002  return sqlite3_os_init();
13003}
13004
13005/*
13006** The list of all registered VFS implementations.
13007*/
13008static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13009#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13010
13011/*
13012** Locate a VFS by name.  If no name is given, simply return the
13013** first VFS on the list.
13014*/
13015SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13016  sqlite3_vfs *pVfs = 0;
13017#if SQLITE_THREADSAFE
13018  sqlite3_mutex *mutex;
13019#endif
13020#ifndef SQLITE_OMIT_AUTOINIT
13021  int rc = sqlite3_initialize();
13022  if( rc ) return 0;
13023#endif
13024#if SQLITE_THREADSAFE
13025  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13026#endif
13027  sqlite3_mutex_enter(mutex);
13028  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13029    if( zVfs==0 ) break;
13030    if( strcmp(zVfs, pVfs->zName)==0 ) break;
13031  }
13032  sqlite3_mutex_leave(mutex);
13033  return pVfs;
13034}
13035
13036/*
13037** Unlink a VFS from the linked list
13038*/
13039static void vfsUnlink(sqlite3_vfs *pVfs){
13040  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13041  if( pVfs==0 ){
13042    /* No-op */
13043  }else if( vfsList==pVfs ){
13044    vfsList = pVfs->pNext;
13045  }else if( vfsList ){
13046    sqlite3_vfs *p = vfsList;
13047    while( p->pNext && p->pNext!=pVfs ){
13048      p = p->pNext;
13049    }
13050    if( p->pNext==pVfs ){
13051      p->pNext = pVfs->pNext;
13052    }
13053  }
13054}
13055
13056/*
13057** Register a VFS with the system.  It is harmless to register the same
13058** VFS multiple times.  The new VFS becomes the default if makeDflt is
13059** true.
13060*/
13061SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13062  sqlite3_mutex *mutex = 0;
13063#ifndef SQLITE_OMIT_AUTOINIT
13064  int rc = sqlite3_initialize();
13065  if( rc ) return rc;
13066#endif
13067  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13068  sqlite3_mutex_enter(mutex);
13069  vfsUnlink(pVfs);
13070  if( makeDflt || vfsList==0 ){
13071    pVfs->pNext = vfsList;
13072    vfsList = pVfs;
13073  }else{
13074    pVfs->pNext = vfsList->pNext;
13075    vfsList->pNext = pVfs;
13076  }
13077  assert(vfsList);
13078  sqlite3_mutex_leave(mutex);
13079  return SQLITE_OK;
13080}
13081
13082/*
13083** Unregister a VFS so that it is no longer accessible.
13084*/
13085SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13086#if SQLITE_THREADSAFE
13087  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13088#endif
13089  sqlite3_mutex_enter(mutex);
13090  vfsUnlink(pVfs);
13091  sqlite3_mutex_leave(mutex);
13092  return SQLITE_OK;
13093}
13094
13095/************** End of os.c **************************************************/
13096/************** Begin file fault.c *******************************************/
13097/*
13098** 2008 Jan 22
13099**
13100** The author disclaims copyright to this source code.  In place of
13101** a legal notice, here is a blessing:
13102**
13103**    May you do good and not evil.
13104**    May you find forgiveness for yourself and forgive others.
13105**    May you share freely, never taking more than you give.
13106**
13107*************************************************************************
13108**
13109** This file contains code to support the concept of "benign"
13110** malloc failures (when the xMalloc() or xRealloc() method of the
13111** sqlite3_mem_methods structure fails to allocate a block of memory
13112** and returns 0).
13113**
13114** Most malloc failures are non-benign. After they occur, SQLite
13115** abandons the current operation and returns an error code (usually
13116** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13117** fatal. For example, if a malloc fails while resizing a hash table, this
13118** is completely recoverable simply by not carrying out the resize. The
13119** hash table will continue to function normally.  So a malloc failure
13120** during a hash table resize is a benign fault.
13121*/
13122
13123
13124#ifndef SQLITE_OMIT_BUILTIN_TEST
13125
13126/*
13127** Global variables.
13128*/
13129typedef struct BenignMallocHooks BenignMallocHooks;
13130static SQLITE_WSD struct BenignMallocHooks {
13131  void (*xBenignBegin)(void);
13132  void (*xBenignEnd)(void);
13133} sqlite3Hooks = { 0, 0 };
13134
13135/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13136** structure.  If writable static data is unsupported on the target,
13137** we have to locate the state vector at run-time.  In the more common
13138** case where writable static data is supported, wsdHooks can refer directly
13139** to the "sqlite3Hooks" state vector declared above.
13140*/
13141#ifdef SQLITE_OMIT_WSD
13142# define wsdHooksInit \
13143  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13144# define wsdHooks x[0]
13145#else
13146# define wsdHooksInit
13147# define wsdHooks sqlite3Hooks
13148#endif
13149
13150
13151/*
13152** Register hooks to call when sqlite3BeginBenignMalloc() and
13153** sqlite3EndBenignMalloc() are called, respectively.
13154*/
13155SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13156  void (*xBenignBegin)(void),
13157  void (*xBenignEnd)(void)
13158){
13159  wsdHooksInit;
13160  wsdHooks.xBenignBegin = xBenignBegin;
13161  wsdHooks.xBenignEnd = xBenignEnd;
13162}
13163
13164/*
13165** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13166** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13167** indicates that subsequent malloc failures are non-benign.
13168*/
13169SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13170  wsdHooksInit;
13171  if( wsdHooks.xBenignBegin ){
13172    wsdHooks.xBenignBegin();
13173  }
13174}
13175SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13176  wsdHooksInit;
13177  if( wsdHooks.xBenignEnd ){
13178    wsdHooks.xBenignEnd();
13179  }
13180}
13181
13182#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13183
13184/************** End of fault.c ***********************************************/
13185/************** Begin file mem0.c ********************************************/
13186/*
13187** 2008 October 28
13188**
13189** The author disclaims copyright to this source code.  In place of
13190** a legal notice, here is a blessing:
13191**
13192**    May you do good and not evil.
13193**    May you find forgiveness for yourself and forgive others.
13194**    May you share freely, never taking more than you give.
13195**
13196*************************************************************************
13197**
13198** This file contains a no-op memory allocation drivers for use when
13199** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13200** here always fail.  SQLite will not operate with these drivers.  These
13201** are merely placeholders.  Real drivers must be substituted using
13202** sqlite3_config() before SQLite will operate.
13203*/
13204
13205/*
13206** This version of the memory allocator is the default.  It is
13207** used when no other memory allocator is specified using compile-time
13208** macros.
13209*/
13210#ifdef SQLITE_ZERO_MALLOC
13211
13212/*
13213** No-op versions of all memory allocation routines
13214*/
13215static void *sqlite3MemMalloc(int nByte){ return 0; }
13216static void sqlite3MemFree(void *pPrior){ return; }
13217static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13218static int sqlite3MemSize(void *pPrior){ return 0; }
13219static int sqlite3MemRoundup(int n){ return n; }
13220static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13221static void sqlite3MemShutdown(void *NotUsed){ return; }
13222
13223/*
13224** This routine is the only routine in this file with external linkage.
13225**
13226** Populate the low-level memory allocation function pointers in
13227** sqlite3GlobalConfig.m with pointers to the routines in this file.
13228*/
13229SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13230  static const sqlite3_mem_methods defaultMethods = {
13231     sqlite3MemMalloc,
13232     sqlite3MemFree,
13233     sqlite3MemRealloc,
13234     sqlite3MemSize,
13235     sqlite3MemRoundup,
13236     sqlite3MemInit,
13237     sqlite3MemShutdown,
13238     0
13239  };
13240  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13241}
13242
13243#endif /* SQLITE_ZERO_MALLOC */
13244
13245/************** End of mem0.c ************************************************/
13246/************** Begin file mem1.c ********************************************/
13247/*
13248** 2007 August 14
13249**
13250** The author disclaims copyright to this source code.  In place of
13251** a legal notice, here is a blessing:
13252**
13253**    May you do good and not evil.
13254**    May you find forgiveness for yourself and forgive others.
13255**    May you share freely, never taking more than you give.
13256**
13257*************************************************************************
13258**
13259** This file contains low-level memory allocation drivers for when
13260** SQLite will use the standard C-library malloc/realloc/free interface
13261** to obtain the memory it needs.
13262**
13263** This file contains implementations of the low-level memory allocation
13264** routines specified in the sqlite3_mem_methods object.
13265*/
13266
13267/*
13268** This version of the memory allocator is the default.  It is
13269** used when no other memory allocator is specified using compile-time
13270** macros.
13271*/
13272#ifdef SQLITE_SYSTEM_MALLOC
13273
13274/*
13275** Like malloc(), but remember the size of the allocation
13276** so that we can find it later using sqlite3MemSize().
13277**
13278** For this low-level routine, we are guaranteed that nByte>0 because
13279** cases of nByte<=0 will be intercepted and dealt with by higher level
13280** routines.
13281*/
13282static void *sqlite3MemMalloc(int nByte){
13283  sqlite3_int64 *p;
13284  assert( nByte>0 );
13285  nByte = ROUND8(nByte);
13286  p = malloc( nByte+8 );
13287  if( p ){
13288    p[0] = nByte;
13289    p++;
13290  }else{
13291    testcase( sqlite3GlobalConfig.xLog!=0 );
13292    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
13293  }
13294  return (void *)p;
13295}
13296
13297/*
13298** Like free() but works for allocations obtained from sqlite3MemMalloc()
13299** or sqlite3MemRealloc().
13300**
13301** For this low-level routine, we already know that pPrior!=0 since
13302** cases where pPrior==0 will have been intecepted and dealt with
13303** by higher-level routines.
13304*/
13305static void sqlite3MemFree(void *pPrior){
13306  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13307  assert( pPrior!=0 );
13308  p--;
13309  free(p);
13310}
13311
13312/*
13313** Report the allocated size of a prior return from xMalloc()
13314** or xRealloc().
13315*/
13316static int sqlite3MemSize(void *pPrior){
13317  sqlite3_int64 *p;
13318  if( pPrior==0 ) return 0;
13319  p = (sqlite3_int64*)pPrior;
13320  p--;
13321  return (int)p[0];
13322}
13323
13324/*
13325** Like realloc().  Resize an allocation previously obtained from
13326** sqlite3MemMalloc().
13327**
13328** For this low-level interface, we know that pPrior!=0.  Cases where
13329** pPrior==0 while have been intercepted by higher-level routine and
13330** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13331** cases where nByte<=0 will have been intercepted by higher-level
13332** routines and redirected to xFree.
13333*/
13334static void *sqlite3MemRealloc(void *pPrior, int nByte){
13335  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13336  assert( pPrior!=0 && nByte>0 );
13337  nByte = ROUND8(nByte);
13338  p--;
13339  p = realloc(p, nByte+8 );
13340  if( p ){
13341    p[0] = nByte;
13342    p++;
13343  }else{
13344    testcase( sqlite3GlobalConfig.xLog!=0 );
13345    sqlite3_log(SQLITE_NOMEM,
13346      "failed memory resize %u to %u bytes",
13347      sqlite3MemSize(pPrior), nByte);
13348  }
13349  return (void*)p;
13350}
13351
13352/*
13353** Round up a request size to the next valid allocation size.
13354*/
13355static int sqlite3MemRoundup(int n){
13356  return ROUND8(n);
13357}
13358
13359/*
13360** Initialize this module.
13361*/
13362static int sqlite3MemInit(void *NotUsed){
13363  UNUSED_PARAMETER(NotUsed);
13364  return SQLITE_OK;
13365}
13366
13367/*
13368** Deinitialize this module.
13369*/
13370static void sqlite3MemShutdown(void *NotUsed){
13371  UNUSED_PARAMETER(NotUsed);
13372  return;
13373}
13374
13375/*
13376** This routine is the only routine in this file with external linkage.
13377**
13378** Populate the low-level memory allocation function pointers in
13379** sqlite3GlobalConfig.m with pointers to the routines in this file.
13380*/
13381SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13382  static const sqlite3_mem_methods defaultMethods = {
13383     sqlite3MemMalloc,
13384     sqlite3MemFree,
13385     sqlite3MemRealloc,
13386     sqlite3MemSize,
13387     sqlite3MemRoundup,
13388     sqlite3MemInit,
13389     sqlite3MemShutdown,
13390     0
13391  };
13392  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13393}
13394
13395#endif /* SQLITE_SYSTEM_MALLOC */
13396
13397/************** End of mem1.c ************************************************/
13398/************** Begin file mem2.c ********************************************/
13399/*
13400** 2007 August 15
13401**
13402** The author disclaims copyright to this source code.  In place of
13403** a legal notice, here is a blessing:
13404**
13405**    May you do good and not evil.
13406**    May you find forgiveness for yourself and forgive others.
13407**    May you share freely, never taking more than you give.
13408**
13409*************************************************************************
13410**
13411** This file contains low-level memory allocation drivers for when
13412** SQLite will use the standard C-library malloc/realloc/free interface
13413** to obtain the memory it needs while adding lots of additional debugging
13414** information to each allocation in order to help detect and fix memory
13415** leaks and memory usage errors.
13416**
13417** This file contains implementations of the low-level memory allocation
13418** routines specified in the sqlite3_mem_methods object.
13419*/
13420
13421/*
13422** This version of the memory allocator is used only if the
13423** SQLITE_MEMDEBUG macro is defined
13424*/
13425#ifdef SQLITE_MEMDEBUG
13426
13427/*
13428** The backtrace functionality is only available with GLIBC
13429*/
13430#ifdef __GLIBC__
13431  extern int backtrace(void**,int);
13432  extern void backtrace_symbols_fd(void*const*,int,int);
13433#else
13434# define backtrace(A,B) 1
13435# define backtrace_symbols_fd(A,B,C)
13436#endif
13437
13438/*
13439** Each memory allocation looks like this:
13440**
13441**  ------------------------------------------------------------------------
13442**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13443**  ------------------------------------------------------------------------
13444**
13445** The application code sees only a pointer to the allocation.  We have
13446** to back up from the allocation pointer to find the MemBlockHdr.  The
13447** MemBlockHdr tells us the size of the allocation and the number of
13448** backtrace pointers.  There is also a guard word at the end of the
13449** MemBlockHdr.
13450*/
13451struct MemBlockHdr {
13452  i64 iSize;                          /* Size of this allocation */
13453  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13454  char nBacktrace;                    /* Number of backtraces on this alloc */
13455  char nBacktraceSlots;               /* Available backtrace slots */
13456  u8 nTitle;                          /* Bytes of title; includes '\0' */
13457  u8 eType;                           /* Allocation type code */
13458  int iForeGuard;                     /* Guard word for sanity */
13459};
13460
13461/*
13462** Guard words
13463*/
13464#define FOREGUARD 0x80F5E153
13465#define REARGUARD 0xE4676B53
13466
13467/*
13468** Number of malloc size increments to track.
13469*/
13470#define NCSIZE  1000
13471
13472/*
13473** All of the static variables used by this module are collected
13474** into a single structure named "mem".  This is to keep the
13475** static variables organized and to reduce namespace pollution
13476** when this module is combined with other in the amalgamation.
13477*/
13478static struct {
13479
13480  /*
13481  ** Mutex to control access to the memory allocation subsystem.
13482  */
13483  sqlite3_mutex *mutex;
13484
13485  /*
13486  ** Head and tail of a linked list of all outstanding allocations
13487  */
13488  struct MemBlockHdr *pFirst;
13489  struct MemBlockHdr *pLast;
13490
13491  /*
13492  ** The number of levels of backtrace to save in new allocations.
13493  */
13494  int nBacktrace;
13495  void (*xBacktrace)(int, int, void **);
13496
13497  /*
13498  ** Title text to insert in front of each block
13499  */
13500  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13501  char zTitle[100];  /* The title text */
13502
13503  /*
13504  ** sqlite3MallocDisallow() increments the following counter.
13505  ** sqlite3MallocAllow() decrements it.
13506  */
13507  int disallow; /* Do not allow memory allocation */
13508
13509  /*
13510  ** Gather statistics on the sizes of memory allocations.
13511  ** nAlloc[i] is the number of allocation attempts of i*8
13512  ** bytes.  i==NCSIZE is the number of allocation attempts for
13513  ** sizes more than NCSIZE*8 bytes.
13514  */
13515  int nAlloc[NCSIZE];      /* Total number of allocations */
13516  int nCurrent[NCSIZE];    /* Current number of allocations */
13517  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13518
13519} mem;
13520
13521
13522/*
13523** Adjust memory usage statistics
13524*/
13525static void adjustStats(int iSize, int increment){
13526  int i = ROUND8(iSize)/8;
13527  if( i>NCSIZE-1 ){
13528    i = NCSIZE - 1;
13529  }
13530  if( increment>0 ){
13531    mem.nAlloc[i]++;
13532    mem.nCurrent[i]++;
13533    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13534      mem.mxCurrent[i] = mem.nCurrent[i];
13535    }
13536  }else{
13537    mem.nCurrent[i]--;
13538    assert( mem.nCurrent[i]>=0 );
13539  }
13540}
13541
13542/*
13543** Given an allocation, find the MemBlockHdr for that allocation.
13544**
13545** This routine checks the guards at either end of the allocation and
13546** if they are incorrect it asserts.
13547*/
13548static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13549  struct MemBlockHdr *p;
13550  int *pInt;
13551  u8 *pU8;
13552  int nReserve;
13553
13554  p = (struct MemBlockHdr*)pAllocation;
13555  p--;
13556  assert( p->iForeGuard==(int)FOREGUARD );
13557  nReserve = ROUND8(p->iSize);
13558  pInt = (int*)pAllocation;
13559  pU8 = (u8*)pAllocation;
13560  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13561  /* This checks any of the "extra" bytes allocated due
13562  ** to rounding up to an 8 byte boundary to ensure
13563  ** they haven't been overwritten.
13564  */
13565  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13566  return p;
13567}
13568
13569/*
13570** Return the number of bytes currently allocated at address p.
13571*/
13572static int sqlite3MemSize(void *p){
13573  struct MemBlockHdr *pHdr;
13574  if( !p ){
13575    return 0;
13576  }
13577  pHdr = sqlite3MemsysGetHeader(p);
13578  return pHdr->iSize;
13579}
13580
13581/*
13582** Initialize the memory allocation subsystem.
13583*/
13584static int sqlite3MemInit(void *NotUsed){
13585  UNUSED_PARAMETER(NotUsed);
13586  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13587  if( !sqlite3GlobalConfig.bMemstat ){
13588    /* If memory status is enabled, then the malloc.c wrapper will already
13589    ** hold the STATIC_MEM mutex when the routines here are invoked. */
13590    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13591  }
13592  return SQLITE_OK;
13593}
13594
13595/*
13596** Deinitialize the memory allocation subsystem.
13597*/
13598static void sqlite3MemShutdown(void *NotUsed){
13599  UNUSED_PARAMETER(NotUsed);
13600  mem.mutex = 0;
13601}
13602
13603/*
13604** Round up a request size to the next valid allocation size.
13605*/
13606static int sqlite3MemRoundup(int n){
13607  return ROUND8(n);
13608}
13609
13610/*
13611** Fill a buffer with pseudo-random bytes.  This is used to preset
13612** the content of a new memory allocation to unpredictable values and
13613** to clear the content of a freed allocation to unpredictable values.
13614*/
13615static void randomFill(char *pBuf, int nByte){
13616  unsigned int x, y, r;
13617  x = SQLITE_PTR_TO_INT(pBuf);
13618  y = nByte | 1;
13619  while( nByte >= 4 ){
13620    x = (x>>1) ^ (-(x&1) & 0xd0000001);
13621    y = y*1103515245 + 12345;
13622    r = x ^ y;
13623    *(int*)pBuf = r;
13624    pBuf += 4;
13625    nByte -= 4;
13626  }
13627  while( nByte-- > 0 ){
13628    x = (x>>1) ^ (-(x&1) & 0xd0000001);
13629    y = y*1103515245 + 12345;
13630    r = x ^ y;
13631    *(pBuf++) = r & 0xff;
13632  }
13633}
13634
13635/*
13636** Allocate nByte bytes of memory.
13637*/
13638static void *sqlite3MemMalloc(int nByte){
13639  struct MemBlockHdr *pHdr;
13640  void **pBt;
13641  char *z;
13642  int *pInt;
13643  void *p = 0;
13644  int totalSize;
13645  int nReserve;
13646  sqlite3_mutex_enter(mem.mutex);
13647  assert( mem.disallow==0 );
13648  nReserve = ROUND8(nByte);
13649  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13650               mem.nBacktrace*sizeof(void*) + mem.nTitle;
13651  p = malloc(totalSize);
13652  if( p ){
13653    z = p;
13654    pBt = (void**)&z[mem.nTitle];
13655    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13656    pHdr->pNext = 0;
13657    pHdr->pPrev = mem.pLast;
13658    if( mem.pLast ){
13659      mem.pLast->pNext = pHdr;
13660    }else{
13661      mem.pFirst = pHdr;
13662    }
13663    mem.pLast = pHdr;
13664    pHdr->iForeGuard = FOREGUARD;
13665    pHdr->eType = MEMTYPE_HEAP;
13666    pHdr->nBacktraceSlots = mem.nBacktrace;
13667    pHdr->nTitle = mem.nTitle;
13668    if( mem.nBacktrace ){
13669      void *aAddr[40];
13670      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13671      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13672      assert(pBt[0]);
13673      if( mem.xBacktrace ){
13674        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13675      }
13676    }else{
13677      pHdr->nBacktrace = 0;
13678    }
13679    if( mem.nTitle ){
13680      memcpy(z, mem.zTitle, mem.nTitle);
13681    }
13682    pHdr->iSize = nByte;
13683    adjustStats(nByte, +1);
13684    pInt = (int*)&pHdr[1];
13685    pInt[nReserve/sizeof(int)] = REARGUARD;
13686    randomFill((char*)pInt, nByte);
13687    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
13688    p = (void*)pInt;
13689  }
13690  sqlite3_mutex_leave(mem.mutex);
13691  return p;
13692}
13693
13694/*
13695** Free memory.
13696*/
13697static void sqlite3MemFree(void *pPrior){
13698  struct MemBlockHdr *pHdr;
13699  void **pBt;
13700  char *z;
13701  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
13702       || mem.mutex!=0 );
13703  pHdr = sqlite3MemsysGetHeader(pPrior);
13704  pBt = (void**)pHdr;
13705  pBt -= pHdr->nBacktraceSlots;
13706  sqlite3_mutex_enter(mem.mutex);
13707  if( pHdr->pPrev ){
13708    assert( pHdr->pPrev->pNext==pHdr );
13709    pHdr->pPrev->pNext = pHdr->pNext;
13710  }else{
13711    assert( mem.pFirst==pHdr );
13712    mem.pFirst = pHdr->pNext;
13713  }
13714  if( pHdr->pNext ){
13715    assert( pHdr->pNext->pPrev==pHdr );
13716    pHdr->pNext->pPrev = pHdr->pPrev;
13717  }else{
13718    assert( mem.pLast==pHdr );
13719    mem.pLast = pHdr->pPrev;
13720  }
13721  z = (char*)pBt;
13722  z -= pHdr->nTitle;
13723  adjustStats(pHdr->iSize, -1);
13724  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13725                pHdr->iSize + sizeof(int) + pHdr->nTitle);
13726  free(z);
13727  sqlite3_mutex_leave(mem.mutex);
13728}
13729
13730/*
13731** Change the size of an existing memory allocation.
13732**
13733** For this debugging implementation, we *always* make a copy of the
13734** allocation into a new place in memory.  In this way, if the
13735** higher level code is using pointer to the old allocation, it is
13736** much more likely to break and we are much more liking to find
13737** the error.
13738*/
13739static void *sqlite3MemRealloc(void *pPrior, int nByte){
13740  struct MemBlockHdr *pOldHdr;
13741  void *pNew;
13742  assert( mem.disallow==0 );
13743  pOldHdr = sqlite3MemsysGetHeader(pPrior);
13744  pNew = sqlite3MemMalloc(nByte);
13745  if( pNew ){
13746    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13747    if( nByte>pOldHdr->iSize ){
13748      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13749    }
13750    sqlite3MemFree(pPrior);
13751  }
13752  return pNew;
13753}
13754
13755/*
13756** Populate the low-level memory allocation function pointers in
13757** sqlite3GlobalConfig.m with pointers to the routines in this file.
13758*/
13759SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13760  static const sqlite3_mem_methods defaultMethods = {
13761     sqlite3MemMalloc,
13762     sqlite3MemFree,
13763     sqlite3MemRealloc,
13764     sqlite3MemSize,
13765     sqlite3MemRoundup,
13766     sqlite3MemInit,
13767     sqlite3MemShutdown,
13768     0
13769  };
13770  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13771}
13772
13773/*
13774** Set the "type" of an allocation.
13775*/
13776SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
13777  if( p ){
13778    struct MemBlockHdr *pHdr;
13779    pHdr = sqlite3MemsysGetHeader(p);
13780    assert( pHdr->iForeGuard==FOREGUARD );
13781    pHdr->eType = eType;
13782  }
13783}
13784
13785/*
13786** Return TRUE if the mask of type in eType matches the type of the
13787** allocation p.  Also return true if p==NULL.
13788**
13789** This routine is designed for use within an assert() statement, to
13790** verify the type of an allocation.  For example:
13791**
13792**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
13793*/
13794SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
13795  int rc = 1;
13796  if( p ){
13797    struct MemBlockHdr *pHdr;
13798    pHdr = sqlite3MemsysGetHeader(p);
13799    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
13800    assert( (pHdr->eType & (pHdr->eType-1))==0 );  /* Only one type bit set */
13801    if( (pHdr->eType&eType)==0 ){
13802      void **pBt;
13803      pBt = (void**)pHdr;
13804      pBt -= pHdr->nBacktraceSlots;
13805      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(stderr));
13806      fprintf(stderr, "\n");
13807      rc = 0;
13808    }
13809  }
13810  return rc;
13811}
13812
13813
13814/*
13815** Set the number of backtrace levels kept for each allocation.
13816** A value of zero turns off backtracing.  The number is always rounded
13817** up to a multiple of 2.
13818*/
13819SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13820  if( depth<0 ){ depth = 0; }
13821  if( depth>20 ){ depth = 20; }
13822  depth = (depth+1)&0xfe;
13823  mem.nBacktrace = depth;
13824}
13825
13826SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13827  mem.xBacktrace = xBacktrace;
13828}
13829
13830/*
13831** Set the title string for subsequent allocations.
13832*/
13833SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13834  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13835  sqlite3_mutex_enter(mem.mutex);
13836  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13837  memcpy(mem.zTitle, zTitle, n);
13838  mem.zTitle[n] = 0;
13839  mem.nTitle = ROUND8(n);
13840  sqlite3_mutex_leave(mem.mutex);
13841}
13842
13843SQLITE_PRIVATE void sqlite3MemdebugSync(){
13844  struct MemBlockHdr *pHdr;
13845  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13846    void **pBt = (void**)pHdr;
13847    pBt -= pHdr->nBacktraceSlots;
13848    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13849  }
13850}
13851
13852/*
13853** Open the file indicated and write a log of all unfreed memory
13854** allocations into that log.
13855*/
13856SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13857  FILE *out;
13858  struct MemBlockHdr *pHdr;
13859  void **pBt;
13860  int i;
13861  out = fopen(zFilename, "w");
13862  if( out==0 ){
13863    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13864                    zFilename);
13865    return;
13866  }
13867  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13868    char *z = (char*)pHdr;
13869    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13870    fprintf(out, "**** %lld bytes at %p from %s ****\n",
13871            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13872    if( pHdr->nBacktrace ){
13873      fflush(out);
13874      pBt = (void**)pHdr;
13875      pBt -= pHdr->nBacktraceSlots;
13876      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13877      fprintf(out, "\n");
13878    }
13879  }
13880  fprintf(out, "COUNTS:\n");
13881  for(i=0; i<NCSIZE-1; i++){
13882    if( mem.nAlloc[i] ){
13883      fprintf(out, "   %5d: %10d %10d %10d\n",
13884            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13885    }
13886  }
13887  if( mem.nAlloc[NCSIZE-1] ){
13888    fprintf(out, "   %5d: %10d %10d %10d\n",
13889             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13890             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13891  }
13892  fclose(out);
13893}
13894
13895/*
13896** Return the number of times sqlite3MemMalloc() has been called.
13897*/
13898SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13899  int i;
13900  int nTotal = 0;
13901  for(i=0; i<NCSIZE; i++){
13902    nTotal += mem.nAlloc[i];
13903  }
13904  return nTotal;
13905}
13906
13907
13908#endif /* SQLITE_MEMDEBUG */
13909
13910/************** End of mem2.c ************************************************/
13911/************** Begin file mem3.c ********************************************/
13912/*
13913** 2007 October 14
13914**
13915** The author disclaims copyright to this source code.  In place of
13916** a legal notice, here is a blessing:
13917**
13918**    May you do good and not evil.
13919**    May you find forgiveness for yourself and forgive others.
13920**    May you share freely, never taking more than you give.
13921**
13922*************************************************************************
13923** This file contains the C functions that implement a memory
13924** allocation subsystem for use by SQLite.
13925**
13926** This version of the memory allocation subsystem omits all
13927** use of malloc(). The SQLite user supplies a block of memory
13928** before calling sqlite3_initialize() from which allocations
13929** are made and returned by the xMalloc() and xRealloc()
13930** implementations. Once sqlite3_initialize() has been called,
13931** the amount of memory available to SQLite is fixed and cannot
13932** be changed.
13933**
13934** This version of the memory allocation subsystem is included
13935** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13936*/
13937
13938/*
13939** This version of the memory allocator is only built into the library
13940** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13941** mean that the library will use a memory-pool by default, just that
13942** it is available. The mempool allocator is activated by calling
13943** sqlite3_config().
13944*/
13945#ifdef SQLITE_ENABLE_MEMSYS3
13946
13947/*
13948** Maximum size (in Mem3Blocks) of a "small" chunk.
13949*/
13950#define MX_SMALL 10
13951
13952
13953/*
13954** Number of freelist hash slots
13955*/
13956#define N_HASH  61
13957
13958/*
13959** A memory allocation (also called a "chunk") consists of two or
13960** more blocks where each block is 8 bytes.  The first 8 bytes are
13961** a header that is not returned to the user.
13962**
13963** A chunk is two or more blocks that is either checked out or
13964** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13965** size of the allocation in blocks if the allocation is free.
13966** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13967** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13968** is true if the previous chunk is checked out and false if the
13969** previous chunk is free.  The u.hdr.prevSize field is the size of
13970** the previous chunk in blocks if the previous chunk is on the
13971** freelist. If the previous chunk is checked out, then
13972** u.hdr.prevSize can be part of the data for that chunk and should
13973** not be read or written.
13974**
13975** We often identify a chunk by its index in mem3.aPool[].  When
13976** this is done, the chunk index refers to the second block of
13977** the chunk.  In this way, the first chunk has an index of 1.
13978** A chunk index of 0 means "no such chunk" and is the equivalent
13979** of a NULL pointer.
13980**
13981** The second block of free chunks is of the form u.list.  The
13982** two fields form a double-linked list of chunks of related sizes.
13983** Pointers to the head of the list are stored in mem3.aiSmall[]
13984** for smaller chunks and mem3.aiHash[] for larger chunks.
13985**
13986** The second block of a chunk is user data if the chunk is checked
13987** out.  If a chunk is checked out, the user data may extend into
13988** the u.hdr.prevSize value of the following chunk.
13989*/
13990typedef struct Mem3Block Mem3Block;
13991struct Mem3Block {
13992  union {
13993    struct {
13994      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13995      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13996    } hdr;
13997    struct {
13998      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13999      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14000    } list;
14001  } u;
14002};
14003
14004/*
14005** All of the static variables used by this module are collected
14006** into a single structure named "mem3".  This is to keep the
14007** static variables organized and to reduce namespace pollution
14008** when this module is combined with other in the amalgamation.
14009*/
14010static SQLITE_WSD struct Mem3Global {
14011  /*
14012  ** Memory available for allocation. nPool is the size of the array
14013  ** (in Mem3Blocks) pointed to by aPool less 2.
14014  */
14015  u32 nPool;
14016  Mem3Block *aPool;
14017
14018  /*
14019  ** True if we are evaluating an out-of-memory callback.
14020  */
14021  int alarmBusy;
14022
14023  /*
14024  ** Mutex to control access to the memory allocation subsystem.
14025  */
14026  sqlite3_mutex *mutex;
14027
14028  /*
14029  ** The minimum amount of free space that we have seen.
14030  */
14031  u32 mnMaster;
14032
14033  /*
14034  ** iMaster is the index of the master chunk.  Most new allocations
14035  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14036  ** of the current master.  iMaster is 0 if there is not master chunk.
14037  ** The master chunk is not in either the aiHash[] or aiSmall[].
14038  */
14039  u32 iMaster;
14040  u32 szMaster;
14041
14042  /*
14043  ** Array of lists of free blocks according to the block size
14044  ** for smaller chunks, or a hash on the block size for larger
14045  ** chunks.
14046  */
14047  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14048  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14049} mem3 = { 97535575 };
14050
14051#define mem3 GLOBAL(struct Mem3Global, mem3)
14052
14053/*
14054** Unlink the chunk at mem3.aPool[i] from list it is currently
14055** on.  *pRoot is the list that i is a member of.
14056*/
14057static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14058  u32 next = mem3.aPool[i].u.list.next;
14059  u32 prev = mem3.aPool[i].u.list.prev;
14060  assert( sqlite3_mutex_held(mem3.mutex) );
14061  if( prev==0 ){
14062    *pRoot = next;
14063  }else{
14064    mem3.aPool[prev].u.list.next = next;
14065  }
14066  if( next ){
14067    mem3.aPool[next].u.list.prev = prev;
14068  }
14069  mem3.aPool[i].u.list.next = 0;
14070  mem3.aPool[i].u.list.prev = 0;
14071}
14072
14073/*
14074** Unlink the chunk at index i from
14075** whatever list is currently a member of.
14076*/
14077static void memsys3Unlink(u32 i){
14078  u32 size, hash;
14079  assert( sqlite3_mutex_held(mem3.mutex) );
14080  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14081  assert( i>=1 );
14082  size = mem3.aPool[i-1].u.hdr.size4x/4;
14083  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14084  assert( size>=2 );
14085  if( size <= MX_SMALL ){
14086    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14087  }else{
14088    hash = size % N_HASH;
14089    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14090  }
14091}
14092
14093/*
14094** Link the chunk at mem3.aPool[i] so that is on the list rooted
14095** at *pRoot.
14096*/
14097static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14098  assert( sqlite3_mutex_held(mem3.mutex) );
14099  mem3.aPool[i].u.list.next = *pRoot;
14100  mem3.aPool[i].u.list.prev = 0;
14101  if( *pRoot ){
14102    mem3.aPool[*pRoot].u.list.prev = i;
14103  }
14104  *pRoot = i;
14105}
14106
14107/*
14108** Link the chunk at index i into either the appropriate
14109** small chunk list, or into the large chunk hash table.
14110*/
14111static void memsys3Link(u32 i){
14112  u32 size, hash;
14113  assert( sqlite3_mutex_held(mem3.mutex) );
14114  assert( i>=1 );
14115  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14116  size = mem3.aPool[i-1].u.hdr.size4x/4;
14117  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14118  assert( size>=2 );
14119  if( size <= MX_SMALL ){
14120    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14121  }else{
14122    hash = size % N_HASH;
14123    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14124  }
14125}
14126
14127/*
14128** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14129** will already be held (obtained by code in malloc.c) if
14130** sqlite3GlobalConfig.bMemStat is true.
14131*/
14132static void memsys3Enter(void){
14133  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14134    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14135  }
14136  sqlite3_mutex_enter(mem3.mutex);
14137}
14138static void memsys3Leave(void){
14139  sqlite3_mutex_leave(mem3.mutex);
14140}
14141
14142/*
14143** Called when we are unable to satisfy an allocation of nBytes.
14144*/
14145static void memsys3OutOfMemory(int nByte){
14146  if( !mem3.alarmBusy ){
14147    mem3.alarmBusy = 1;
14148    assert( sqlite3_mutex_held(mem3.mutex) );
14149    sqlite3_mutex_leave(mem3.mutex);
14150    sqlite3_release_memory(nByte);
14151    sqlite3_mutex_enter(mem3.mutex);
14152    mem3.alarmBusy = 0;
14153  }
14154}
14155
14156
14157/*
14158** Chunk i is a free chunk that has been unlinked.  Adjust its
14159** size parameters for check-out and return a pointer to the
14160** user portion of the chunk.
14161*/
14162static void *memsys3Checkout(u32 i, u32 nBlock){
14163  u32 x;
14164  assert( sqlite3_mutex_held(mem3.mutex) );
14165  assert( i>=1 );
14166  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14167  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14168  x = mem3.aPool[i-1].u.hdr.size4x;
14169  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14170  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14171  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14172  return &mem3.aPool[i];
14173}
14174
14175/*
14176** Carve a piece off of the end of the mem3.iMaster free chunk.
14177** Return a pointer to the new allocation.  Or, if the master chunk
14178** is not large enough, return 0.
14179*/
14180static void *memsys3FromMaster(u32 nBlock){
14181  assert( sqlite3_mutex_held(mem3.mutex) );
14182  assert( mem3.szMaster>=nBlock );
14183  if( nBlock>=mem3.szMaster-1 ){
14184    /* Use the entire master */
14185    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14186    mem3.iMaster = 0;
14187    mem3.szMaster = 0;
14188    mem3.mnMaster = 0;
14189    return p;
14190  }else{
14191    /* Split the master block.  Return the tail. */
14192    u32 newi, x;
14193    newi = mem3.iMaster + mem3.szMaster - nBlock;
14194    assert( newi > mem3.iMaster+1 );
14195    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14196    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14197    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14198    mem3.szMaster -= nBlock;
14199    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14200    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14201    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14202    if( mem3.szMaster < mem3.mnMaster ){
14203      mem3.mnMaster = mem3.szMaster;
14204    }
14205    return (void*)&mem3.aPool[newi];
14206  }
14207}
14208
14209/*
14210** *pRoot is the head of a list of free chunks of the same size
14211** or same size hash.  In other words, *pRoot is an entry in either
14212** mem3.aiSmall[] or mem3.aiHash[].
14213**
14214** This routine examines all entries on the given list and tries
14215** to coalesce each entries with adjacent free chunks.
14216**
14217** If it sees a chunk that is larger than mem3.iMaster, it replaces
14218** the current mem3.iMaster with the new larger chunk.  In order for
14219** this mem3.iMaster replacement to work, the master chunk must be
14220** linked into the hash tables.  That is not the normal state of
14221** affairs, of course.  The calling routine must link the master
14222** chunk before invoking this routine, then must unlink the (possibly
14223** changed) master chunk once this routine has finished.
14224*/
14225static void memsys3Merge(u32 *pRoot){
14226  u32 iNext, prev, size, i, x;
14227
14228  assert( sqlite3_mutex_held(mem3.mutex) );
14229  for(i=*pRoot; i>0; i=iNext){
14230    iNext = mem3.aPool[i].u.list.next;
14231    size = mem3.aPool[i-1].u.hdr.size4x;
14232    assert( (size&1)==0 );
14233    if( (size&2)==0 ){
14234      memsys3UnlinkFromList(i, pRoot);
14235      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14236      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14237      if( prev==iNext ){
14238        iNext = mem3.aPool[prev].u.list.next;
14239      }
14240      memsys3Unlink(prev);
14241      size = i + size/4 - prev;
14242      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14243      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14244      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14245      memsys3Link(prev);
14246      i = prev;
14247    }else{
14248      size /= 4;
14249    }
14250    if( size>mem3.szMaster ){
14251      mem3.iMaster = i;
14252      mem3.szMaster = size;
14253    }
14254  }
14255}
14256
14257/*
14258** Return a block of memory of at least nBytes in size.
14259** Return NULL if unable.
14260**
14261** This function assumes that the necessary mutexes, if any, are
14262** already held by the caller. Hence "Unsafe".
14263*/
14264static void *memsys3MallocUnsafe(int nByte){
14265  u32 i;
14266  u32 nBlock;
14267  u32 toFree;
14268
14269  assert( sqlite3_mutex_held(mem3.mutex) );
14270  assert( sizeof(Mem3Block)==8 );
14271  if( nByte<=12 ){
14272    nBlock = 2;
14273  }else{
14274    nBlock = (nByte + 11)/8;
14275  }
14276  assert( nBlock>=2 );
14277
14278  /* STEP 1:
14279  ** Look for an entry of the correct size in either the small
14280  ** chunk table or in the large chunk hash table.  This is
14281  ** successful most of the time (about 9 times out of 10).
14282  */
14283  if( nBlock <= MX_SMALL ){
14284    i = mem3.aiSmall[nBlock-2];
14285    if( i>0 ){
14286      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14287      return memsys3Checkout(i, nBlock);
14288    }
14289  }else{
14290    int hash = nBlock % N_HASH;
14291    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14292      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14293        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14294        return memsys3Checkout(i, nBlock);
14295      }
14296    }
14297  }
14298
14299  /* STEP 2:
14300  ** Try to satisfy the allocation by carving a piece off of the end
14301  ** of the master chunk.  This step usually works if step 1 fails.
14302  */
14303  if( mem3.szMaster>=nBlock ){
14304    return memsys3FromMaster(nBlock);
14305  }
14306
14307
14308  /* STEP 3:
14309  ** Loop through the entire memory pool.  Coalesce adjacent free
14310  ** chunks.  Recompute the master chunk as the largest free chunk.
14311  ** Then try again to satisfy the allocation by carving a piece off
14312  ** of the end of the master chunk.  This step happens very
14313  ** rarely (we hope!)
14314  */
14315  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14316    memsys3OutOfMemory(toFree);
14317    if( mem3.iMaster ){
14318      memsys3Link(mem3.iMaster);
14319      mem3.iMaster = 0;
14320      mem3.szMaster = 0;
14321    }
14322    for(i=0; i<N_HASH; i++){
14323      memsys3Merge(&mem3.aiHash[i]);
14324    }
14325    for(i=0; i<MX_SMALL-1; i++){
14326      memsys3Merge(&mem3.aiSmall[i]);
14327    }
14328    if( mem3.szMaster ){
14329      memsys3Unlink(mem3.iMaster);
14330      if( mem3.szMaster>=nBlock ){
14331        return memsys3FromMaster(nBlock);
14332      }
14333    }
14334  }
14335
14336  /* If none of the above worked, then we fail. */
14337  return 0;
14338}
14339
14340/*
14341** Free an outstanding memory allocation.
14342**
14343** This function assumes that the necessary mutexes, if any, are
14344** already held by the caller. Hence "Unsafe".
14345*/
14346void memsys3FreeUnsafe(void *pOld){
14347  Mem3Block *p = (Mem3Block*)pOld;
14348  int i;
14349  u32 size, x;
14350  assert( sqlite3_mutex_held(mem3.mutex) );
14351  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14352  i = p - mem3.aPool;
14353  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14354  size = mem3.aPool[i-1].u.hdr.size4x/4;
14355  assert( i+size<=mem3.nPool+1 );
14356  mem3.aPool[i-1].u.hdr.size4x &= ~1;
14357  mem3.aPool[i+size-1].u.hdr.prevSize = size;
14358  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14359  memsys3Link(i);
14360
14361  /* Try to expand the master using the newly freed chunk */
14362  if( mem3.iMaster ){
14363    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14364      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14365      mem3.iMaster -= size;
14366      mem3.szMaster += size;
14367      memsys3Unlink(mem3.iMaster);
14368      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14369      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14370      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14371    }
14372    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14373    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14374      memsys3Unlink(mem3.iMaster+mem3.szMaster);
14375      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14376      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14377      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14378    }
14379  }
14380}
14381
14382/*
14383** Return the size of an outstanding allocation, in bytes.  The
14384** size returned omits the 8-byte header overhead.  This only
14385** works for chunks that are currently checked out.
14386*/
14387static int memsys3Size(void *p){
14388  Mem3Block *pBlock;
14389  if( p==0 ) return 0;
14390  pBlock = (Mem3Block*)p;
14391  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14392  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14393}
14394
14395/*
14396** Round up a request size to the next valid allocation size.
14397*/
14398static int memsys3Roundup(int n){
14399  if( n<=12 ){
14400    return 12;
14401  }else{
14402    return ((n+11)&~7) - 4;
14403  }
14404}
14405
14406/*
14407** Allocate nBytes of memory.
14408*/
14409static void *memsys3Malloc(int nBytes){
14410  sqlite3_int64 *p;
14411  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14412  memsys3Enter();
14413  p = memsys3MallocUnsafe(nBytes);
14414  memsys3Leave();
14415  return (void*)p;
14416}
14417
14418/*
14419** Free memory.
14420*/
14421void memsys3Free(void *pPrior){
14422  assert( pPrior );
14423  memsys3Enter();
14424  memsys3FreeUnsafe(pPrior);
14425  memsys3Leave();
14426}
14427
14428/*
14429** Change the size of an existing memory allocation
14430*/
14431void *memsys3Realloc(void *pPrior, int nBytes){
14432  int nOld;
14433  void *p;
14434  if( pPrior==0 ){
14435    return sqlite3_malloc(nBytes);
14436  }
14437  if( nBytes<=0 ){
14438    sqlite3_free(pPrior);
14439    return 0;
14440  }
14441  nOld = memsys3Size(pPrior);
14442  if( nBytes<=nOld && nBytes>=nOld-128 ){
14443    return pPrior;
14444  }
14445  memsys3Enter();
14446  p = memsys3MallocUnsafe(nBytes);
14447  if( p ){
14448    if( nOld<nBytes ){
14449      memcpy(p, pPrior, nOld);
14450    }else{
14451      memcpy(p, pPrior, nBytes);
14452    }
14453    memsys3FreeUnsafe(pPrior);
14454  }
14455  memsys3Leave();
14456  return p;
14457}
14458
14459/*
14460** Initialize this module.
14461*/
14462static int memsys3Init(void *NotUsed){
14463  UNUSED_PARAMETER(NotUsed);
14464  if( !sqlite3GlobalConfig.pHeap ){
14465    return SQLITE_ERROR;
14466  }
14467
14468  /* Store a pointer to the memory block in global structure mem3. */
14469  assert( sizeof(Mem3Block)==8 );
14470  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14471  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14472
14473  /* Initialize the master block. */
14474  mem3.szMaster = mem3.nPool;
14475  mem3.mnMaster = mem3.szMaster;
14476  mem3.iMaster = 1;
14477  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14478  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14479  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14480
14481  return SQLITE_OK;
14482}
14483
14484/*
14485** Deinitialize this module.
14486*/
14487static void memsys3Shutdown(void *NotUsed){
14488  UNUSED_PARAMETER(NotUsed);
14489  mem3.mutex = 0;
14490  return;
14491}
14492
14493
14494
14495/*
14496** Open the file indicated and write a log of all unfreed memory
14497** allocations into that log.
14498*/
14499SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14500#ifdef SQLITE_DEBUG
14501  FILE *out;
14502  u32 i, j;
14503  u32 size;
14504  if( zFilename==0 || zFilename[0]==0 ){
14505    out = stdout;
14506  }else{
14507    out = fopen(zFilename, "w");
14508    if( out==0 ){
14509      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14510                      zFilename);
14511      return;
14512    }
14513  }
14514  memsys3Enter();
14515  fprintf(out, "CHUNKS:\n");
14516  for(i=1; i<=mem3.nPool; i+=size/4){
14517    size = mem3.aPool[i-1].u.hdr.size4x;
14518    if( size/4<=1 ){
14519      fprintf(out, "%p size error\n", &mem3.aPool[i]);
14520      assert( 0 );
14521      break;
14522    }
14523    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14524      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14525      assert( 0 );
14526      break;
14527    }
14528    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14529      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14530      assert( 0 );
14531      break;
14532    }
14533    if( size&1 ){
14534      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14535    }else{
14536      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14537                  i==mem3.iMaster ? " **master**" : "");
14538    }
14539  }
14540  for(i=0; i<MX_SMALL-1; i++){
14541    if( mem3.aiSmall[i]==0 ) continue;
14542    fprintf(out, "small(%2d):", i);
14543    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14544      fprintf(out, " %p(%d)", &mem3.aPool[j],
14545              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14546    }
14547    fprintf(out, "\n");
14548  }
14549  for(i=0; i<N_HASH; i++){
14550    if( mem3.aiHash[i]==0 ) continue;
14551    fprintf(out, "hash(%2d):", i);
14552    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14553      fprintf(out, " %p(%d)", &mem3.aPool[j],
14554              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14555    }
14556    fprintf(out, "\n");
14557  }
14558  fprintf(out, "master=%d\n", mem3.iMaster);
14559  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14560  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14561  sqlite3_mutex_leave(mem3.mutex);
14562  if( out==stdout ){
14563    fflush(stdout);
14564  }else{
14565    fclose(out);
14566  }
14567#else
14568  UNUSED_PARAMETER(zFilename);
14569#endif
14570}
14571
14572/*
14573** This routine is the only routine in this file with external
14574** linkage.
14575**
14576** Populate the low-level memory allocation function pointers in
14577** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14578** arguments specify the block of memory to manage.
14579**
14580** This routine is only called by sqlite3_config(), and therefore
14581** is not required to be threadsafe (it is not).
14582*/
14583SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14584  static const sqlite3_mem_methods mempoolMethods = {
14585     memsys3Malloc,
14586     memsys3Free,
14587     memsys3Realloc,
14588     memsys3Size,
14589     memsys3Roundup,
14590     memsys3Init,
14591     memsys3Shutdown,
14592     0
14593  };
14594  return &mempoolMethods;
14595}
14596
14597#endif /* SQLITE_ENABLE_MEMSYS3 */
14598
14599/************** End of mem3.c ************************************************/
14600/************** Begin file mem5.c ********************************************/
14601/*
14602** 2007 October 14
14603**
14604** The author disclaims copyright to this source code.  In place of
14605** a legal notice, here is a blessing:
14606**
14607**    May you do good and not evil.
14608**    May you find forgiveness for yourself and forgive others.
14609**    May you share freely, never taking more than you give.
14610**
14611*************************************************************************
14612** This file contains the C functions that implement a memory
14613** allocation subsystem for use by SQLite.
14614**
14615** This version of the memory allocation subsystem omits all
14616** use of malloc(). The application gives SQLite a block of memory
14617** before calling sqlite3_initialize() from which allocations
14618** are made and returned by the xMalloc() and xRealloc()
14619** implementations. Once sqlite3_initialize() has been called,
14620** the amount of memory available to SQLite is fixed and cannot
14621** be changed.
14622**
14623** This version of the memory allocation subsystem is included
14624** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14625**
14626** This memory allocator uses the following algorithm:
14627**
14628**   1.  All memory allocations sizes are rounded up to a power of 2.
14629**
14630**   2.  If two adjacent free blocks are the halves of a larger block,
14631**       then the two blocks are coalesed into the single larger block.
14632**
14633**   3.  New memory is allocated from the first available free block.
14634**
14635** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
14636** Concerning Dynamic Storage Allocation". Journal of the Association for
14637** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
14638**
14639** Let n be the size of the largest allocation divided by the minimum
14640** allocation size (after rounding all sizes up to a power of 2.)  Let M
14641** be the maximum amount of memory ever outstanding at one time.  Let
14642** N be the total amount of memory available for allocation.  Robson
14643** proved that this memory allocator will never breakdown due to
14644** fragmentation as long as the following constraint holds:
14645**
14646**      N >=  M*(1 + log2(n)/2) - n + 1
14647**
14648** The sqlite3_status() logic tracks the maximum values of n and M so
14649** that an application can, at any time, verify this constraint.
14650*/
14651
14652/*
14653** This version of the memory allocator is used only when
14654** SQLITE_ENABLE_MEMSYS5 is defined.
14655*/
14656#ifdef SQLITE_ENABLE_MEMSYS5
14657
14658/*
14659** A minimum allocation is an instance of the following structure.
14660** Larger allocations are an array of these structures where the
14661** size of the array is a power of 2.
14662**
14663** The size of this object must be a power of two.  That fact is
14664** verified in memsys5Init().
14665*/
14666typedef struct Mem5Link Mem5Link;
14667struct Mem5Link {
14668  int next;       /* Index of next free chunk */
14669  int prev;       /* Index of previous free chunk */
14670};
14671
14672/*
14673** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
14674** mem5.szAtom is always at least 8 and 32-bit integers are used,
14675** it is not actually possible to reach this limit.
14676*/
14677#define LOGMAX 30
14678
14679/*
14680** Masks used for mem5.aCtrl[] elements.
14681*/
14682#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
14683#define CTRL_FREE     0x20    /* True if not checked out */
14684
14685/*
14686** All of the static variables used by this module are collected
14687** into a single structure named "mem5".  This is to keep the
14688** static variables organized and to reduce namespace pollution
14689** when this module is combined with other in the amalgamation.
14690*/
14691static SQLITE_WSD struct Mem5Global {
14692  /*
14693  ** Memory available for allocation
14694  */
14695  int szAtom;      /* Smallest possible allocation in bytes */
14696  int nBlock;      /* Number of szAtom sized blocks in zPool */
14697  u8 *zPool;       /* Memory available to be allocated */
14698
14699  /*
14700  ** Mutex to control access to the memory allocation subsystem.
14701  */
14702  sqlite3_mutex *mutex;
14703
14704  /*
14705  ** Performance statistics
14706  */
14707  u64 nAlloc;         /* Total number of calls to malloc */
14708  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14709  u64 totalExcess;    /* Total internal fragmentation */
14710  u32 currentOut;     /* Current checkout, including internal fragmentation */
14711  u32 currentCount;   /* Current number of distinct checkouts */
14712  u32 maxOut;         /* Maximum instantaneous currentOut */
14713  u32 maxCount;       /* Maximum instantaneous currentCount */
14714  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14715
14716  /*
14717  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
14718  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
14719  ** and so forth.
14720  */
14721  int aiFreelist[LOGMAX+1];
14722
14723  /*
14724  ** Space for tracking which blocks are checked out and the size
14725  ** of each block.  One byte per block.
14726  */
14727  u8 *aCtrl;
14728
14729} mem5 = { 0 };
14730
14731/*
14732** Access the static variable through a macro for SQLITE_OMIT_WSD
14733*/
14734#define mem5 GLOBAL(struct Mem5Global, mem5)
14735
14736/*
14737** Assuming mem5.zPool is divided up into an array of Mem5Link
14738** structures, return a pointer to the idx-th such lik.
14739*/
14740#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
14741
14742/*
14743** Unlink the chunk at mem5.aPool[i] from list it is currently
14744** on.  It should be found on mem5.aiFreelist[iLogsize].
14745*/
14746static void memsys5Unlink(int i, int iLogsize){
14747  int next, prev;
14748  assert( i>=0 && i<mem5.nBlock );
14749  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14750  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14751
14752  next = MEM5LINK(i)->next;
14753  prev = MEM5LINK(i)->prev;
14754  if( prev<0 ){
14755    mem5.aiFreelist[iLogsize] = next;
14756  }else{
14757    MEM5LINK(prev)->next = next;
14758  }
14759  if( next>=0 ){
14760    MEM5LINK(next)->prev = prev;
14761  }
14762}
14763
14764/*
14765** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14766** free list.
14767*/
14768static void memsys5Link(int i, int iLogsize){
14769  int x;
14770  assert( sqlite3_mutex_held(mem5.mutex) );
14771  assert( i>=0 && i<mem5.nBlock );
14772  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14773  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14774
14775  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14776  MEM5LINK(i)->prev = -1;
14777  if( x>=0 ){
14778    assert( x<mem5.nBlock );
14779    MEM5LINK(x)->prev = i;
14780  }
14781  mem5.aiFreelist[iLogsize] = i;
14782}
14783
14784/*
14785** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14786** will already be held (obtained by code in malloc.c) if
14787** sqlite3GlobalConfig.bMemStat is true.
14788*/
14789static void memsys5Enter(void){
14790  sqlite3_mutex_enter(mem5.mutex);
14791}
14792static void memsys5Leave(void){
14793  sqlite3_mutex_leave(mem5.mutex);
14794}
14795
14796/*
14797** Return the size of an outstanding allocation, in bytes.  The
14798** size returned omits the 8-byte header overhead.  This only
14799** works for chunks that are currently checked out.
14800*/
14801static int memsys5Size(void *p){
14802  int iSize = 0;
14803  if( p ){
14804    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14805    assert( i>=0 && i<mem5.nBlock );
14806    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14807  }
14808  return iSize;
14809}
14810
14811/*
14812** Find the first entry on the freelist iLogsize.  Unlink that
14813** entry and return its index.
14814*/
14815static int memsys5UnlinkFirst(int iLogsize){
14816  int i;
14817  int iFirst;
14818
14819  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14820  i = iFirst = mem5.aiFreelist[iLogsize];
14821  assert( iFirst>=0 );
14822  while( i>0 ){
14823    if( i<iFirst ) iFirst = i;
14824    i = MEM5LINK(i)->next;
14825  }
14826  memsys5Unlink(iFirst, iLogsize);
14827  return iFirst;
14828}
14829
14830/*
14831** Return a block of memory of at least nBytes in size.
14832** Return NULL if unable.  Return NULL if nBytes==0.
14833**
14834** The caller guarantees that nByte positive.
14835**
14836** The caller has obtained a mutex prior to invoking this
14837** routine so there is never any chance that two or more
14838** threads can be in this routine at the same time.
14839*/
14840static void *memsys5MallocUnsafe(int nByte){
14841  int i;           /* Index of a mem5.aPool[] slot */
14842  int iBin;        /* Index into mem5.aiFreelist[] */
14843  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14844  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14845
14846  /* nByte must be a positive */
14847  assert( nByte>0 );
14848
14849  /* Keep track of the maximum allocation request.  Even unfulfilled
14850  ** requests are counted */
14851  if( (u32)nByte>mem5.maxRequest ){
14852    mem5.maxRequest = nByte;
14853  }
14854
14855  /* Abort if the requested allocation size is larger than the largest
14856  ** power of two that we can represent using 32-bit signed integers.
14857  */
14858  if( nByte > 0x40000000 ){
14859    return 0;
14860  }
14861
14862  /* Round nByte up to the next valid power of two */
14863  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14864
14865  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14866  ** block.  If not, then split a block of the next larger power of
14867  ** two in order to create a new free block of size iLogsize.
14868  */
14869  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14870  if( iBin>LOGMAX ){
14871    testcase( sqlite3GlobalConfig.xLog!=0 );
14872    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14873    return 0;
14874  }
14875  i = memsys5UnlinkFirst(iBin);
14876  while( iBin>iLogsize ){
14877    int newSize;
14878
14879    iBin--;
14880    newSize = 1 << iBin;
14881    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14882    memsys5Link(i+newSize, iBin);
14883  }
14884  mem5.aCtrl[i] = iLogsize;
14885
14886  /* Update allocator performance statistics. */
14887  mem5.nAlloc++;
14888  mem5.totalAlloc += iFullSz;
14889  mem5.totalExcess += iFullSz - nByte;
14890  mem5.currentCount++;
14891  mem5.currentOut += iFullSz;
14892  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14893  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14894
14895  /* Return a pointer to the allocated memory. */
14896  return (void*)&mem5.zPool[i*mem5.szAtom];
14897}
14898
14899/*
14900** Free an outstanding memory allocation.
14901*/
14902static void memsys5FreeUnsafe(void *pOld){
14903  u32 size, iLogsize;
14904  int iBlock;
14905
14906  /* Set iBlock to the index of the block pointed to by pOld in
14907  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14908  */
14909  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14910
14911  /* Check that the pointer pOld points to a valid, non-free block. */
14912  assert( iBlock>=0 && iBlock<mem5.nBlock );
14913  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14914  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14915
14916  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14917  size = 1<<iLogsize;
14918  assert( iBlock+size-1<(u32)mem5.nBlock );
14919
14920  mem5.aCtrl[iBlock] |= CTRL_FREE;
14921  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14922  assert( mem5.currentCount>0 );
14923  assert( mem5.currentOut>=(size*mem5.szAtom) );
14924  mem5.currentCount--;
14925  mem5.currentOut -= size*mem5.szAtom;
14926  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14927  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14928
14929  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14930  while( ALWAYS(iLogsize<LOGMAX) ){
14931    int iBuddy;
14932    if( (iBlock>>iLogsize) & 1 ){
14933      iBuddy = iBlock - size;
14934    }else{
14935      iBuddy = iBlock + size;
14936    }
14937    assert( iBuddy>=0 );
14938    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14939    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14940    memsys5Unlink(iBuddy, iLogsize);
14941    iLogsize++;
14942    if( iBuddy<iBlock ){
14943      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14944      mem5.aCtrl[iBlock] = 0;
14945      iBlock = iBuddy;
14946    }else{
14947      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14948      mem5.aCtrl[iBuddy] = 0;
14949    }
14950    size *= 2;
14951  }
14952  memsys5Link(iBlock, iLogsize);
14953}
14954
14955/*
14956** Allocate nBytes of memory
14957*/
14958static void *memsys5Malloc(int nBytes){
14959  sqlite3_int64 *p = 0;
14960  if( nBytes>0 ){
14961    memsys5Enter();
14962    p = memsys5MallocUnsafe(nBytes);
14963    memsys5Leave();
14964  }
14965  return (void*)p;
14966}
14967
14968/*
14969** Free memory.
14970**
14971** The outer layer memory allocator prevents this routine from
14972** being called with pPrior==0.
14973*/
14974static void memsys5Free(void *pPrior){
14975  assert( pPrior!=0 );
14976  memsys5Enter();
14977  memsys5FreeUnsafe(pPrior);
14978  memsys5Leave();
14979}
14980
14981/*
14982** Change the size of an existing memory allocation.
14983**
14984** The outer layer memory allocator prevents this routine from
14985** being called with pPrior==0.
14986**
14987** nBytes is always a value obtained from a prior call to
14988** memsys5Round().  Hence nBytes is always a non-negative power
14989** of two.  If nBytes==0 that means that an oversize allocation
14990** (an allocation larger than 0x40000000) was requested and this
14991** routine should return 0 without freeing pPrior.
14992*/
14993static void *memsys5Realloc(void *pPrior, int nBytes){
14994  int nOld;
14995  void *p;
14996  assert( pPrior!=0 );
14997  assert( (nBytes&(nBytes-1))==0 );
14998  assert( nBytes>=0 );
14999  if( nBytes==0 ){
15000    return 0;
15001  }
15002  nOld = memsys5Size(pPrior);
15003  if( nBytes<=nOld ){
15004    return pPrior;
15005  }
15006  memsys5Enter();
15007  p = memsys5MallocUnsafe(nBytes);
15008  if( p ){
15009    memcpy(p, pPrior, nOld);
15010    memsys5FreeUnsafe(pPrior);
15011  }
15012  memsys5Leave();
15013  return p;
15014}
15015
15016/*
15017** Round up a request size to the next valid allocation size.  If
15018** the allocation is too large to be handled by this allocation system,
15019** return 0.
15020**
15021** All allocations must be a power of two and must be expressed by a
15022** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15023** or 1073741824 bytes.
15024*/
15025static int memsys5Roundup(int n){
15026  int iFullSz;
15027  if( n > 0x40000000 ) return 0;
15028  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15029  return iFullSz;
15030}
15031
15032/*
15033** Return the ceiling of the logarithm base 2 of iValue.
15034**
15035** Examples:   memsys5Log(1) -> 0
15036**             memsys5Log(2) -> 1
15037**             memsys5Log(4) -> 2
15038**             memsys5Log(5) -> 3
15039**             memsys5Log(8) -> 3
15040**             memsys5Log(9) -> 4
15041*/
15042static int memsys5Log(int iValue){
15043  int iLog;
15044  for(iLog=0; (1<<iLog)<iValue; iLog++);
15045  return iLog;
15046}
15047
15048/*
15049** Initialize the memory allocator.
15050**
15051** This routine is not threadsafe.  The caller must be holding a mutex
15052** to prevent multiple threads from entering at the same time.
15053*/
15054static int memsys5Init(void *NotUsed){
15055  int ii;            /* Loop counter */
15056  int nByte;         /* Number of bytes of memory available to this allocator */
15057  u8 *zByte;         /* Memory usable by this allocator */
15058  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15059  int iOffset;       /* An offset into mem5.aCtrl[] */
15060
15061  UNUSED_PARAMETER(NotUsed);
15062
15063  /* For the purposes of this routine, disable the mutex */
15064  mem5.mutex = 0;
15065
15066  /* The size of a Mem5Link object must be a power of two.  Verify that
15067  ** this is case.
15068  */
15069  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15070
15071  nByte = sqlite3GlobalConfig.nHeap;
15072  zByte = (u8*)sqlite3GlobalConfig.pHeap;
15073  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15074
15075  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15076  mem5.szAtom = (1<<nMinLog);
15077  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15078    mem5.szAtom = mem5.szAtom << 1;
15079  }
15080
15081  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15082  mem5.zPool = zByte;
15083  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15084
15085  for(ii=0; ii<=LOGMAX; ii++){
15086    mem5.aiFreelist[ii] = -1;
15087  }
15088
15089  iOffset = 0;
15090  for(ii=LOGMAX; ii>=0; ii--){
15091    int nAlloc = (1<<ii);
15092    if( (iOffset+nAlloc)<=mem5.nBlock ){
15093      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15094      memsys5Link(iOffset, ii);
15095      iOffset += nAlloc;
15096    }
15097    assert((iOffset+nAlloc)>mem5.nBlock);
15098  }
15099
15100  /* If a mutex is required for normal operation, allocate one */
15101  if( sqlite3GlobalConfig.bMemstat==0 ){
15102    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15103  }
15104
15105  return SQLITE_OK;
15106}
15107
15108/*
15109** Deinitialize this module.
15110*/
15111static void memsys5Shutdown(void *NotUsed){
15112  UNUSED_PARAMETER(NotUsed);
15113  mem5.mutex = 0;
15114  return;
15115}
15116
15117#ifdef SQLITE_TEST
15118/*
15119** Open the file indicated and write a log of all unfreed memory
15120** allocations into that log.
15121*/
15122SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15123  FILE *out;
15124  int i, j, n;
15125  int nMinLog;
15126
15127  if( zFilename==0 || zFilename[0]==0 ){
15128    out = stdout;
15129  }else{
15130    out = fopen(zFilename, "w");
15131    if( out==0 ){
15132      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15133                      zFilename);
15134      return;
15135    }
15136  }
15137  memsys5Enter();
15138  nMinLog = memsys5Log(mem5.szAtom);
15139  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15140    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15141    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15142  }
15143  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15144  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15145  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15146  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15147  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15148  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15149  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15150  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15151  memsys5Leave();
15152  if( out==stdout ){
15153    fflush(stdout);
15154  }else{
15155    fclose(out);
15156  }
15157}
15158#endif
15159
15160/*
15161** This routine is the only routine in this file with external
15162** linkage. It returns a pointer to a static sqlite3_mem_methods
15163** struct populated with the memsys5 methods.
15164*/
15165SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15166  static const sqlite3_mem_methods memsys5Methods = {
15167     memsys5Malloc,
15168     memsys5Free,
15169     memsys5Realloc,
15170     memsys5Size,
15171     memsys5Roundup,
15172     memsys5Init,
15173     memsys5Shutdown,
15174     0
15175  };
15176  return &memsys5Methods;
15177}
15178
15179#endif /* SQLITE_ENABLE_MEMSYS5 */
15180
15181/************** End of mem5.c ************************************************/
15182/************** Begin file mutex.c *******************************************/
15183/*
15184** 2007 August 14
15185**
15186** The author disclaims copyright to this source code.  In place of
15187** a legal notice, here is a blessing:
15188**
15189**    May you do good and not evil.
15190**    May you find forgiveness for yourself and forgive others.
15191**    May you share freely, never taking more than you give.
15192**
15193*************************************************************************
15194** This file contains the C functions that implement mutexes.
15195**
15196** This file contains code that is common across all mutex implementations.
15197*/
15198
15199#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
15200/*
15201** For debugging purposes, record when the mutex subsystem is initialized
15202** and uninitialized so that we can assert() if there is an attempt to
15203** allocate a mutex while the system is uninitialized.
15204*/
15205static SQLITE_WSD int mutexIsInit = 0;
15206#endif /* SQLITE_DEBUG */
15207
15208
15209#ifndef SQLITE_MUTEX_OMIT
15210/*
15211** Initialize the mutex system.
15212*/
15213SQLITE_PRIVATE int sqlite3MutexInit(void){
15214  int rc = SQLITE_OK;
15215  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15216    /* If the xMutexAlloc method has not been set, then the user did not
15217    ** install a mutex implementation via sqlite3_config() prior to
15218    ** sqlite3_initialize() being called. This block copies pointers to
15219    ** the default implementation into the sqlite3GlobalConfig structure.
15220    */
15221    sqlite3_mutex_methods const *pFrom;
15222    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
15223
15224    if( sqlite3GlobalConfig.bCoreMutex ){
15225      pFrom = sqlite3DefaultMutex();
15226    }else{
15227      pFrom = sqlite3NoopMutex();
15228    }
15229    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
15230    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
15231           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
15232    pTo->xMutexAlloc = pFrom->xMutexAlloc;
15233  }
15234  rc = sqlite3GlobalConfig.mutex.xMutexInit();
15235
15236#ifdef SQLITE_DEBUG
15237  GLOBAL(int, mutexIsInit) = 1;
15238#endif
15239
15240  return rc;
15241}
15242
15243/*
15244** Shutdown the mutex system. This call frees resources allocated by
15245** sqlite3MutexInit().
15246*/
15247SQLITE_PRIVATE int sqlite3MutexEnd(void){
15248  int rc = SQLITE_OK;
15249  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15250    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15251  }
15252
15253#ifdef SQLITE_DEBUG
15254  GLOBAL(int, mutexIsInit) = 0;
15255#endif
15256
15257  return rc;
15258}
15259
15260/*
15261** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15262*/
15263SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15264#ifndef SQLITE_OMIT_AUTOINIT
15265  if( sqlite3_initialize() ) return 0;
15266#endif
15267  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15268}
15269
15270SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15271  if( !sqlite3GlobalConfig.bCoreMutex ){
15272    return 0;
15273  }
15274  assert( GLOBAL(int, mutexIsInit) );
15275  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15276}
15277
15278/*
15279** Free a dynamic mutex.
15280*/
15281SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15282  if( p ){
15283    sqlite3GlobalConfig.mutex.xMutexFree(p);
15284  }
15285}
15286
15287/*
15288** Obtain the mutex p. If some other thread already has the mutex, block
15289** until it can be obtained.
15290*/
15291SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15292  if( p ){
15293    sqlite3GlobalConfig.mutex.xMutexEnter(p);
15294  }
15295}
15296
15297/*
15298** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15299** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15300*/
15301SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15302  int rc = SQLITE_OK;
15303  if( p ){
15304    return sqlite3GlobalConfig.mutex.xMutexTry(p);
15305  }
15306  return rc;
15307}
15308
15309/*
15310** The sqlite3_mutex_leave() routine exits a mutex that was previously
15311** entered by the same thread.  The behavior is undefined if the mutex
15312** is not currently entered. If a NULL pointer is passed as an argument
15313** this function is a no-op.
15314*/
15315SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15316  if( p ){
15317    sqlite3GlobalConfig.mutex.xMutexLeave(p);
15318  }
15319}
15320
15321#ifndef NDEBUG
15322/*
15323** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15324** intended for use inside assert() statements.
15325*/
15326SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15327  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15328}
15329SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15330  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15331}
15332#endif
15333
15334#endif /* SQLITE_MUTEX_OMIT */
15335
15336/************** End of mutex.c ***********************************************/
15337/************** Begin file mutex_noop.c **************************************/
15338/*
15339** 2008 October 07
15340**
15341** The author disclaims copyright to this source code.  In place of
15342** a legal notice, here is a blessing:
15343**
15344**    May you do good and not evil.
15345**    May you find forgiveness for yourself and forgive others.
15346**    May you share freely, never taking more than you give.
15347**
15348*************************************************************************
15349** This file contains the C functions that implement mutexes.
15350**
15351** This implementation in this file does not provide any mutual
15352** exclusion and is thus suitable for use only in applications
15353** that use SQLite in a single thread.  The routines defined
15354** here are place-holders.  Applications can substitute working
15355** mutex routines at start-time using the
15356**
15357**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15358**
15359** interface.
15360**
15361** If compiled with SQLITE_DEBUG, then additional logic is inserted
15362** that does error checking on mutexes to make sure they are being
15363** called correctly.
15364*/
15365
15366#ifndef SQLITE_MUTEX_OMIT
15367
15368#ifndef SQLITE_DEBUG
15369/*
15370** Stub routines for all mutex methods.
15371**
15372** This routines provide no mutual exclusion or error checking.
15373*/
15374static int noopMutexInit(void){ return SQLITE_OK; }
15375static int noopMutexEnd(void){ return SQLITE_OK; }
15376static sqlite3_mutex *noopMutexAlloc(int id){
15377  UNUSED_PARAMETER(id);
15378  return (sqlite3_mutex*)8;
15379}
15380static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15381static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15382static int noopMutexTry(sqlite3_mutex *p){
15383  UNUSED_PARAMETER(p);
15384  return SQLITE_OK;
15385}
15386static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15387
15388SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15389  static const sqlite3_mutex_methods sMutex = {
15390    noopMutexInit,
15391    noopMutexEnd,
15392    noopMutexAlloc,
15393    noopMutexFree,
15394    noopMutexEnter,
15395    noopMutexTry,
15396    noopMutexLeave,
15397
15398    0,
15399    0,
15400  };
15401
15402  return &sMutex;
15403}
15404#endif /* !SQLITE_DEBUG */
15405
15406#ifdef SQLITE_DEBUG
15407/*
15408** In this implementation, error checking is provided for testing
15409** and debugging purposes.  The mutexes still do not provide any
15410** mutual exclusion.
15411*/
15412
15413/*
15414** The mutex object
15415*/
15416typedef struct sqlite3_debug_mutex {
15417  int id;     /* The mutex type */
15418  int cnt;    /* Number of entries without a matching leave */
15419} sqlite3_debug_mutex;
15420
15421/*
15422** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15423** intended for use inside assert() statements.
15424*/
15425static int debugMutexHeld(sqlite3_mutex *pX){
15426  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15427  return p==0 || p->cnt>0;
15428}
15429static int debugMutexNotheld(sqlite3_mutex *pX){
15430  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15431  return p==0 || p->cnt==0;
15432}
15433
15434/*
15435** Initialize and deinitialize the mutex subsystem.
15436*/
15437static int debugMutexInit(void){ return SQLITE_OK; }
15438static int debugMutexEnd(void){ return SQLITE_OK; }
15439
15440/*
15441** The sqlite3_mutex_alloc() routine allocates a new
15442** mutex and returns a pointer to it.  If it returns NULL
15443** that means that a mutex could not be allocated.
15444*/
15445static sqlite3_mutex *debugMutexAlloc(int id){
15446  static sqlite3_debug_mutex aStatic[6];
15447  sqlite3_debug_mutex *pNew = 0;
15448  switch( id ){
15449    case SQLITE_MUTEX_FAST:
15450    case SQLITE_MUTEX_RECURSIVE: {
15451      pNew = sqlite3Malloc(sizeof(*pNew));
15452      if( pNew ){
15453        pNew->id = id;
15454        pNew->cnt = 0;
15455      }
15456      break;
15457    }
15458    default: {
15459      assert( id-2 >= 0 );
15460      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15461      pNew = &aStatic[id-2];
15462      pNew->id = id;
15463      break;
15464    }
15465  }
15466  return (sqlite3_mutex*)pNew;
15467}
15468
15469/*
15470** This routine deallocates a previously allocated mutex.
15471*/
15472static void debugMutexFree(sqlite3_mutex *pX){
15473  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15474  assert( p->cnt==0 );
15475  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15476  sqlite3_free(p);
15477}
15478
15479/*
15480** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15481** to enter a mutex.  If another thread is already within the mutex,
15482** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15483** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15484** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15485** be entered multiple times by the same thread.  In such cases the,
15486** mutex must be exited an equal number of times before another thread
15487** can enter.  If the same thread tries to enter any other kind of mutex
15488** more than once, the behavior is undefined.
15489*/
15490static void debugMutexEnter(sqlite3_mutex *pX){
15491  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15492  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15493  p->cnt++;
15494}
15495static int debugMutexTry(sqlite3_mutex *pX){
15496  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15497  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15498  p->cnt++;
15499  return SQLITE_OK;
15500}
15501
15502/*
15503** The sqlite3_mutex_leave() routine exits a mutex that was
15504** previously entered by the same thread.  The behavior
15505** is undefined if the mutex is not currently entered or
15506** is not currently allocated.  SQLite will never do either.
15507*/
15508static void debugMutexLeave(sqlite3_mutex *pX){
15509  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15510  assert( debugMutexHeld(pX) );
15511  p->cnt--;
15512  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15513}
15514
15515SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15516  static const sqlite3_mutex_methods sMutex = {
15517    debugMutexInit,
15518    debugMutexEnd,
15519    debugMutexAlloc,
15520    debugMutexFree,
15521    debugMutexEnter,
15522    debugMutexTry,
15523    debugMutexLeave,
15524
15525    debugMutexHeld,
15526    debugMutexNotheld
15527  };
15528
15529  return &sMutex;
15530}
15531#endif /* SQLITE_DEBUG */
15532
15533/*
15534** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
15535** is used regardless of the run-time threadsafety setting.
15536*/
15537#ifdef SQLITE_MUTEX_NOOP
15538SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15539  return sqlite3NoopMutex();
15540}
15541#endif /* SQLITE_MUTEX_NOOP */
15542#endif /* SQLITE_MUTEX_OMIT */
15543
15544/************** End of mutex_noop.c ******************************************/
15545/************** Begin file mutex_os2.c ***************************************/
15546/*
15547** 2007 August 28
15548**
15549** The author disclaims copyright to this source code.  In place of
15550** a legal notice, here is a blessing:
15551**
15552**    May you do good and not evil.
15553**    May you find forgiveness for yourself and forgive others.
15554**    May you share freely, never taking more than you give.
15555**
15556*************************************************************************
15557** This file contains the C functions that implement mutexes for OS/2
15558*/
15559
15560/*
15561** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15562** See the mutex.h file for details.
15563*/
15564#ifdef SQLITE_MUTEX_OS2
15565
15566/********************** OS/2 Mutex Implementation **********************
15567**
15568** This implementation of mutexes is built using the OS/2 API.
15569*/
15570
15571/*
15572** The mutex object
15573** Each recursive mutex is an instance of the following structure.
15574*/
15575struct sqlite3_mutex {
15576  HMTX mutex;       /* Mutex controlling the lock */
15577  int  id;          /* Mutex type */
15578  int  nRef;        /* Number of references */
15579  TID  owner;       /* Thread holding this mutex */
15580};
15581
15582#define OS2_MUTEX_INITIALIZER   0,0,0,0
15583
15584/*
15585** Initialize and deinitialize the mutex subsystem.
15586*/
15587static int os2MutexInit(void){ return SQLITE_OK; }
15588static int os2MutexEnd(void){ return SQLITE_OK; }
15589
15590/*
15591** The sqlite3_mutex_alloc() routine allocates a new
15592** mutex and returns a pointer to it.  If it returns NULL
15593** that means that a mutex could not be allocated.
15594** SQLite will unwind its stack and return an error.  The argument
15595** to sqlite3_mutex_alloc() is one of these integer constants:
15596**
15597** <ul>
15598** <li>  SQLITE_MUTEX_FAST               0
15599** <li>  SQLITE_MUTEX_RECURSIVE          1
15600** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15601** <li>  SQLITE_MUTEX_STATIC_MEM         3
15602** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15603** </ul>
15604**
15605** The first two constants cause sqlite3_mutex_alloc() to create
15606** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15607** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15608** The mutex implementation does not need to make a distinction
15609** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15610** not want to.  But SQLite will only request a recursive mutex in
15611** cases where it really needs one.  If a faster non-recursive mutex
15612** implementation is available on the host platform, the mutex subsystem
15613** might return such a mutex in response to SQLITE_MUTEX_FAST.
15614**
15615** The other allowed parameters to sqlite3_mutex_alloc() each return
15616** a pointer to a static preexisting mutex.  Three static mutexes are
15617** used by the current version of SQLite.  Future versions of SQLite
15618** may add additional static mutexes.  Static mutexes are for internal
15619** use by SQLite only.  Applications that use SQLite mutexes should
15620** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15621** SQLITE_MUTEX_RECURSIVE.
15622**
15623** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15624** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15625** returns a different mutex on every call.  But for the static
15626** mutex types, the same mutex is returned on every call that has
15627** the same type number.
15628*/
15629static sqlite3_mutex *os2MutexAlloc(int iType){
15630  sqlite3_mutex *p = NULL;
15631  switch( iType ){
15632    case SQLITE_MUTEX_FAST:
15633    case SQLITE_MUTEX_RECURSIVE: {
15634      p = sqlite3MallocZero( sizeof(*p) );
15635      if( p ){
15636        p->id = iType;
15637        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15638          sqlite3_free( p );
15639          p = NULL;
15640        }
15641      }
15642      break;
15643    }
15644    default: {
15645      static volatile int isInit = 0;
15646      static sqlite3_mutex staticMutexes[] = {
15647        { OS2_MUTEX_INITIALIZER, },
15648        { OS2_MUTEX_INITIALIZER, },
15649        { OS2_MUTEX_INITIALIZER, },
15650        { OS2_MUTEX_INITIALIZER, },
15651        { OS2_MUTEX_INITIALIZER, },
15652        { OS2_MUTEX_INITIALIZER, },
15653      };
15654      if ( !isInit ){
15655        APIRET rc;
15656        PTIB ptib;
15657        PPIB ppib;
15658        HMTX mutex;
15659        char name[32];
15660        DosGetInfoBlocks( &ptib, &ppib );
15661        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15662                          ppib->pib_ulpid );
15663        while( !isInit ){
15664          mutex = 0;
15665          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15666          if( rc == NO_ERROR ){
15667            unsigned int i;
15668            if( !isInit ){
15669              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15670                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15671              }
15672              isInit = 1;
15673            }
15674            DosCloseMutexSem( mutex );
15675          }else if( rc == ERROR_DUPLICATE_NAME ){
15676            DosSleep( 1 );
15677          }else{
15678            return p;
15679          }
15680        }
15681      }
15682      assert( iType-2 >= 0 );
15683      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15684      p = &staticMutexes[iType-2];
15685      p->id = iType;
15686      break;
15687    }
15688  }
15689  return p;
15690}
15691
15692
15693/*
15694** This routine deallocates a previously allocated mutex.
15695** SQLite is careful to deallocate every mutex that it allocates.
15696*/
15697static void os2MutexFree(sqlite3_mutex *p){
15698  if( p==0 ) return;
15699  assert( p->nRef==0 );
15700  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15701  DosCloseMutexSem( p->mutex );
15702  sqlite3_free( p );
15703}
15704
15705#ifdef SQLITE_DEBUG
15706/*
15707** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15708** intended for use inside assert() statements.
15709*/
15710static int os2MutexHeld(sqlite3_mutex *p){
15711  TID tid;
15712  PID pid;
15713  ULONG ulCount;
15714  PTIB ptib;
15715  if( p!=0 ) {
15716    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15717  } else {
15718    DosGetInfoBlocks(&ptib, NULL);
15719    tid = ptib->tib_ptib2->tib2_ultid;
15720  }
15721  return p==0 || (p->nRef!=0 && p->owner==tid);
15722}
15723static int os2MutexNotheld(sqlite3_mutex *p){
15724  TID tid;
15725  PID pid;
15726  ULONG ulCount;
15727  PTIB ptib;
15728  if( p!= 0 ) {
15729    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15730  } else {
15731    DosGetInfoBlocks(&ptib, NULL);
15732    tid = ptib->tib_ptib2->tib2_ultid;
15733  }
15734  return p==0 || p->nRef==0 || p->owner!=tid;
15735}
15736#endif
15737
15738/*
15739** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15740** to enter a mutex.  If another thread is already within the mutex,
15741** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15742** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15743** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15744** be entered multiple times by the same thread.  In such cases the,
15745** mutex must be exited an equal number of times before another thread
15746** can enter.  If the same thread tries to enter any other kind of mutex
15747** more than once, the behavior is undefined.
15748*/
15749static void os2MutexEnter(sqlite3_mutex *p){
15750  TID tid;
15751  PID holder1;
15752  ULONG holder2;
15753  if( p==0 ) return;
15754  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15755  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15756  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15757  p->owner = tid;
15758  p->nRef++;
15759}
15760static int os2MutexTry(sqlite3_mutex *p){
15761  int rc;
15762  TID tid;
15763  PID holder1;
15764  ULONG holder2;
15765  if( p==0 ) return SQLITE_OK;
15766  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15767  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15768    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15769    p->owner = tid;
15770    p->nRef++;
15771    rc = SQLITE_OK;
15772  } else {
15773    rc = SQLITE_BUSY;
15774  }
15775
15776  return rc;
15777}
15778
15779/*
15780** The sqlite3_mutex_leave() routine exits a mutex that was
15781** previously entered by the same thread.  The behavior
15782** is undefined if the mutex is not currently entered or
15783** is not currently allocated.  SQLite will never do either.
15784*/
15785static void os2MutexLeave(sqlite3_mutex *p){
15786  TID tid;
15787  PID holder1;
15788  ULONG holder2;
15789  if( p==0 ) return;
15790  assert( p->nRef>0 );
15791  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15792  assert( p->owner==tid );
15793  p->nRef--;
15794  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15795  DosReleaseMutexSem(p->mutex);
15796}
15797
15798SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15799  static const sqlite3_mutex_methods sMutex = {
15800    os2MutexInit,
15801    os2MutexEnd,
15802    os2MutexAlloc,
15803    os2MutexFree,
15804    os2MutexEnter,
15805    os2MutexTry,
15806    os2MutexLeave,
15807#ifdef SQLITE_DEBUG
15808    os2MutexHeld,
15809    os2MutexNotheld
15810#endif
15811  };
15812
15813  return &sMutex;
15814}
15815#endif /* SQLITE_MUTEX_OS2 */
15816
15817/************** End of mutex_os2.c *******************************************/
15818/************** Begin file mutex_unix.c **************************************/
15819/*
15820** 2007 August 28
15821**
15822** The author disclaims copyright to this source code.  In place of
15823** a legal notice, here is a blessing:
15824**
15825**    May you do good and not evil.
15826**    May you find forgiveness for yourself and forgive others.
15827**    May you share freely, never taking more than you give.
15828**
15829*************************************************************************
15830** This file contains the C functions that implement mutexes for pthreads
15831*/
15832
15833/*
15834** The code in this file is only used if we are compiling threadsafe
15835** under unix with pthreads.
15836**
15837** Note that this implementation requires a version of pthreads that
15838** supports recursive mutexes.
15839*/
15840#ifdef SQLITE_MUTEX_PTHREADS
15841
15842#include <pthread.h>
15843
15844/*
15845** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
15846** are necessary under two condidtions:  (1) Debug builds and (2) using
15847** home-grown mutexes.  Encapsulate these conditions into a single #define.
15848*/
15849#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
15850# define SQLITE_MUTEX_NREF 1
15851#else
15852# define SQLITE_MUTEX_NREF 0
15853#endif
15854
15855/*
15856** Each recursive mutex is an instance of the following structure.
15857*/
15858struct sqlite3_mutex {
15859  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15860#if SQLITE_MUTEX_NREF
15861  int id;                    /* Mutex type */
15862  volatile int nRef;         /* Number of entrances */
15863  volatile pthread_t owner;  /* Thread that is within this mutex */
15864  int trace;                 /* True to trace changes */
15865#endif
15866};
15867#if SQLITE_MUTEX_NREF
15868#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15869#else
15870#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
15871#endif
15872
15873/*
15874** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15875** intended for use only inside assert() statements.  On some platforms,
15876** there might be race conditions that can cause these routines to
15877** deliver incorrect results.  In particular, if pthread_equal() is
15878** not an atomic operation, then these routines might delivery
15879** incorrect results.  On most platforms, pthread_equal() is a
15880** comparison of two integers and is therefore atomic.  But we are
15881** told that HPUX is not such a platform.  If so, then these routines
15882** will not always work correctly on HPUX.
15883**
15884** On those platforms where pthread_equal() is not atomic, SQLite
15885** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15886** make sure no assert() statements are evaluated and hence these
15887** routines are never called.
15888*/
15889#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15890static int pthreadMutexHeld(sqlite3_mutex *p){
15891  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15892}
15893static int pthreadMutexNotheld(sqlite3_mutex *p){
15894  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15895}
15896#endif
15897
15898/*
15899** Initialize and deinitialize the mutex subsystem.
15900*/
15901static int pthreadMutexInit(void){ return SQLITE_OK; }
15902static int pthreadMutexEnd(void){ return SQLITE_OK; }
15903
15904/*
15905** The sqlite3_mutex_alloc() routine allocates a new
15906** mutex and returns a pointer to it.  If it returns NULL
15907** that means that a mutex could not be allocated.  SQLite
15908** will unwind its stack and return an error.  The argument
15909** to sqlite3_mutex_alloc() is one of these integer constants:
15910**
15911** <ul>
15912** <li>  SQLITE_MUTEX_FAST
15913** <li>  SQLITE_MUTEX_RECURSIVE
15914** <li>  SQLITE_MUTEX_STATIC_MASTER
15915** <li>  SQLITE_MUTEX_STATIC_MEM
15916** <li>  SQLITE_MUTEX_STATIC_MEM2
15917** <li>  SQLITE_MUTEX_STATIC_PRNG
15918** <li>  SQLITE_MUTEX_STATIC_LRU
15919** <li>  SQLITE_MUTEX_STATIC_LRU2
15920** </ul>
15921**
15922** The first two constants cause sqlite3_mutex_alloc() to create
15923** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15924** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15925** The mutex implementation does not need to make a distinction
15926** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15927** not want to.  But SQLite will only request a recursive mutex in
15928** cases where it really needs one.  If a faster non-recursive mutex
15929** implementation is available on the host platform, the mutex subsystem
15930** might return such a mutex in response to SQLITE_MUTEX_FAST.
15931**
15932** The other allowed parameters to sqlite3_mutex_alloc() each return
15933** a pointer to a static preexisting mutex.  Six static mutexes are
15934** used by the current version of SQLite.  Future versions of SQLite
15935** may add additional static mutexes.  Static mutexes are for internal
15936** use by SQLite only.  Applications that use SQLite mutexes should
15937** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15938** SQLITE_MUTEX_RECURSIVE.
15939**
15940** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15941** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15942** returns a different mutex on every call.  But for the static
15943** mutex types, the same mutex is returned on every call that has
15944** the same type number.
15945*/
15946static sqlite3_mutex *pthreadMutexAlloc(int iType){
15947  static sqlite3_mutex staticMutexes[] = {
15948    SQLITE3_MUTEX_INITIALIZER,
15949    SQLITE3_MUTEX_INITIALIZER,
15950    SQLITE3_MUTEX_INITIALIZER,
15951    SQLITE3_MUTEX_INITIALIZER,
15952    SQLITE3_MUTEX_INITIALIZER,
15953    SQLITE3_MUTEX_INITIALIZER
15954  };
15955  sqlite3_mutex *p;
15956  switch( iType ){
15957    case SQLITE_MUTEX_RECURSIVE: {
15958      p = sqlite3MallocZero( sizeof(*p) );
15959      if( p ){
15960#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15961        /* If recursive mutexes are not available, we will have to
15962        ** build our own.  See below. */
15963        pthread_mutex_init(&p->mutex, 0);
15964#else
15965        /* Use a recursive mutex if it is available */
15966        pthread_mutexattr_t recursiveAttr;
15967        pthread_mutexattr_init(&recursiveAttr);
15968        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15969        pthread_mutex_init(&p->mutex, &recursiveAttr);
15970        pthread_mutexattr_destroy(&recursiveAttr);
15971#endif
15972#if SQLITE_MUTEX_NREF
15973        p->id = iType;
15974#endif
15975      }
15976      break;
15977    }
15978    case SQLITE_MUTEX_FAST: {
15979      p = sqlite3MallocZero( sizeof(*p) );
15980      if( p ){
15981#if SQLITE_MUTEX_NREF
15982        p->id = iType;
15983#endif
15984        pthread_mutex_init(&p->mutex, 0);
15985      }
15986      break;
15987    }
15988    default: {
15989      assert( iType-2 >= 0 );
15990      assert( iType-2 < ArraySize(staticMutexes) );
15991      p = &staticMutexes[iType-2];
15992#if SQLITE_MUTEX_NREF
15993      p->id = iType;
15994#endif
15995      break;
15996    }
15997  }
15998  return p;
15999}
16000
16001
16002/*
16003** This routine deallocates a previously
16004** allocated mutex.  SQLite is careful to deallocate every
16005** mutex that it allocates.
16006*/
16007static void pthreadMutexFree(sqlite3_mutex *p){
16008  assert( p->nRef==0 );
16009  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16010  pthread_mutex_destroy(&p->mutex);
16011  sqlite3_free(p);
16012}
16013
16014/*
16015** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16016** to enter a mutex.  If another thread is already within the mutex,
16017** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16018** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16019** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16020** be entered multiple times by the same thread.  In such cases the,
16021** mutex must be exited an equal number of times before another thread
16022** can enter.  If the same thread tries to enter any other kind of mutex
16023** more than once, the behavior is undefined.
16024*/
16025static void pthreadMutexEnter(sqlite3_mutex *p){
16026  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16027
16028#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16029  /* If recursive mutexes are not available, then we have to grow
16030  ** our own.  This implementation assumes that pthread_equal()
16031  ** is atomic - that it cannot be deceived into thinking self
16032  ** and p->owner are equal if p->owner changes between two values
16033  ** that are not equal to self while the comparison is taking place.
16034  ** This implementation also assumes a coherent cache - that
16035  ** separate processes cannot read different values from the same
16036  ** address at the same time.  If either of these two conditions
16037  ** are not met, then the mutexes will fail and problems will result.
16038  */
16039  {
16040    pthread_t self = pthread_self();
16041    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16042      p->nRef++;
16043    }else{
16044      pthread_mutex_lock(&p->mutex);
16045      assert( p->nRef==0 );
16046      p->owner = self;
16047      p->nRef = 1;
16048    }
16049  }
16050#else
16051  /* Use the built-in recursive mutexes if they are available.
16052  */
16053  pthread_mutex_lock(&p->mutex);
16054#if SQLITE_MUTEX_NREF
16055  p->owner = pthread_self();
16056  p->nRef++;
16057#endif
16058#endif
16059
16060#ifdef SQLITE_DEBUG
16061  if( p->trace ){
16062    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16063  }
16064#endif
16065}
16066static int pthreadMutexTry(sqlite3_mutex *p){
16067  int rc;
16068  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16069
16070#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16071  /* If recursive mutexes are not available, then we have to grow
16072  ** our own.  This implementation assumes that pthread_equal()
16073  ** is atomic - that it cannot be deceived into thinking self
16074  ** and p->owner are equal if p->owner changes between two values
16075  ** that are not equal to self while the comparison is taking place.
16076  ** This implementation also assumes a coherent cache - that
16077  ** separate processes cannot read different values from the same
16078  ** address at the same time.  If either of these two conditions
16079  ** are not met, then the mutexes will fail and problems will result.
16080  */
16081  {
16082    pthread_t self = pthread_self();
16083    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16084      p->nRef++;
16085      rc = SQLITE_OK;
16086    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16087      assert( p->nRef==0 );
16088      p->owner = self;
16089      p->nRef = 1;
16090      rc = SQLITE_OK;
16091    }else{
16092      rc = SQLITE_BUSY;
16093    }
16094  }
16095#else
16096  /* Use the built-in recursive mutexes if they are available.
16097  */
16098  if( pthread_mutex_trylock(&p->mutex)==0 ){
16099#if SQLITE_MUTEX_NREF
16100    p->owner = pthread_self();
16101    p->nRef++;
16102#endif
16103    rc = SQLITE_OK;
16104  }else{
16105    rc = SQLITE_BUSY;
16106  }
16107#endif
16108
16109#ifdef SQLITE_DEBUG
16110  if( rc==SQLITE_OK && p->trace ){
16111    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16112  }
16113#endif
16114  return rc;
16115}
16116
16117/*
16118** The sqlite3_mutex_leave() routine exits a mutex that was
16119** previously entered by the same thread.  The behavior
16120** is undefined if the mutex is not currently entered or
16121** is not currently allocated.  SQLite will never do either.
16122*/
16123static void pthreadMutexLeave(sqlite3_mutex *p){
16124  assert( pthreadMutexHeld(p) );
16125#if SQLITE_MUTEX_NREF
16126  p->nRef--;
16127#endif
16128  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16129
16130#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16131  if( p->nRef==0 ){
16132    pthread_mutex_unlock(&p->mutex);
16133  }
16134#else
16135  pthread_mutex_unlock(&p->mutex);
16136#endif
16137
16138#ifdef SQLITE_DEBUG
16139  if( p->trace ){
16140    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16141  }
16142#endif
16143}
16144
16145SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16146  static const sqlite3_mutex_methods sMutex = {
16147    pthreadMutexInit,
16148    pthreadMutexEnd,
16149    pthreadMutexAlloc,
16150    pthreadMutexFree,
16151    pthreadMutexEnter,
16152    pthreadMutexTry,
16153    pthreadMutexLeave,
16154#ifdef SQLITE_DEBUG
16155    pthreadMutexHeld,
16156    pthreadMutexNotheld
16157#else
16158    0,
16159    0
16160#endif
16161  };
16162
16163  return &sMutex;
16164}
16165
16166#endif /* SQLITE_MUTEX_PTHREAD */
16167
16168/************** End of mutex_unix.c ******************************************/
16169/************** Begin file mutex_w32.c ***************************************/
16170/*
16171** 2007 August 14
16172**
16173** The author disclaims copyright to this source code.  In place of
16174** a legal notice, here is a blessing:
16175**
16176**    May you do good and not evil.
16177**    May you find forgiveness for yourself and forgive others.
16178**    May you share freely, never taking more than you give.
16179**
16180*************************************************************************
16181** This file contains the C functions that implement mutexes for win32
16182*/
16183
16184/*
16185** The code in this file is only used if we are compiling multithreaded
16186** on a win32 system.
16187*/
16188#ifdef SQLITE_MUTEX_W32
16189
16190/*
16191** Each recursive mutex is an instance of the following structure.
16192*/
16193struct sqlite3_mutex {
16194  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16195  int id;                    /* Mutex type */
16196#ifdef SQLITE_DEBUG
16197  volatile int nRef;         /* Number of enterances */
16198  volatile DWORD owner;      /* Thread holding this mutex */
16199  int trace;                 /* True to trace changes */
16200#endif
16201};
16202#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
16203#ifdef SQLITE_DEBUG
16204#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
16205#else
16206#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
16207#endif
16208
16209/*
16210** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16211** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16212**
16213** Here is an interesting observation:  Win95, Win98, and WinME lack
16214** the LockFileEx() API.  But we can still statically link against that
16215** API as long as we don't call it win running Win95/98/ME.  A call to
16216** this routine is used to determine if the host is Win95/98/ME or
16217** WinNT/2K/XP so that we will know whether or not we can safely call
16218** the LockFileEx() API.
16219**
16220** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16221** which is only available if your application was compiled with
16222** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16223** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
16224** this out as well.
16225*/
16226#if 0
16227#if SQLITE_OS_WINCE
16228# define mutexIsNT()  (1)
16229#else
16230  static int mutexIsNT(void){
16231    static int osType = 0;
16232    if( osType==0 ){
16233      OSVERSIONINFO sInfo;
16234      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16235      GetVersionEx(&sInfo);
16236      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16237    }
16238    return osType==2;
16239  }
16240#endif /* SQLITE_OS_WINCE */
16241#endif
16242
16243#ifdef SQLITE_DEBUG
16244/*
16245** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16246** intended for use only inside assert() statements.
16247*/
16248static int winMutexHeld(sqlite3_mutex *p){
16249  return p->nRef!=0 && p->owner==GetCurrentThreadId();
16250}
16251static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
16252  return p->nRef==0 || p->owner!=tid;
16253}
16254static int winMutexNotheld(sqlite3_mutex *p){
16255  DWORD tid = GetCurrentThreadId();
16256  return winMutexNotheld2(p, tid);
16257}
16258#endif
16259
16260
16261/*
16262** Initialize and deinitialize the mutex subsystem.
16263*/
16264static sqlite3_mutex winMutex_staticMutexes[6] = {
16265  SQLITE3_MUTEX_INITIALIZER,
16266  SQLITE3_MUTEX_INITIALIZER,
16267  SQLITE3_MUTEX_INITIALIZER,
16268  SQLITE3_MUTEX_INITIALIZER,
16269  SQLITE3_MUTEX_INITIALIZER,
16270  SQLITE3_MUTEX_INITIALIZER
16271};
16272static int winMutex_isInit = 0;
16273/* As winMutexInit() and winMutexEnd() are called as part
16274** of the sqlite3_initialize and sqlite3_shutdown()
16275** processing, the "interlocked" magic is probably not
16276** strictly necessary.
16277*/
16278static long winMutex_lock = 0;
16279
16280static int winMutexInit(void){
16281  /* The first to increment to 1 does actual initialization */
16282  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
16283    int i;
16284    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16285      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
16286    }
16287    winMutex_isInit = 1;
16288  }else{
16289    /* Someone else is in the process of initing the static mutexes */
16290    while( !winMutex_isInit ){
16291      Sleep(1);
16292    }
16293  }
16294  return SQLITE_OK;
16295}
16296
16297static int winMutexEnd(void){
16298  /* The first to decrement to 0 does actual shutdown
16299  ** (which should be the last to shutdown.) */
16300  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
16301    if( winMutex_isInit==1 ){
16302      int i;
16303      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16304        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
16305      }
16306      winMutex_isInit = 0;
16307    }
16308  }
16309  return SQLITE_OK;
16310}
16311
16312/*
16313** The sqlite3_mutex_alloc() routine allocates a new
16314** mutex and returns a pointer to it.  If it returns NULL
16315** that means that a mutex could not be allocated.  SQLite
16316** will unwind its stack and return an error.  The argument
16317** to sqlite3_mutex_alloc() is one of these integer constants:
16318**
16319** <ul>
16320** <li>  SQLITE_MUTEX_FAST
16321** <li>  SQLITE_MUTEX_RECURSIVE
16322** <li>  SQLITE_MUTEX_STATIC_MASTER
16323** <li>  SQLITE_MUTEX_STATIC_MEM
16324** <li>  SQLITE_MUTEX_STATIC_MEM2
16325** <li>  SQLITE_MUTEX_STATIC_PRNG
16326** <li>  SQLITE_MUTEX_STATIC_LRU
16327** <li>  SQLITE_MUTEX_STATIC_LRU2
16328** </ul>
16329**
16330** The first two constants cause sqlite3_mutex_alloc() to create
16331** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16332** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16333** The mutex implementation does not need to make a distinction
16334** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16335** not want to.  But SQLite will only request a recursive mutex in
16336** cases where it really needs one.  If a faster non-recursive mutex
16337** implementation is available on the host platform, the mutex subsystem
16338** might return such a mutex in response to SQLITE_MUTEX_FAST.
16339**
16340** The other allowed parameters to sqlite3_mutex_alloc() each return
16341** a pointer to a static preexisting mutex.  Six static mutexes are
16342** used by the current version of SQLite.  Future versions of SQLite
16343** may add additional static mutexes.  Static mutexes are for internal
16344** use by SQLite only.  Applications that use SQLite mutexes should
16345** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16346** SQLITE_MUTEX_RECURSIVE.
16347**
16348** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16349** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16350** returns a different mutex on every call.  But for the static
16351** mutex types, the same mutex is returned on every call that has
16352** the same type number.
16353*/
16354static sqlite3_mutex *winMutexAlloc(int iType){
16355  sqlite3_mutex *p;
16356
16357  switch( iType ){
16358    case SQLITE_MUTEX_FAST:
16359    case SQLITE_MUTEX_RECURSIVE: {
16360      p = sqlite3MallocZero( sizeof(*p) );
16361      if( p ){
16362#ifdef SQLITE_DEBUG
16363        p->id = iType;
16364#endif
16365        InitializeCriticalSection(&p->mutex);
16366      }
16367      break;
16368    }
16369    default: {
16370      assert( winMutex_isInit==1 );
16371      assert( iType-2 >= 0 );
16372      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
16373      p = &winMutex_staticMutexes[iType-2];
16374#ifdef SQLITE_DEBUG
16375      p->id = iType;
16376#endif
16377      break;
16378    }
16379  }
16380  return p;
16381}
16382
16383
16384/*
16385** This routine deallocates a previously
16386** allocated mutex.  SQLite is careful to deallocate every
16387** mutex that it allocates.
16388*/
16389static void winMutexFree(sqlite3_mutex *p){
16390  assert( p );
16391  assert( p->nRef==0 );
16392  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16393  DeleteCriticalSection(&p->mutex);
16394  sqlite3_free(p);
16395}
16396
16397/*
16398** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16399** to enter a mutex.  If another thread is already within the mutex,
16400** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16401** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16402** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16403** be entered multiple times by the same thread.  In such cases the,
16404** mutex must be exited an equal number of times before another thread
16405** can enter.  If the same thread tries to enter any other kind of mutex
16406** more than once, the behavior is undefined.
16407*/
16408static void winMutexEnter(sqlite3_mutex *p){
16409#ifdef SQLITE_DEBUG
16410  DWORD tid = GetCurrentThreadId();
16411  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16412#endif
16413  EnterCriticalSection(&p->mutex);
16414#ifdef SQLITE_DEBUG
16415  p->owner = tid;
16416  p->nRef++;
16417  if( p->trace ){
16418    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16419  }
16420#endif
16421}
16422static int winMutexTry(sqlite3_mutex *p){
16423#ifndef NDEBUG
16424  DWORD tid = GetCurrentThreadId();
16425#endif
16426  int rc = SQLITE_BUSY;
16427  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16428  /*
16429  ** The sqlite3_mutex_try() routine is very rarely used, and when it
16430  ** is used it is merely an optimization.  So it is OK for it to always
16431  ** fail.
16432  **
16433  ** The TryEnterCriticalSection() interface is only available on WinNT.
16434  ** And some windows compilers complain if you try to use it without
16435  ** first doing some #defines that prevent SQLite from building on Win98.
16436  ** For that reason, we will omit this optimization for now.  See
16437  ** ticket #2685.
16438  */
16439#if 0
16440  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16441    p->owner = tid;
16442    p->nRef++;
16443    rc = SQLITE_OK;
16444  }
16445#else
16446  UNUSED_PARAMETER(p);
16447#endif
16448#ifdef SQLITE_DEBUG
16449  if( rc==SQLITE_OK && p->trace ){
16450    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16451  }
16452#endif
16453  return rc;
16454}
16455
16456/*
16457** The sqlite3_mutex_leave() routine exits a mutex that was
16458** previously entered by the same thread.  The behavior
16459** is undefined if the mutex is not currently entered or
16460** is not currently allocated.  SQLite will never do either.
16461*/
16462static void winMutexLeave(sqlite3_mutex *p){
16463#ifndef NDEBUG
16464  DWORD tid = GetCurrentThreadId();
16465  assert( p->nRef>0 );
16466  assert( p->owner==tid );
16467  p->nRef--;
16468  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16469#endif
16470  LeaveCriticalSection(&p->mutex);
16471#ifdef SQLITE_DEBUG
16472  if( p->trace ){
16473    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16474  }
16475#endif
16476}
16477
16478SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16479  static const sqlite3_mutex_methods sMutex = {
16480    winMutexInit,
16481    winMutexEnd,
16482    winMutexAlloc,
16483    winMutexFree,
16484    winMutexEnter,
16485    winMutexTry,
16486    winMutexLeave,
16487#ifdef SQLITE_DEBUG
16488    winMutexHeld,
16489    winMutexNotheld
16490#else
16491    0,
16492    0
16493#endif
16494  };
16495
16496  return &sMutex;
16497}
16498#endif /* SQLITE_MUTEX_W32 */
16499
16500/************** End of mutex_w32.c *******************************************/
16501/************** Begin file malloc.c ******************************************/
16502/*
16503** 2001 September 15
16504**
16505** The author disclaims copyright to this source code.  In place of
16506** a legal notice, here is a blessing:
16507**
16508**    May you do good and not evil.
16509**    May you find forgiveness for yourself and forgive others.
16510**    May you share freely, never taking more than you give.
16511**
16512*************************************************************************
16513**
16514** Memory allocation functions used throughout sqlite.
16515*/
16516
16517/*
16518** This routine runs when the memory allocator sees that the
16519** total memory allocation is about to exceed the soft heap
16520** limit.
16521*/
16522static void softHeapLimitEnforcer(
16523  void *NotUsed,
16524  sqlite3_int64 NotUsed2,
16525  int allocSize
16526){
16527  UNUSED_PARAMETER2(NotUsed, NotUsed2);
16528  sqlite3_release_memory(allocSize);
16529}
16530
16531/*
16532** Set the soft heap-size limit for the library. Passing a zero or
16533** negative value indicates no limit.
16534*/
16535SQLITE_API void sqlite3_soft_heap_limit(int n){
16536  sqlite3_uint64 iLimit;
16537  int overage;
16538  if( n<0 ){
16539    iLimit = 0;
16540  }else{
16541    iLimit = n;
16542  }
16543#ifndef SQLITE_OMIT_AUTOINIT
16544  sqlite3_initialize();
16545#endif
16546  if( iLimit>0 ){
16547    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16548  }else{
16549    sqlite3MemoryAlarm(0, 0, 0);
16550  }
16551  overage = (int)(sqlite3_memory_used() - (i64)n);
16552  if( overage>0 ){
16553    sqlite3_release_memory(overage);
16554  }
16555}
16556
16557/*
16558** Attempt to release up to n bytes of non-essential memory currently
16559** held by SQLite. An example of non-essential memory is memory used to
16560** cache database pages that are not currently in use.
16561*/
16562SQLITE_API int sqlite3_release_memory(int n){
16563#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16564  int nRet = 0;
16565  nRet += sqlite3PcacheReleaseMemory(n-nRet);
16566  return nRet;
16567#else
16568  UNUSED_PARAMETER(n);
16569  return SQLITE_OK;
16570#endif
16571}
16572
16573/*
16574** State information local to the memory allocation subsystem.
16575*/
16576static SQLITE_WSD struct Mem0Global {
16577  /* Number of free pages for scratch and page-cache memory */
16578  u32 nScratchFree;
16579  u32 nPageFree;
16580
16581  sqlite3_mutex *mutex;         /* Mutex to serialize access */
16582
16583  /*
16584  ** The alarm callback and its arguments.  The mem0.mutex lock will
16585  ** be held while the callback is running.  Recursive calls into
16586  ** the memory subsystem are allowed, but no new callbacks will be
16587  ** issued.
16588  */
16589  sqlite3_int64 alarmThreshold;
16590  void (*alarmCallback)(void*, sqlite3_int64,int);
16591  void *alarmArg;
16592
16593  /*
16594  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16595  ** sqlite3GlobalConfig.pPage to a block of memory that records
16596  ** which pages are available.
16597  */
16598  u32 *aScratchFree;
16599  u32 *aPageFree;
16600} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
16601
16602#define mem0 GLOBAL(struct Mem0Global, mem0)
16603
16604/*
16605** Initialize the memory allocation subsystem.
16606*/
16607SQLITE_PRIVATE int sqlite3MallocInit(void){
16608  if( sqlite3GlobalConfig.m.xMalloc==0 ){
16609    sqlite3MemSetDefault();
16610  }
16611  memset(&mem0, 0, sizeof(mem0));
16612  if( sqlite3GlobalConfig.bCoreMutex ){
16613    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16614  }
16615  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16616      && sqlite3GlobalConfig.nScratch>=0 ){
16617    int i;
16618    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
16619    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16620                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16621    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16622    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16623  }else{
16624    sqlite3GlobalConfig.pScratch = 0;
16625    sqlite3GlobalConfig.szScratch = 0;
16626  }
16627  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16628      && sqlite3GlobalConfig.nPage>=1 ){
16629    int i;
16630    int overhead;
16631    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
16632    int n = sqlite3GlobalConfig.nPage;
16633    overhead = (4*n + sz - 1)/sz;
16634    sqlite3GlobalConfig.nPage -= overhead;
16635    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16636                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16637    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16638    mem0.nPageFree = sqlite3GlobalConfig.nPage;
16639  }else{
16640    sqlite3GlobalConfig.pPage = 0;
16641    sqlite3GlobalConfig.szPage = 0;
16642  }
16643  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16644}
16645
16646/*
16647** Deinitialize the memory allocation subsystem.
16648*/
16649SQLITE_PRIVATE void sqlite3MallocEnd(void){
16650  if( sqlite3GlobalConfig.m.xShutdown ){
16651    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16652  }
16653  memset(&mem0, 0, sizeof(mem0));
16654}
16655
16656/*
16657** Return the amount of memory currently checked out.
16658*/
16659SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16660  int n, mx;
16661  sqlite3_int64 res;
16662  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16663  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16664  return res;
16665}
16666
16667/*
16668** Return the maximum amount of memory that has ever been
16669** checked out since either the beginning of this process
16670** or since the most recent reset.
16671*/
16672SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16673  int n, mx;
16674  sqlite3_int64 res;
16675  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16676  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16677  return res;
16678}
16679
16680/*
16681** Change the alarm callback
16682*/
16683SQLITE_PRIVATE int sqlite3MemoryAlarm(
16684  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16685  void *pArg,
16686  sqlite3_int64 iThreshold
16687){
16688  sqlite3_mutex_enter(mem0.mutex);
16689  mem0.alarmCallback = xCallback;
16690  mem0.alarmArg = pArg;
16691  mem0.alarmThreshold = iThreshold;
16692  sqlite3_mutex_leave(mem0.mutex);
16693  return SQLITE_OK;
16694}
16695
16696#ifndef SQLITE_OMIT_DEPRECATED
16697/*
16698** Deprecated external interface.  Internal/core SQLite code
16699** should call sqlite3MemoryAlarm.
16700*/
16701SQLITE_API int sqlite3_memory_alarm(
16702  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16703  void *pArg,
16704  sqlite3_int64 iThreshold
16705){
16706  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16707}
16708#endif
16709
16710/*
16711** Trigger the alarm
16712*/
16713static void sqlite3MallocAlarm(int nByte){
16714  void (*xCallback)(void*,sqlite3_int64,int);
16715  sqlite3_int64 nowUsed;
16716  void *pArg;
16717  if( mem0.alarmCallback==0 ) return;
16718  xCallback = mem0.alarmCallback;
16719  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16720  pArg = mem0.alarmArg;
16721  mem0.alarmCallback = 0;
16722  sqlite3_mutex_leave(mem0.mutex);
16723  xCallback(pArg, nowUsed, nByte);
16724  sqlite3_mutex_enter(mem0.mutex);
16725  mem0.alarmCallback = xCallback;
16726  mem0.alarmArg = pArg;
16727}
16728
16729/*
16730** Do a memory allocation with statistics and alarms.  Assume the
16731** lock is already held.
16732*/
16733static int mallocWithAlarm(int n, void **pp){
16734  int nFull;
16735  void *p;
16736  assert( sqlite3_mutex_held(mem0.mutex) );
16737  nFull = sqlite3GlobalConfig.m.xRoundup(n);
16738  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16739  if( mem0.alarmCallback!=0 ){
16740    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16741    if( nUsed+nFull >= mem0.alarmThreshold ){
16742      sqlite3MallocAlarm(nFull);
16743    }
16744  }
16745  p = sqlite3GlobalConfig.m.xMalloc(nFull);
16746  if( p==0 && mem0.alarmCallback ){
16747    sqlite3MallocAlarm(nFull);
16748    p = sqlite3GlobalConfig.m.xMalloc(nFull);
16749  }
16750  if( p ){
16751    nFull = sqlite3MallocSize(p);
16752    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16753  }
16754  *pp = p;
16755  return nFull;
16756}
16757
16758/*
16759** Allocate memory.  This routine is like sqlite3_malloc() except that it
16760** assumes the memory subsystem has already been initialized.
16761*/
16762SQLITE_PRIVATE void *sqlite3Malloc(int n){
16763  void *p;
16764  if( n<=0 || n>=0x7fffff00 ){
16765    /* A memory allocation of a number of bytes which is near the maximum
16766    ** signed integer value might cause an integer overflow inside of the
16767    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
16768    ** 255 bytes of overhead.  SQLite itself will never use anything near
16769    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
16770    p = 0;
16771  }else if( sqlite3GlobalConfig.bMemstat ){
16772    sqlite3_mutex_enter(mem0.mutex);
16773    mallocWithAlarm(n, &p);
16774    sqlite3_mutex_leave(mem0.mutex);
16775  }else{
16776    p = sqlite3GlobalConfig.m.xMalloc(n);
16777  }
16778  return p;
16779}
16780
16781/*
16782** This version of the memory allocation is for use by the application.
16783** First make sure the memory subsystem is initialized, then do the
16784** allocation.
16785*/
16786SQLITE_API void *sqlite3_malloc(int n){
16787#ifndef SQLITE_OMIT_AUTOINIT
16788  if( sqlite3_initialize() ) return 0;
16789#endif
16790  return sqlite3Malloc(n);
16791}
16792
16793/*
16794** Each thread may only have a single outstanding allocation from
16795** xScratchMalloc().  We verify this constraint in the single-threaded
16796** case by setting scratchAllocOut to 1 when an allocation
16797** is outstanding clearing it when the allocation is freed.
16798*/
16799#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16800static int scratchAllocOut = 0;
16801#endif
16802
16803
16804/*
16805** Allocate memory that is to be used and released right away.
16806** This routine is similar to alloca() in that it is not intended
16807** for situations where the memory might be held long-term.  This
16808** routine is intended to get memory to old large transient data
16809** structures that would not normally fit on the stack of an
16810** embedded processor.
16811*/
16812SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16813  void *p;
16814  assert( n>0 );
16815
16816#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16817  /* Verify that no more than two scratch allocation per thread
16818  ** is outstanding at one time.  (This is only checked in the
16819  ** single-threaded case since checking in the multi-threaded case
16820  ** would be much more complicated.) */
16821  assert( scratchAllocOut<=1 );
16822#endif
16823
16824  if( sqlite3GlobalConfig.szScratch<n ){
16825    goto scratch_overflow;
16826  }else{
16827    sqlite3_mutex_enter(mem0.mutex);
16828    if( mem0.nScratchFree==0 ){
16829      sqlite3_mutex_leave(mem0.mutex);
16830      goto scratch_overflow;
16831    }else{
16832      int i;
16833      i = mem0.aScratchFree[--mem0.nScratchFree];
16834      i *= sqlite3GlobalConfig.szScratch;
16835      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16836      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16837      sqlite3_mutex_leave(mem0.mutex);
16838      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16839      assert(  (((u8*)p - (u8*)0) & 7)==0 );
16840    }
16841  }
16842#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16843  scratchAllocOut = p!=0;
16844#endif
16845
16846  return p;
16847
16848scratch_overflow:
16849  if( sqlite3GlobalConfig.bMemstat ){
16850    sqlite3_mutex_enter(mem0.mutex);
16851    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16852    n = mallocWithAlarm(n, &p);
16853    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16854    sqlite3_mutex_leave(mem0.mutex);
16855  }else{
16856    p = sqlite3GlobalConfig.m.xMalloc(n);
16857  }
16858  sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
16859#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16860  scratchAllocOut = p!=0;
16861#endif
16862  return p;
16863}
16864SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16865  if( p ){
16866    if( sqlite3GlobalConfig.pScratch==0
16867           || p<sqlite3GlobalConfig.pScratch
16868           || p>=(void*)mem0.aScratchFree ){
16869      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
16870      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16871      if( sqlite3GlobalConfig.bMemstat ){
16872        int iSize = sqlite3MallocSize(p);
16873        sqlite3_mutex_enter(mem0.mutex);
16874        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16875        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16876        sqlite3GlobalConfig.m.xFree(p);
16877        sqlite3_mutex_leave(mem0.mutex);
16878      }else{
16879        sqlite3GlobalConfig.m.xFree(p);
16880      }
16881    }else{
16882      int i;
16883      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16884      i /= sqlite3GlobalConfig.szScratch;
16885      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16886      sqlite3_mutex_enter(mem0.mutex);
16887      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16888      mem0.aScratchFree[mem0.nScratchFree++] = i;
16889      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16890      sqlite3_mutex_leave(mem0.mutex);
16891
16892#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16893    /* Verify that no more than two scratch allocation per thread
16894    ** is outstanding at one time.  (This is only checked in the
16895    ** single-threaded case since checking in the multi-threaded case
16896    ** would be much more complicated.) */
16897    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
16898    scratchAllocOut = 0;
16899#endif
16900
16901    }
16902  }
16903}
16904
16905/*
16906** TRUE if p is a lookaside memory allocation from db
16907*/
16908#ifndef SQLITE_OMIT_LOOKASIDE
16909static int isLookaside(sqlite3 *db, void *p){
16910  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16911}
16912#else
16913#define isLookaside(A,B) 0
16914#endif
16915
16916/*
16917** Return the size of a memory allocation previously obtained from
16918** sqlite3Malloc() or sqlite3_malloc().
16919*/
16920SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16921  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16922  return sqlite3GlobalConfig.m.xSize(p);
16923}
16924SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16925  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16926  if( isLookaside(db, p) ){
16927    return db->lookaside.sz;
16928  }else{
16929    assert( sqlite3MemdebugHasType(p,
16930             db ? (MEMTYPE_DB|MEMTYPE_HEAP) : MEMTYPE_HEAP) );
16931    return sqlite3GlobalConfig.m.xSize(p);
16932  }
16933}
16934
16935/*
16936** Free memory previously obtained from sqlite3Malloc().
16937*/
16938SQLITE_API void sqlite3_free(void *p){
16939  if( p==0 ) return;
16940  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16941  if( sqlite3GlobalConfig.bMemstat ){
16942    sqlite3_mutex_enter(mem0.mutex);
16943    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16944    sqlite3GlobalConfig.m.xFree(p);
16945    sqlite3_mutex_leave(mem0.mutex);
16946  }else{
16947    sqlite3GlobalConfig.m.xFree(p);
16948  }
16949}
16950
16951/*
16952** Free memory that might be associated with a particular database
16953** connection.
16954*/
16955SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16956  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16957  if( isLookaside(db, p) ){
16958    LookasideSlot *pBuf = (LookasideSlot*)p;
16959    pBuf->pNext = db->lookaside.pFree;
16960    db->lookaside.pFree = pBuf;
16961    db->lookaside.nOut--;
16962  }else{
16963    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
16964    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16965    sqlite3_free(p);
16966  }
16967}
16968
16969/*
16970** Change the size of an existing memory allocation
16971*/
16972SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16973  int nOld, nNew;
16974  void *pNew;
16975  if( pOld==0 ){
16976    return sqlite3Malloc(nBytes);
16977  }
16978  if( nBytes<=0 ){
16979    sqlite3_free(pOld);
16980    return 0;
16981  }
16982  if( nBytes>=0x7fffff00 ){
16983    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16984    return 0;
16985  }
16986  nOld = sqlite3MallocSize(pOld);
16987  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16988  if( nOld==nNew ){
16989    pNew = pOld;
16990  }else if( sqlite3GlobalConfig.bMemstat ){
16991    sqlite3_mutex_enter(mem0.mutex);
16992    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16993    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
16994          mem0.alarmThreshold ){
16995      sqlite3MallocAlarm(nNew-nOld);
16996    }
16997    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
16998    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16999    if( pNew==0 && mem0.alarmCallback ){
17000      sqlite3MallocAlarm(nBytes);
17001      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17002    }
17003    if( pNew ){
17004      nNew = sqlite3MallocSize(pNew);
17005      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17006    }
17007    sqlite3_mutex_leave(mem0.mutex);
17008  }else{
17009    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17010  }
17011  return pNew;
17012}
17013
17014/*
17015** The public interface to sqlite3Realloc.  Make sure that the memory
17016** subsystem is initialized prior to invoking sqliteRealloc.
17017*/
17018SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17019#ifndef SQLITE_OMIT_AUTOINIT
17020  if( sqlite3_initialize() ) return 0;
17021#endif
17022  return sqlite3Realloc(pOld, n);
17023}
17024
17025
17026/*
17027** Allocate and zero memory.
17028*/
17029SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17030  void *p = sqlite3Malloc(n);
17031  if( p ){
17032    memset(p, 0, n);
17033  }
17034  return p;
17035}
17036
17037/*
17038** Allocate and zero memory.  If the allocation fails, make
17039** the mallocFailed flag in the connection pointer.
17040*/
17041SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17042  void *p = sqlite3DbMallocRaw(db, n);
17043  if( p ){
17044    memset(p, 0, n);
17045  }
17046  return p;
17047}
17048
17049/*
17050** Allocate and zero memory.  If the allocation fails, make
17051** the mallocFailed flag in the connection pointer.
17052**
17053** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17054** failure on the same database connection) then always return 0.
17055** Hence for a particular database connection, once malloc starts
17056** failing, it fails consistently until mallocFailed is reset.
17057** This is an important assumption.  There are many places in the
17058** code that do things like this:
17059**
17060**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17061**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17062**         if( b ) a[10] = 9;
17063**
17064** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17065** that all prior mallocs (ex: "a") worked too.
17066*/
17067SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17068  void *p;
17069  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17070#ifndef SQLITE_OMIT_LOOKASIDE
17071  if( db ){
17072    LookasideSlot *pBuf;
17073    if( db->mallocFailed ){
17074      return 0;
17075    }
17076    if( db->lookaside.bEnabled && n<=db->lookaside.sz
17077         && (pBuf = db->lookaside.pFree)!=0 ){
17078      db->lookaside.pFree = pBuf->pNext;
17079      db->lookaside.nOut++;
17080      if( db->lookaside.nOut>db->lookaside.mxOut ){
17081        db->lookaside.mxOut = db->lookaside.nOut;
17082      }
17083      return (void*)pBuf;
17084    }
17085  }
17086#else
17087  if( db && db->mallocFailed ){
17088    return 0;
17089  }
17090#endif
17091  p = sqlite3Malloc(n);
17092  if( !p && db ){
17093    db->mallocFailed = 1;
17094  }
17095  sqlite3MemdebugSetType(p,
17096            (db && db->lookaside.bEnabled) ? MEMTYPE_DB : MEMTYPE_HEAP);
17097  return p;
17098}
17099
17100/*
17101** Resize the block of memory pointed to by p to n bytes. If the
17102** resize fails, set the mallocFailed flag in the connection object.
17103*/
17104SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
17105  void *pNew = 0;
17106  assert( db!=0 );
17107  assert( sqlite3_mutex_held(db->mutex) );
17108  if( db->mallocFailed==0 ){
17109    if( p==0 ){
17110      return sqlite3DbMallocRaw(db, n);
17111    }
17112    if( isLookaside(db, p) ){
17113      if( n<=db->lookaside.sz ){
17114        return p;
17115      }
17116      pNew = sqlite3DbMallocRaw(db, n);
17117      if( pNew ){
17118        memcpy(pNew, p, db->lookaside.sz);
17119        sqlite3DbFree(db, p);
17120      }
17121    }else{
17122      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
17123      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17124      pNew = sqlite3_realloc(p, n);
17125      if( !pNew ){
17126        db->mallocFailed = 1;
17127      }
17128      sqlite3MemdebugSetType(pNew,
17129            db->lookaside.bEnabled ? MEMTYPE_DB : MEMTYPE_HEAP);
17130    }
17131  }
17132  return pNew;
17133}
17134
17135/*
17136** Attempt to reallocate p.  If the reallocation fails, then free p
17137** and set the mallocFailed flag in the database connection.
17138*/
17139SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
17140  void *pNew;
17141  pNew = sqlite3DbRealloc(db, p, n);
17142  if( !pNew ){
17143    sqlite3DbFree(db, p);
17144  }
17145  return pNew;
17146}
17147
17148/*
17149** Make a copy of a string in memory obtained from sqliteMalloc(). These
17150** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
17151** is because when memory debugging is turned on, these two functions are
17152** called via macros that record the current file and line number in the
17153** ThreadData structure.
17154*/
17155SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
17156  char *zNew;
17157  size_t n;
17158  if( z==0 ){
17159    return 0;
17160  }
17161  n = sqlite3Strlen30(z) + 1;
17162  assert( (n&0x7fffffff)==n );
17163  zNew = sqlite3DbMallocRaw(db, (int)n);
17164  if( zNew ){
17165    memcpy(zNew, z, n);
17166  }
17167  return zNew;
17168}
17169SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17170  char *zNew;
17171  if( z==0 ){
17172    return 0;
17173  }
17174  assert( (n&0x7fffffff)==n );
17175  zNew = sqlite3DbMallocRaw(db, n+1);
17176  if( zNew ){
17177    memcpy(zNew, z, n);
17178    zNew[n] = 0;
17179  }
17180  return zNew;
17181}
17182
17183/*
17184** Create a string from the zFromat argument and the va_list that follows.
17185** Store the string in memory obtained from sqliteMalloc() and make *pz
17186** point to that string.
17187*/
17188SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17189  va_list ap;
17190  char *z;
17191
17192  va_start(ap, zFormat);
17193  z = sqlite3VMPrintf(db, zFormat, ap);
17194  va_end(ap);
17195  sqlite3DbFree(db, *pz);
17196  *pz = z;
17197}
17198
17199
17200/*
17201** This function must be called before exiting any API function (i.e.
17202** returning control to the user) that has called sqlite3_malloc or
17203** sqlite3_realloc.
17204**
17205** The returned value is normally a copy of the second argument to this
17206** function. However, if a malloc() failure has occurred since the previous
17207** invocation SQLITE_NOMEM is returned instead.
17208**
17209** If the first argument, db, is not NULL and a malloc() error has occurred,
17210** then the connection error-code (the value returned by sqlite3_errcode())
17211** is set to SQLITE_NOMEM.
17212*/
17213SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17214  /* If the db handle is not NULL, then we must hold the connection handle
17215  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
17216  ** is unsafe, as is the call to sqlite3Error().
17217  */
17218  assert( !db || sqlite3_mutex_held(db->mutex) );
17219  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17220    sqlite3Error(db, SQLITE_NOMEM, 0);
17221    db->mallocFailed = 0;
17222    rc = SQLITE_NOMEM;
17223  }
17224  return rc & (db ? db->errMask : 0xff);
17225}
17226
17227/************** End of malloc.c **********************************************/
17228/************** Begin file printf.c ******************************************/
17229/*
17230** The "printf" code that follows dates from the 1980's.  It is in
17231** the public domain.  The original comments are included here for
17232** completeness.  They are very out-of-date but might be useful as
17233** an historical reference.  Most of the "enhancements" have been backed
17234** out so that the functionality is now the same as standard printf().
17235**
17236**************************************************************************
17237**
17238** The following modules is an enhanced replacement for the "printf" subroutines
17239** found in the standard C library.  The following enhancements are
17240** supported:
17241**
17242**      +  Additional functions.  The standard set of "printf" functions
17243**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17244**         vsprintf.  This module adds the following:
17245**
17246**           *  snprintf -- Works like sprintf, but has an extra argument
17247**                          which is the size of the buffer written to.
17248**
17249**           *  mprintf --  Similar to sprintf.  Writes output to memory
17250**                          obtained from malloc.
17251**
17252**           *  xprintf --  Calls a function to dispose of output.
17253**
17254**           *  nprintf --  No output, but returns the number of characters
17255**                          that would have been output by printf.
17256**
17257**           *  A v- version (ex: vsnprintf) of every function is also
17258**              supplied.
17259**
17260**      +  A few extensions to the formatting notation are supported:
17261**
17262**           *  The "=" flag (similar to "-") causes the output to be
17263**              be centered in the appropriately sized field.
17264**
17265**           *  The %b field outputs an integer in binary notation.
17266**
17267**           *  The %c field now accepts a precision.  The character output
17268**              is repeated by the number of times the precision specifies.
17269**
17270**           *  The %' field works like %c, but takes as its character the
17271**              next character of the format string, instead of the next
17272**              argument.  For example,  printf("%.78'-")  prints 78 minus
17273**              signs, the same as  printf("%.78c",'-').
17274**
17275**      +  When compiled using GCC on a SPARC, this version of printf is
17276**         faster than the library printf for SUN OS 4.1.
17277**
17278**      +  All functions are fully reentrant.
17279**
17280*/
17281
17282/*
17283** Conversion types fall into various categories as defined by the
17284** following enumeration.
17285*/
17286#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17287#define etFLOAT       2 /* Floating point.  %f */
17288#define etEXP         3 /* Exponentional notation. %e and %E */
17289#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17290#define etSIZE        5 /* Return number of characters processed so far. %n */
17291#define etSTRING      6 /* Strings. %s */
17292#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17293#define etPERCENT     8 /* Percent symbol. %% */
17294#define etCHARX       9 /* Characters. %c */
17295/* The rest are extensions, not normally found in printf() */
17296#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17297#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17298                          NULL pointers replaced by SQL NULL.  %Q */
17299#define etTOKEN      12 /* a pointer to a Token structure */
17300#define etSRCLIST    13 /* a pointer to a SrcList */
17301#define etPOINTER    14 /* The %p conversion */
17302#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17303#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17304
17305#define etINVALID     0 /* Any unrecognized conversion type */
17306
17307
17308/*
17309** An "etByte" is an 8-bit unsigned value.
17310*/
17311typedef unsigned char etByte;
17312
17313/*
17314** Each builtin conversion character (ex: the 'd' in "%d") is described
17315** by an instance of the following structure
17316*/
17317typedef struct et_info {   /* Information about each format field */
17318  char fmttype;            /* The format field code letter */
17319  etByte base;             /* The base for radix conversion */
17320  etByte flags;            /* One or more of FLAG_ constants below */
17321  etByte type;             /* Conversion paradigm */
17322  etByte charset;          /* Offset into aDigits[] of the digits string */
17323  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17324} et_info;
17325
17326/*
17327** Allowed values for et_info.flags
17328*/
17329#define FLAG_SIGNED  1     /* True if the value to convert is signed */
17330#define FLAG_INTERN  2     /* True if for internal use only */
17331#define FLAG_STRING  4     /* Allow infinity precision */
17332
17333
17334/*
17335** The following table is searched linearly, so it is good to put the
17336** most frequently used conversion types first.
17337*/
17338static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17339static const char aPrefix[] = "-x0\000X0";
17340static const et_info fmtinfo[] = {
17341  {  'd', 10, 1, etRADIX,      0,  0 },
17342  {  's',  0, 4, etSTRING,     0,  0 },
17343  {  'g',  0, 1, etGENERIC,    30, 0 },
17344  {  'z',  0, 4, etDYNSTRING,  0,  0 },
17345  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17346  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17347  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17348  {  'c',  0, 0, etCHARX,      0,  0 },
17349  {  'o',  8, 0, etRADIX,      0,  2 },
17350  {  'u', 10, 0, etRADIX,      0,  0 },
17351  {  'x', 16, 0, etRADIX,      16, 1 },
17352  {  'X', 16, 0, etRADIX,      0,  4 },
17353#ifndef SQLITE_OMIT_FLOATING_POINT
17354  {  'f',  0, 1, etFLOAT,      0,  0 },
17355  {  'e',  0, 1, etEXP,        30, 0 },
17356  {  'E',  0, 1, etEXP,        14, 0 },
17357  {  'G',  0, 1, etGENERIC,    14, 0 },
17358#endif
17359  {  'i', 10, 1, etRADIX,      0,  0 },
17360  {  'n',  0, 0, etSIZE,       0,  0 },
17361  {  '%',  0, 0, etPERCENT,    0,  0 },
17362  {  'p', 16, 0, etPOINTER,    0,  1 },
17363
17364/* All the rest have the FLAG_INTERN bit set and are thus for internal
17365** use only */
17366  {  'T',  0, 2, etTOKEN,      0,  0 },
17367  {  'S',  0, 2, etSRCLIST,    0,  0 },
17368  {  'r', 10, 3, etORDINAL,    0,  0 },
17369};
17370
17371/*
17372** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17373** conversions will work.
17374*/
17375#ifndef SQLITE_OMIT_FLOATING_POINT
17376/*
17377** "*val" is a double such that 0.1 <= *val < 10.0
17378** Return the ascii code for the leading digit of *val, then
17379** multiply "*val" by 10.0 to renormalize.
17380**
17381** Example:
17382**     input:     *val = 3.14159
17383**     output:    *val = 1.4159    function return = '3'
17384**
17385** The counter *cnt is incremented each time.  After counter exceeds
17386** 16 (the number of significant digits in a 64-bit float) '0' is
17387** always returned.
17388*/
17389static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17390  int digit;
17391  LONGDOUBLE_TYPE d;
17392  if( (*cnt)++ >= 16 ) return '0';
17393  digit = (int)*val;
17394  d = digit;
17395  digit += '0';
17396  *val = (*val - d)*10.0;
17397  return (char)digit;
17398}
17399#endif /* SQLITE_OMIT_FLOATING_POINT */
17400
17401/*
17402** Append N space characters to the given string buffer.
17403*/
17404static void appendSpace(StrAccum *pAccum, int N){
17405  static const char zSpaces[] = "                             ";
17406  while( N>=(int)sizeof(zSpaces)-1 ){
17407    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
17408    N -= sizeof(zSpaces)-1;
17409  }
17410  if( N>0 ){
17411    sqlite3StrAccumAppend(pAccum, zSpaces, N);
17412  }
17413}
17414
17415/*
17416** On machines with a small stack size, you can redefine the
17417** SQLITE_PRINT_BUF_SIZE to be less than 350.
17418*/
17419#ifndef SQLITE_PRINT_BUF_SIZE
17420# if defined(SQLITE_SMALL_STACK)
17421#   define SQLITE_PRINT_BUF_SIZE 50
17422# else
17423#   define SQLITE_PRINT_BUF_SIZE 350
17424# endif
17425#endif
17426#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17427
17428/*
17429** The root program.  All variations call this core.
17430**
17431** INPUTS:
17432**   func   This is a pointer to a function taking three arguments
17433**            1. A pointer to anything.  Same as the "arg" parameter.
17434**            2. A pointer to the list of characters to be output
17435**               (Note, this list is NOT null terminated.)
17436**            3. An integer number of characters to be output.
17437**               (Note: This number might be zero.)
17438**
17439**   arg    This is the pointer to anything which will be passed as the
17440**          first argument to "func".  Use it for whatever you like.
17441**
17442**   fmt    This is the format string, as in the usual print.
17443**
17444**   ap     This is a pointer to a list of arguments.  Same as in
17445**          vfprint.
17446**
17447** OUTPUTS:
17448**          The return value is the total number of characters sent to
17449**          the function "func".  Returns -1 on a error.
17450**
17451** Note that the order in which automatic variables are declared below
17452** seems to make a big difference in determining how fast this beast
17453** will run.
17454*/
17455SQLITE_PRIVATE void sqlite3VXPrintf(
17456  StrAccum *pAccum,                  /* Accumulate results here */
17457  int useExtended,                   /* Allow extended %-conversions */
17458  const char *fmt,                   /* Format string */
17459  va_list ap                         /* arguments */
17460){
17461  int c;                     /* Next character in the format string */
17462  char *bufpt;               /* Pointer to the conversion buffer */
17463  int precision;             /* Precision of the current field */
17464  int length;                /* Length of the field */
17465  int idx;                   /* A general purpose loop counter */
17466  int width;                 /* Width of the current field */
17467  etByte flag_leftjustify;   /* True if "-" flag is present */
17468  etByte flag_plussign;      /* True if "+" flag is present */
17469  etByte flag_blanksign;     /* True if " " flag is present */
17470  etByte flag_alternateform; /* True if "#" flag is present */
17471  etByte flag_altform2;      /* True if "!" flag is present */
17472  etByte flag_zeropad;       /* True if field width constant starts with zero */
17473  etByte flag_long;          /* True if "l" flag is present */
17474  etByte flag_longlong;      /* True if the "ll" flag is present */
17475  etByte done;               /* Loop termination flag */
17476  sqlite_uint64 longvalue;   /* Value for integer types */
17477  LONGDOUBLE_TYPE realvalue; /* Value for real types */
17478  const et_info *infop;      /* Pointer to the appropriate info structure */
17479  char buf[etBUFSIZE];       /* Conversion buffer */
17480  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17481  etByte xtype = 0;          /* Conversion paradigm */
17482  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17483#ifndef SQLITE_OMIT_FLOATING_POINT
17484  int  exp, e2;              /* exponent of real numbers */
17485  double rounder;            /* Used for rounding floating point values */
17486  etByte flag_dp;            /* True if decimal point should be shown */
17487  etByte flag_rtz;           /* True if trailing zeros should be removed */
17488  etByte flag_exp;           /* True to force display of the exponent */
17489  int nsd;                   /* Number of significant digits returned */
17490#endif
17491
17492  length = 0;
17493  bufpt = 0;
17494  for(; (c=(*fmt))!=0; ++fmt){
17495    if( c!='%' ){
17496      int amt;
17497      bufpt = (char *)fmt;
17498      amt = 1;
17499      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17500      sqlite3StrAccumAppend(pAccum, bufpt, amt);
17501      if( c==0 ) break;
17502    }
17503    if( (c=(*++fmt))==0 ){
17504      sqlite3StrAccumAppend(pAccum, "%", 1);
17505      break;
17506    }
17507    /* Find out what flags are present */
17508    flag_leftjustify = flag_plussign = flag_blanksign =
17509     flag_alternateform = flag_altform2 = flag_zeropad = 0;
17510    done = 0;
17511    do{
17512      switch( c ){
17513        case '-':   flag_leftjustify = 1;     break;
17514        case '+':   flag_plussign = 1;        break;
17515        case ' ':   flag_blanksign = 1;       break;
17516        case '#':   flag_alternateform = 1;   break;
17517        case '!':   flag_altform2 = 1;        break;
17518        case '0':   flag_zeropad = 1;         break;
17519        default:    done = 1;                 break;
17520      }
17521    }while( !done && (c=(*++fmt))!=0 );
17522    /* Get the field width */
17523    width = 0;
17524    if( c=='*' ){
17525      width = va_arg(ap,int);
17526      if( width<0 ){
17527        flag_leftjustify = 1;
17528        width = -width;
17529      }
17530      c = *++fmt;
17531    }else{
17532      while( c>='0' && c<='9' ){
17533        width = width*10 + c - '0';
17534        c = *++fmt;
17535      }
17536    }
17537    if( width > etBUFSIZE-10 ){
17538      width = etBUFSIZE-10;
17539    }
17540    /* Get the precision */
17541    if( c=='.' ){
17542      precision = 0;
17543      c = *++fmt;
17544      if( c=='*' ){
17545        precision = va_arg(ap,int);
17546        if( precision<0 ) precision = -precision;
17547        c = *++fmt;
17548      }else{
17549        while( c>='0' && c<='9' ){
17550          precision = precision*10 + c - '0';
17551          c = *++fmt;
17552        }
17553      }
17554    }else{
17555      precision = -1;
17556    }
17557    /* Get the conversion type modifier */
17558    if( c=='l' ){
17559      flag_long = 1;
17560      c = *++fmt;
17561      if( c=='l' ){
17562        flag_longlong = 1;
17563        c = *++fmt;
17564      }else{
17565        flag_longlong = 0;
17566      }
17567    }else{
17568      flag_long = flag_longlong = 0;
17569    }
17570    /* Fetch the info entry for the field */
17571    infop = &fmtinfo[0];
17572    xtype = etINVALID;
17573    for(idx=0; idx<ArraySize(fmtinfo); idx++){
17574      if( c==fmtinfo[idx].fmttype ){
17575        infop = &fmtinfo[idx];
17576        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17577          xtype = infop->type;
17578        }else{
17579          return;
17580        }
17581        break;
17582      }
17583    }
17584    zExtra = 0;
17585
17586
17587    /* Limit the precision to prevent overflowing buf[] during conversion */
17588    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17589      precision = etBUFSIZE-40;
17590    }
17591
17592    /*
17593    ** At this point, variables are initialized as follows:
17594    **
17595    **   flag_alternateform          TRUE if a '#' is present.
17596    **   flag_altform2               TRUE if a '!' is present.
17597    **   flag_plussign               TRUE if a '+' is present.
17598    **   flag_leftjustify            TRUE if a '-' is present or if the
17599    **                               field width was negative.
17600    **   flag_zeropad                TRUE if the width began with 0.
17601    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17602    **                               the conversion character.
17603    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17604    **                               the conversion character.
17605    **   flag_blanksign              TRUE if a ' ' is present.
17606    **   width                       The specified field width.  This is
17607    **                               always non-negative.  Zero is the default.
17608    **   precision                   The specified precision.  The default
17609    **                               is -1.
17610    **   xtype                       The class of the conversion.
17611    **   infop                       Pointer to the appropriate info struct.
17612    */
17613    switch( xtype ){
17614      case etPOINTER:
17615        flag_longlong = sizeof(char*)==sizeof(i64);
17616        flag_long = sizeof(char*)==sizeof(long int);
17617        /* Fall through into the next case */
17618      case etORDINAL:
17619      case etRADIX:
17620        if( infop->flags & FLAG_SIGNED ){
17621          i64 v;
17622          if( flag_longlong ){
17623            v = va_arg(ap,i64);
17624          }else if( flag_long ){
17625            v = va_arg(ap,long int);
17626          }else{
17627            v = va_arg(ap,int);
17628          }
17629          if( v<0 ){
17630            longvalue = -v;
17631            prefix = '-';
17632          }else{
17633            longvalue = v;
17634            if( flag_plussign )        prefix = '+';
17635            else if( flag_blanksign )  prefix = ' ';
17636            else                       prefix = 0;
17637          }
17638        }else{
17639          if( flag_longlong ){
17640            longvalue = va_arg(ap,u64);
17641          }else if( flag_long ){
17642            longvalue = va_arg(ap,unsigned long int);
17643          }else{
17644            longvalue = va_arg(ap,unsigned int);
17645          }
17646          prefix = 0;
17647        }
17648        if( longvalue==0 ) flag_alternateform = 0;
17649        if( flag_zeropad && precision<width-(prefix!=0) ){
17650          precision = width-(prefix!=0);
17651        }
17652        bufpt = &buf[etBUFSIZE-1];
17653        if( xtype==etORDINAL ){
17654          static const char zOrd[] = "thstndrd";
17655          int x = (int)(longvalue % 10);
17656          if( x>=4 || (longvalue/10)%10==1 ){
17657            x = 0;
17658          }
17659          buf[etBUFSIZE-3] = zOrd[x*2];
17660          buf[etBUFSIZE-2] = zOrd[x*2+1];
17661          bufpt -= 2;
17662        }
17663        {
17664          register const char *cset;      /* Use registers for speed */
17665          register int base;
17666          cset = &aDigits[infop->charset];
17667          base = infop->base;
17668          do{                                           /* Convert to ascii */
17669            *(--bufpt) = cset[longvalue%base];
17670            longvalue = longvalue/base;
17671          }while( longvalue>0 );
17672        }
17673        length = (int)(&buf[etBUFSIZE-1]-bufpt);
17674        for(idx=precision-length; idx>0; idx--){
17675          *(--bufpt) = '0';                             /* Zero pad */
17676        }
17677        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17678        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17679          const char *pre;
17680          char x;
17681          pre = &aPrefix[infop->prefix];
17682          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17683        }
17684        length = (int)(&buf[etBUFSIZE-1]-bufpt);
17685        break;
17686      case etFLOAT:
17687      case etEXP:
17688      case etGENERIC:
17689        realvalue = va_arg(ap,double);
17690#ifdef SQLITE_OMIT_FLOATING_POINT
17691        length = 0;
17692#else
17693        if( precision<0 ) precision = 6;         /* Set default precision */
17694        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17695        if( realvalue<0.0 ){
17696          realvalue = -realvalue;
17697          prefix = '-';
17698        }else{
17699          if( flag_plussign )          prefix = '+';
17700          else if( flag_blanksign )    prefix = ' ';
17701          else                         prefix = 0;
17702        }
17703        if( xtype==etGENERIC && precision>0 ) precision--;
17704#if 0
17705        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17706        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17707#else
17708        /* It makes more sense to use 0.5 */
17709        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17710#endif
17711        if( xtype==etFLOAT ) realvalue += rounder;
17712        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17713        exp = 0;
17714        if( sqlite3IsNaN((double)realvalue) ){
17715          bufpt = "NaN";
17716          length = 3;
17717          break;
17718        }
17719        if( realvalue>0.0 ){
17720          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17721          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17722          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17723          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17724          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17725          if( exp>350 ){
17726            if( prefix=='-' ){
17727              bufpt = "-Inf";
17728            }else if( prefix=='+' ){
17729              bufpt = "+Inf";
17730            }else{
17731              bufpt = "Inf";
17732            }
17733            length = sqlite3Strlen30(bufpt);
17734            break;
17735          }
17736        }
17737        bufpt = buf;
17738        /*
17739        ** If the field type is etGENERIC, then convert to either etEXP
17740        ** or etFLOAT, as appropriate.
17741        */
17742        flag_exp = xtype==etEXP;
17743        if( xtype!=etFLOAT ){
17744          realvalue += rounder;
17745          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17746        }
17747        if( xtype==etGENERIC ){
17748          flag_rtz = !flag_alternateform;
17749          if( exp<-4 || exp>precision ){
17750            xtype = etEXP;
17751          }else{
17752            precision = precision - exp;
17753            xtype = etFLOAT;
17754          }
17755        }else{
17756          flag_rtz = 0;
17757        }
17758        if( xtype==etEXP ){
17759          e2 = 0;
17760        }else{
17761          e2 = exp;
17762        }
17763        nsd = 0;
17764        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17765        /* The sign in front of the number */
17766        if( prefix ){
17767          *(bufpt++) = prefix;
17768        }
17769        /* Digits prior to the decimal point */
17770        if( e2<0 ){
17771          *(bufpt++) = '0';
17772        }else{
17773          for(; e2>=0; e2--){
17774            *(bufpt++) = et_getdigit(&realvalue,&nsd);
17775          }
17776        }
17777        /* The decimal point */
17778        if( flag_dp ){
17779          *(bufpt++) = '.';
17780        }
17781        /* "0" digits after the decimal point but before the first
17782        ** significant digit of the number */
17783        for(e2++; e2<0; precision--, e2++){
17784          assert( precision>0 );
17785          *(bufpt++) = '0';
17786        }
17787        /* Significant digits after the decimal point */
17788        while( (precision--)>0 ){
17789          *(bufpt++) = et_getdigit(&realvalue,&nsd);
17790        }
17791        /* Remove trailing zeros and the "." if no digits follow the "." */
17792        if( flag_rtz && flag_dp ){
17793          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17794          assert( bufpt>buf );
17795          if( bufpt[-1]=='.' ){
17796            if( flag_altform2 ){
17797              *(bufpt++) = '0';
17798            }else{
17799              *(--bufpt) = 0;
17800            }
17801          }
17802        }
17803        /* Add the "eNNN" suffix */
17804        if( flag_exp || xtype==etEXP ){
17805          *(bufpt++) = aDigits[infop->charset];
17806          if( exp<0 ){
17807            *(bufpt++) = '-'; exp = -exp;
17808          }else{
17809            *(bufpt++) = '+';
17810          }
17811          if( exp>=100 ){
17812            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17813            exp %= 100;
17814          }
17815          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17816          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17817        }
17818        *bufpt = 0;
17819
17820        /* The converted number is in buf[] and zero terminated. Output it.
17821        ** Note that the number is in the usual order, not reversed as with
17822        ** integer conversions. */
17823        length = (int)(bufpt-buf);
17824        bufpt = buf;
17825
17826        /* Special case:  Add leading zeros if the flag_zeropad flag is
17827        ** set and we are not left justified */
17828        if( flag_zeropad && !flag_leftjustify && length < width){
17829          int i;
17830          int nPad = width - length;
17831          for(i=width; i>=nPad; i--){
17832            bufpt[i] = bufpt[i-nPad];
17833          }
17834          i = prefix!=0;
17835          while( nPad-- ) bufpt[i++] = '0';
17836          length = width;
17837        }
17838#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
17839        break;
17840      case etSIZE:
17841        *(va_arg(ap,int*)) = pAccum->nChar;
17842        length = width = 0;
17843        break;
17844      case etPERCENT:
17845        buf[0] = '%';
17846        bufpt = buf;
17847        length = 1;
17848        break;
17849      case etCHARX:
17850        c = va_arg(ap,int);
17851        buf[0] = (char)c;
17852        if( precision>=0 ){
17853          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17854          length = precision;
17855        }else{
17856          length =1;
17857        }
17858        bufpt = buf;
17859        break;
17860      case etSTRING:
17861      case etDYNSTRING:
17862        bufpt = va_arg(ap,char*);
17863        if( bufpt==0 ){
17864          bufpt = "";
17865        }else if( xtype==etDYNSTRING ){
17866          zExtra = bufpt;
17867        }
17868        if( precision>=0 ){
17869          for(length=0; length<precision && bufpt[length]; length++){}
17870        }else{
17871          length = sqlite3Strlen30(bufpt);
17872        }
17873        break;
17874      case etSQLESCAPE:
17875      case etSQLESCAPE2:
17876      case etSQLESCAPE3: {
17877        int i, j, k, n, isnull;
17878        int needQuote;
17879        char ch;
17880        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17881        char *escarg = va_arg(ap,char*);
17882        isnull = escarg==0;
17883        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17884        k = precision;
17885        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
17886          if( ch==q )  n++;
17887        }
17888        needQuote = !isnull && xtype==etSQLESCAPE2;
17889        n += i + 1 + needQuote*2;
17890        if( n>etBUFSIZE ){
17891          bufpt = zExtra = sqlite3Malloc( n );
17892          if( bufpt==0 ){
17893            pAccum->mallocFailed = 1;
17894            return;
17895          }
17896        }else{
17897          bufpt = buf;
17898        }
17899        j = 0;
17900        if( needQuote ) bufpt[j++] = q;
17901        k = i;
17902        for(i=0; i<k; i++){
17903          bufpt[j++] = ch = escarg[i];
17904          if( ch==q ) bufpt[j++] = ch;
17905        }
17906        if( needQuote ) bufpt[j++] = q;
17907        bufpt[j] = 0;
17908        length = j;
17909        /* The precision in %q and %Q means how many input characters to
17910        ** consume, not the length of the output...
17911        ** if( precision>=0 && precision<length ) length = precision; */
17912        break;
17913      }
17914      case etTOKEN: {
17915        Token *pToken = va_arg(ap, Token*);
17916        if( pToken ){
17917          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17918        }
17919        length = width = 0;
17920        break;
17921      }
17922      case etSRCLIST: {
17923        SrcList *pSrc = va_arg(ap, SrcList*);
17924        int k = va_arg(ap, int);
17925        struct SrcList_item *pItem = &pSrc->a[k];
17926        assert( k>=0 && k<pSrc->nSrc );
17927        if( pItem->zDatabase ){
17928          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17929          sqlite3StrAccumAppend(pAccum, ".", 1);
17930        }
17931        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17932        length = width = 0;
17933        break;
17934      }
17935      default: {
17936        assert( xtype==etINVALID );
17937        return;
17938      }
17939    }/* End switch over the format type */
17940    /*
17941    ** The text of the conversion is pointed to by "bufpt" and is
17942    ** "length" characters long.  The field width is "width".  Do
17943    ** the output.
17944    */
17945    if( !flag_leftjustify ){
17946      register int nspace;
17947      nspace = width-length;
17948      if( nspace>0 ){
17949        appendSpace(pAccum, nspace);
17950      }
17951    }
17952    if( length>0 ){
17953      sqlite3StrAccumAppend(pAccum, bufpt, length);
17954    }
17955    if( flag_leftjustify ){
17956      register int nspace;
17957      nspace = width-length;
17958      if( nspace>0 ){
17959        appendSpace(pAccum, nspace);
17960      }
17961    }
17962    if( zExtra ){
17963      sqlite3_free(zExtra);
17964    }
17965  }/* End for loop over the format string */
17966} /* End of function */
17967
17968/*
17969** Append N bytes of text from z to the StrAccum object.
17970*/
17971SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17972  assert( z!=0 || N==0 );
17973  if( p->tooBig | p->mallocFailed ){
17974    testcase(p->tooBig);
17975    testcase(p->mallocFailed);
17976    return;
17977  }
17978  if( N<0 ){
17979    N = sqlite3Strlen30(z);
17980  }
17981  if( N==0 || NEVER(z==0) ){
17982    return;
17983  }
17984  if( p->nChar+N >= p->nAlloc ){
17985    char *zNew;
17986    if( !p->useMalloc ){
17987      p->tooBig = 1;
17988      N = p->nAlloc - p->nChar - 1;
17989      if( N<=0 ){
17990        return;
17991      }
17992    }else{
17993      i64 szNew = p->nChar;
17994      szNew += N + 1;
17995      if( szNew > p->mxAlloc ){
17996        sqlite3StrAccumReset(p);
17997        p->tooBig = 1;
17998        return;
17999      }else{
18000        p->nAlloc = (int)szNew;
18001      }
18002      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18003      if( zNew ){
18004        memcpy(zNew, p->zText, p->nChar);
18005        sqlite3StrAccumReset(p);
18006        p->zText = zNew;
18007      }else{
18008        p->mallocFailed = 1;
18009        sqlite3StrAccumReset(p);
18010        return;
18011      }
18012    }
18013  }
18014  memcpy(&p->zText[p->nChar], z, N);
18015  p->nChar += N;
18016}
18017
18018/*
18019** Finish off a string by making sure it is zero-terminated.
18020** Return a pointer to the resulting string.  Return a NULL
18021** pointer if any kind of error was encountered.
18022*/
18023SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18024  if( p->zText ){
18025    p->zText[p->nChar] = 0;
18026    if( p->useMalloc && p->zText==p->zBase ){
18027      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18028      if( p->zText ){
18029        memcpy(p->zText, p->zBase, p->nChar+1);
18030      }else{
18031        p->mallocFailed = 1;
18032      }
18033    }
18034  }
18035  return p->zText;
18036}
18037
18038/*
18039** Reset an StrAccum string.  Reclaim all malloced memory.
18040*/
18041SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18042  if( p->zText!=p->zBase ){
18043    sqlite3DbFree(p->db, p->zText);
18044  }
18045  p->zText = 0;
18046}
18047
18048/*
18049** Initialize a string accumulator
18050*/
18051SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18052  p->zText = p->zBase = zBase;
18053  p->db = 0;
18054  p->nChar = 0;
18055  p->nAlloc = n;
18056  p->mxAlloc = mx;
18057  p->useMalloc = 1;
18058  p->tooBig = 0;
18059  p->mallocFailed = 0;
18060}
18061
18062/*
18063** Print into memory obtained from sqliteMalloc().  Use the internal
18064** %-conversion extensions.
18065*/
18066SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18067  char *z;
18068  char zBase[SQLITE_PRINT_BUF_SIZE];
18069  StrAccum acc;
18070  assert( db!=0 );
18071  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18072                      db->aLimit[SQLITE_LIMIT_LENGTH]);
18073  acc.db = db;
18074  sqlite3VXPrintf(&acc, 1, zFormat, ap);
18075  z = sqlite3StrAccumFinish(&acc);
18076  if( acc.mallocFailed ){
18077    db->mallocFailed = 1;
18078  }
18079  return z;
18080}
18081
18082/*
18083** Print into memory obtained from sqliteMalloc().  Use the internal
18084** %-conversion extensions.
18085*/
18086SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
18087  va_list ap;
18088  char *z;
18089  va_start(ap, zFormat);
18090  z = sqlite3VMPrintf(db, zFormat, ap);
18091  va_end(ap);
18092  return z;
18093}
18094
18095/*
18096** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
18097** the string and before returnning.  This routine is intended to be used
18098** to modify an existing string.  For example:
18099**
18100**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
18101**
18102*/
18103SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
18104  va_list ap;
18105  char *z;
18106  va_start(ap, zFormat);
18107  z = sqlite3VMPrintf(db, zFormat, ap);
18108  va_end(ap);
18109  sqlite3DbFree(db, zStr);
18110  return z;
18111}
18112
18113/*
18114** Print into memory obtained from sqlite3_malloc().  Omit the internal
18115** %-conversion extensions.
18116*/
18117SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
18118  char *z;
18119  char zBase[SQLITE_PRINT_BUF_SIZE];
18120  StrAccum acc;
18121#ifndef SQLITE_OMIT_AUTOINIT
18122  if( sqlite3_initialize() ) return 0;
18123#endif
18124  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
18125  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18126  z = sqlite3StrAccumFinish(&acc);
18127  return z;
18128}
18129
18130/*
18131** Print into memory obtained from sqlite3_malloc()().  Omit the internal
18132** %-conversion extensions.
18133*/
18134SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
18135  va_list ap;
18136  char *z;
18137#ifndef SQLITE_OMIT_AUTOINIT
18138  if( sqlite3_initialize() ) return 0;
18139#endif
18140  va_start(ap, zFormat);
18141  z = sqlite3_vmprintf(zFormat, ap);
18142  va_end(ap);
18143  return z;
18144}
18145
18146/*
18147** sqlite3_snprintf() works like snprintf() except that it ignores the
18148** current locale settings.  This is important for SQLite because we
18149** are not able to use a "," as the decimal point in place of "." as
18150** specified by some locales.
18151*/
18152SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
18153  char *z;
18154  va_list ap;
18155  StrAccum acc;
18156
18157  if( n<=0 ){
18158    return zBuf;
18159  }
18160  sqlite3StrAccumInit(&acc, zBuf, n, 0);
18161  acc.useMalloc = 0;
18162  va_start(ap,zFormat);
18163  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18164  va_end(ap);
18165  z = sqlite3StrAccumFinish(&acc);
18166  return z;
18167}
18168
18169/*
18170** This is the routine that actually formats the sqlite3_log() message.
18171** We house it in a separate routine from sqlite3_log() to avoid using
18172** stack space on small-stack systems when logging is disabled.
18173**
18174** sqlite3_log() must render into a static buffer.  It cannot dynamically
18175** allocate memory because it might be called while the memory allocator
18176** mutex is held.
18177*/
18178static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
18179  StrAccum acc;                          /* String accumulator */
18180  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
18181
18182  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
18183  acc.useMalloc = 0;
18184  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18185  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
18186                           sqlite3StrAccumFinish(&acc));
18187}
18188
18189/*
18190** Format and write a message to the log if logging is enabled.
18191*/
18192SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
18193  va_list ap;                             /* Vararg list */
18194  if( sqlite3GlobalConfig.xLog ){
18195    va_start(ap, zFormat);
18196    renderLogMsg(iErrCode, zFormat, ap);
18197    va_end(ap);
18198  }
18199}
18200
18201#if defined(SQLITE_DEBUG)
18202/*
18203** A version of printf() that understands %lld.  Used for debugging.
18204** The printf() built into some versions of windows does not understand %lld
18205** and segfaults if you give it a long long int.
18206*/
18207SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
18208  va_list ap;
18209  StrAccum acc;
18210  char zBuf[500];
18211  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
18212  acc.useMalloc = 0;
18213  va_start(ap,zFormat);
18214  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18215  va_end(ap);
18216  sqlite3StrAccumFinish(&acc);
18217  fprintf(stdout,"%s", zBuf);
18218  fflush(stdout);
18219}
18220#endif
18221
18222#ifndef SQLITE_OMIT_TRACE
18223/*
18224** variable-argument wrapper around sqlite3VXPrintf().
18225*/
18226SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
18227  va_list ap;
18228  va_start(ap,zFormat);
18229  sqlite3VXPrintf(p, 1, zFormat, ap);
18230  va_end(ap);
18231}
18232#endif
18233
18234/************** End of printf.c **********************************************/
18235/************** Begin file random.c ******************************************/
18236/*
18237** 2001 September 15
18238**
18239** The author disclaims copyright to this source code.  In place of
18240** a legal notice, here is a blessing:
18241**
18242**    May you do good and not evil.
18243**    May you find forgiveness for yourself and forgive others.
18244**    May you share freely, never taking more than you give.
18245**
18246*************************************************************************
18247** This file contains code to implement a pseudo-random number
18248** generator (PRNG) for SQLite.
18249**
18250** Random numbers are used by some of the database backends in order
18251** to generate random integer keys for tables or random filenames.
18252*/
18253
18254
18255/* All threads share a single random number generator.
18256** This structure is the current state of the generator.
18257*/
18258static SQLITE_WSD struct sqlite3PrngType {
18259  unsigned char isInit;          /* True if initialized */
18260  unsigned char i, j;            /* State variables */
18261  unsigned char s[256];          /* State variables */
18262} sqlite3Prng;
18263
18264/*
18265** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18266** must be held while executing this routine.
18267**
18268** Why not just use a library random generator like lrand48() for this?
18269** Because the OP_NewRowid opcode in the VDBE depends on having a very
18270** good source of random numbers.  The lrand48() library function may
18271** well be good enough.  But maybe not.  Or maybe lrand48() has some
18272** subtle problems on some systems that could cause problems.  It is hard
18273** to know.  To minimize the risk of problems due to bad lrand48()
18274** implementations, SQLite uses this random number generator based
18275** on RC4, which we know works very well.
18276**
18277** (Later):  Actually, OP_NewRowid does not depend on a good source of
18278** randomness any more.  But we will leave this code in all the same.
18279*/
18280static u8 randomByte(void){
18281  unsigned char t;
18282
18283
18284  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18285  ** state vector.  If writable static data is unsupported on the target,
18286  ** we have to locate the state vector at run-time.  In the more common
18287  ** case where writable static data is supported, wsdPrng can refer directly
18288  ** to the "sqlite3Prng" state vector declared above.
18289  */
18290#ifdef SQLITE_OMIT_WSD
18291  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18292# define wsdPrng p[0]
18293#else
18294# define wsdPrng sqlite3Prng
18295#endif
18296
18297
18298  /* Initialize the state of the random number generator once,
18299  ** the first time this routine is called.  The seed value does
18300  ** not need to contain a lot of randomness since we are not
18301  ** trying to do secure encryption or anything like that...
18302  **
18303  ** Nothing in this file or anywhere else in SQLite does any kind of
18304  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18305  ** number generator) not as an encryption device.
18306  */
18307  if( !wsdPrng.isInit ){
18308    int i;
18309    char k[256];
18310    wsdPrng.j = 0;
18311    wsdPrng.i = 0;
18312    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18313    for(i=0; i<256; i++){
18314      wsdPrng.s[i] = (u8)i;
18315    }
18316    for(i=0; i<256; i++){
18317      wsdPrng.j += wsdPrng.s[i] + k[i];
18318      t = wsdPrng.s[wsdPrng.j];
18319      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18320      wsdPrng.s[i] = t;
18321    }
18322    wsdPrng.isInit = 1;
18323  }
18324
18325  /* Generate and return single random byte
18326  */
18327  wsdPrng.i++;
18328  t = wsdPrng.s[wsdPrng.i];
18329  wsdPrng.j += t;
18330  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18331  wsdPrng.s[wsdPrng.j] = t;
18332  t += wsdPrng.s[wsdPrng.i];
18333  return wsdPrng.s[t];
18334}
18335
18336/*
18337** Return N random bytes.
18338*/
18339SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18340  unsigned char *zBuf = pBuf;
18341#if SQLITE_THREADSAFE
18342  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18343#endif
18344  sqlite3_mutex_enter(mutex);
18345  while( N-- ){
18346    *(zBuf++) = randomByte();
18347  }
18348  sqlite3_mutex_leave(mutex);
18349}
18350
18351#ifndef SQLITE_OMIT_BUILTIN_TEST
18352/*
18353** For testing purposes, we sometimes want to preserve the state of
18354** PRNG and restore the PRNG to its saved state at a later time, or
18355** to reset the PRNG to its initial state.  These routines accomplish
18356** those tasks.
18357**
18358** The sqlite3_test_control() interface calls these routines to
18359** control the PRNG.
18360*/
18361static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18362SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18363  memcpy(
18364    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18365    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18366    sizeof(sqlite3Prng)
18367  );
18368}
18369SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18370  memcpy(
18371    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18372    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18373    sizeof(sqlite3Prng)
18374  );
18375}
18376SQLITE_PRIVATE void sqlite3PrngResetState(void){
18377  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18378}
18379#endif /* SQLITE_OMIT_BUILTIN_TEST */
18380
18381/************** End of random.c **********************************************/
18382/************** Begin file utf.c *********************************************/
18383/*
18384** 2004 April 13
18385**
18386** The author disclaims copyright to this source code.  In place of
18387** a legal notice, here is a blessing:
18388**
18389**    May you do good and not evil.
18390**    May you find forgiveness for yourself and forgive others.
18391**    May you share freely, never taking more than you give.
18392**
18393*************************************************************************
18394** This file contains routines used to translate between UTF-8,
18395** UTF-16, UTF-16BE, and UTF-16LE.
18396**
18397** Notes on UTF-8:
18398**
18399**   Byte-0    Byte-1    Byte-2    Byte-3    Value
18400**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
18401**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
18402**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
18403**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
18404**
18405**
18406** Notes on UTF-16:  (with wwww+1==uuuuu)
18407**
18408**      Word-0               Word-1          Value
18409**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
18410**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
18411**
18412**
18413** BOM or Byte Order Mark:
18414**     0xff 0xfe   little-endian utf-16 follows
18415**     0xfe 0xff   big-endian utf-16 follows
18416**
18417*/
18418/************** Include vdbeInt.h in the middle of utf.c *********************/
18419/************** Begin file vdbeInt.h *****************************************/
18420/*
18421** 2003 September 6
18422**
18423** The author disclaims copyright to this source code.  In place of
18424** a legal notice, here is a blessing:
18425**
18426**    May you do good and not evil.
18427**    May you find forgiveness for yourself and forgive others.
18428**    May you share freely, never taking more than you give.
18429**
18430*************************************************************************
18431** This is the header file for information that is private to the
18432** VDBE.  This information used to all be at the top of the single
18433** source code file "vdbe.c".  When that file became too big (over
18434** 6000 lines long) it was split up into several smaller files and
18435** this header information was factored out.
18436*/
18437#ifndef _VDBEINT_H_
18438#define _VDBEINT_H_
18439
18440/*
18441** SQL is translated into a sequence of instructions to be
18442** executed by a virtual machine.  Each instruction is an instance
18443** of the following structure.
18444*/
18445typedef struct VdbeOp Op;
18446
18447/*
18448** Boolean values
18449*/
18450typedef unsigned char Bool;
18451
18452/*
18453** A cursor is a pointer into a single BTree within a database file.
18454** The cursor can seek to a BTree entry with a particular key, or
18455** loop over all entries of the Btree.  You can also insert new BTree
18456** entries or retrieve the key or data from the entry that the cursor
18457** is currently pointing to.
18458**
18459** Every cursor that the virtual machine has open is represented by an
18460** instance of the following structure.
18461**
18462** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
18463** really a single row that represents the NEW or OLD pseudo-table of
18464** a row trigger.  The data for the row is stored in VdbeCursor.pData and
18465** the rowid is in VdbeCursor.iKey.
18466*/
18467struct VdbeCursor {
18468  BtCursor *pCursor;    /* The cursor structure of the backend */
18469  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
18470  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
18471  Bool zeroed;          /* True if zeroed out and ready for reuse */
18472  Bool rowidIsValid;    /* True if lastRowid is valid */
18473  Bool atFirst;         /* True if pointing to first entry */
18474  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
18475  Bool nullRow;         /* True if pointing to a row with no data */
18476  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
18477  Bool isTable;         /* True if a table requiring integer keys */
18478  Bool isIndex;         /* True if an index containing keys only - no data */
18479  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
18480  Btree *pBt;           /* Separate file holding temporary table */
18481  int pseudoTableReg;   /* Register holding pseudotable content. */
18482  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
18483  int nField;           /* Number of fields in the header */
18484  i64 seqCount;         /* Sequence counter */
18485  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
18486  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
18487
18488  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
18489  ** OP_IsUnique opcode on this cursor. */
18490  int seekResult;
18491
18492  /* Cached information about the header for the data record that the
18493  ** cursor is currently pointing to.  Only valid if cacheStatus matches
18494  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18495  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
18496  ** the cache is out of date.
18497  **
18498  ** aRow might point to (ephemeral) data for the current row, or it might
18499  ** be NULL.
18500  */
18501  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
18502  int payloadSize;      /* Total number of bytes in the record */
18503  u32 *aType;           /* Type values for all entries in the record */
18504  u32 *aOffset;         /* Cached offsets to the start of each columns data */
18505  u8 *aRow;             /* Data for the current row, if all on one page */
18506};
18507typedef struct VdbeCursor VdbeCursor;
18508
18509/*
18510** When a sub-program is executed (OP_Program), a structure of this type
18511** is allocated to store the current value of the program counter, as
18512** well as the current memory cell array and various other frame specific
18513** values stored in the Vdbe struct. When the sub-program is finished,
18514** these values are copied back to the Vdbe from the VdbeFrame structure,
18515** restoring the state of the VM to as it was before the sub-program
18516** began executing.
18517**
18518** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
18519** is the parent of the current frame, or zero if the current frame
18520** is the main Vdbe program.
18521*/
18522typedef struct VdbeFrame VdbeFrame;
18523struct VdbeFrame {
18524  Vdbe *v;                /* VM this frame belongs to */
18525  int pc;                 /* Program Counter */
18526  Op *aOp;                /* Program instructions */
18527  int nOp;                /* Size of aOp array */
18528  Mem *aMem;              /* Array of memory cells */
18529  int nMem;               /* Number of entries in aMem */
18530  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
18531  u16 nCursor;            /* Number of entries in apCsr */
18532  void *token;            /* Copy of SubProgram.token */
18533  int nChildMem;          /* Number of memory cells for child frame */
18534  int nChildCsr;          /* Number of cursors for child frame */
18535  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18536  int nChange;            /* Statement changes (Vdbe.nChanges)     */
18537  VdbeFrame *pParent;     /* Parent of this frame */
18538};
18539
18540#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18541
18542/*
18543** A value for VdbeCursor.cacheValid that means the cache is always invalid.
18544*/
18545#define CACHE_STALE 0
18546
18547/*
18548** Internally, the vdbe manipulates nearly all SQL values as Mem
18549** structures. Each Mem struct may cache multiple representations (string,
18550** integer etc.) of the same value.  A value (and therefore Mem structure)
18551** has the following properties:
18552**
18553** Each value has a manifest type. The manifest type of the value stored
18554** in a Mem struct is returned by the MemType(Mem*) macro. The type is
18555** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
18556** SQLITE_BLOB.
18557*/
18558struct Mem {
18559  union {
18560    i64 i;              /* Integer value. */
18561    int nZero;          /* Used when bit MEM_Zero is set in flags */
18562    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18563    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18564    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18565  } u;
18566  double r;           /* Real value */
18567  sqlite3 *db;        /* The associated database connection */
18568  char *z;            /* String or BLOB value */
18569  int n;              /* Number of characters in string value, excluding '\0' */
18570  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18571  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18572  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18573  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18574  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18575};
18576
18577/* One or more of the following flags are set to indicate the validOK
18578** representations of the value stored in the Mem struct.
18579**
18580** If the MEM_Null flag is set, then the value is an SQL NULL value.
18581** No other flags may be set in this case.
18582**
18583** If the MEM_Str flag is set then Mem.z points at a string representation.
18584** Usually this is encoded in the same unicode encoding as the main
18585** database (see below for exceptions). If the MEM_Term flag is also
18586** set, then the string is nul terminated. The MEM_Int and MEM_Real
18587** flags may coexist with the MEM_Str flag.
18588**
18589** Multiple of these values can appear in Mem.flags.  But only one
18590** at a time can appear in Mem.type.
18591*/
18592#define MEM_Null      0x0001   /* Value is NULL */
18593#define MEM_Str       0x0002   /* Value is a string */
18594#define MEM_Int       0x0004   /* Value is an integer */
18595#define MEM_Real      0x0008   /* Value is a real number */
18596#define MEM_Blob      0x0010   /* Value is a BLOB */
18597#define MEM_RowSet    0x0020   /* Value is a RowSet object */
18598#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18599#define MEM_TypeMask  0x00ff   /* Mask of type bits */
18600
18601/* Whenever Mem contains a valid string or blob representation, one of
18602** the following flags must be set to determine the memory management
18603** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18604** string is \000 or \u0000 terminated
18605*/
18606#define MEM_Term      0x0200   /* String rep is nul terminated */
18607#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
18608#define MEM_Static    0x0800   /* Mem.z points to a static string */
18609#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18610#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18611#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18612
18613#ifdef SQLITE_OMIT_INCRBLOB
18614  #undef MEM_Zero
18615  #define MEM_Zero 0x0000
18616#endif
18617
18618
18619/*
18620** Clear any existing type flags from a Mem and replace them with f
18621*/
18622#define MemSetTypeFlag(p, f) \
18623   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18624
18625
18626/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18627** additional information about auxiliary information bound to arguments
18628** of the function.  This is used to implement the sqlite3_get_auxdata()
18629** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18630** that can be associated with a constant argument to a function.  This
18631** allows functions such as "regexp" to compile their constant regular
18632** expression argument once and reused the compiled code for multiple
18633** invocations.
18634*/
18635struct VdbeFunc {
18636  FuncDef *pFunc;               /* The definition of the function */
18637  int nAux;                     /* Number of entries allocated for apAux[] */
18638  struct AuxData {
18639    void *pAux;                   /* Aux data for the i-th argument */
18640    void (*xDelete)(void *);      /* Destructor for the aux data */
18641  } apAux[1];                   /* One slot for each function argument */
18642};
18643
18644/*
18645** The "context" argument for a installable function.  A pointer to an
18646** instance of this structure is the first argument to the routines used
18647** implement the SQL functions.
18648**
18649** There is a typedef for this structure in sqlite.h.  So all routines,
18650** even the public interface to SQLite, can use a pointer to this structure.
18651** But this file is the only place where the internal details of this
18652** structure are known.
18653**
18654** This structure is defined inside of vdbeInt.h because it uses substructures
18655** (Mem) which are only defined there.
18656*/
18657struct sqlite3_context {
18658  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18659  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18660  Mem s;                /* The return value is stored here */
18661  Mem *pMem;            /* Memory cell used to store aggregate context */
18662  int isError;          /* Error code returned by the function. */
18663  CollSeq *pColl;       /* Collating sequence */
18664};
18665
18666/*
18667** A Set structure is used for quick testing to see if a value
18668** is part of a small set.  Sets are used to implement code like
18669** this:
18670**            x.y IN ('hi','hoo','hum')
18671*/
18672typedef struct Set Set;
18673struct Set {
18674  Hash hash;             /* A set is just a hash table */
18675  HashElem *prev;        /* Previously accessed hash elemen */
18676};
18677
18678/*
18679** An instance of the virtual machine.  This structure contains the complete
18680** state of the virtual machine.
18681**
18682** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18683** is really a pointer to an instance of this structure.
18684**
18685** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18686** any virtual table method invocations made by the vdbe program. It is
18687** set to 2 for xDestroy method calls and 1 for all other methods. This
18688** variable is used for two purposes: to allow xDestroy methods to execute
18689** "DROP TABLE" statements and to prevent some nasty side effects of
18690** malloc failure when SQLite is invoked recursively by a virtual table
18691** method function.
18692*/
18693struct Vdbe {
18694  sqlite3 *db;            /* The database connection that owns this statement */
18695  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18696  int nOp;                /* Number of instructions in the program */
18697  int nOpAlloc;           /* Number of slots allocated for aOp[] */
18698  Op *aOp;                /* Space to hold the virtual machine's program */
18699  int nLabel;             /* Number of labels used */
18700  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
18701  int *aLabel;            /* Space to hold the labels */
18702  Mem **apArg;            /* Arguments to currently executing user function */
18703  Mem *aColName;          /* Column names to return */
18704  Mem *pResultSet;        /* Pointer to an array of results */
18705  u16 nResColumn;         /* Number of columns in one row of the result set */
18706  u16 nCursor;            /* Number of slots in apCsr[] */
18707  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18708  u8 errorAction;         /* Recovery action to do in case of an error */
18709  u8 okVar;               /* True if azVar[] has been initialized */
18710  ynVar nVar;             /* Number of entries in aVar[] */
18711  Mem *aVar;              /* Values for the OP_Variable opcode. */
18712  char **azVar;           /* Name of variables */
18713  u32 magic;              /* Magic number for sanity checking */
18714  int nMem;               /* Number of memory locations currently allocated */
18715  Mem *aMem;              /* The memory locations */
18716  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18717  int pc;                 /* The program counter */
18718  int rc;                 /* Value to return */
18719  char *zErrMsg;          /* Error message written here */
18720  u8 explain;             /* True if EXPLAIN present on SQL command */
18721  u8 changeCntOn;         /* True to update the change-counter */
18722  u8 expired;             /* True if the VM needs to be recompiled */
18723  u8 runOnlyOnce;         /* Automatically expire on reset */
18724  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18725  u8 inVtabMethod;        /* See comments above */
18726  u8 usesStmtJournal;     /* True if uses a statement journal */
18727  u8 readOnly;            /* True for read-only statements */
18728  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
18729  int nChange;            /* Number of db changes made since last reset */
18730  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18731  i64 startTime;          /* Time when query started - used for profiling */
18732  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18733  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
18734  char *zSql;             /* Text of the SQL statement that generated this */
18735  void *pFree;            /* Free this when deleting the vdbe */
18736  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18737  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18738  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18739#ifdef SQLITE_DEBUG
18740  FILE *trace;            /* Write an execution trace here, if not NULL */
18741#endif
18742  VdbeFrame *pFrame;      /* Parent frame */
18743  int nFrame;             /* Number of frames in pFrame list */
18744  u32 expmask;            /* Binding to these vars invalidates VM */
18745};
18746
18747/*
18748** The following are allowed values for Vdbe.magic
18749*/
18750#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18751#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18752#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18753#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18754
18755/*
18756** Function prototypes
18757*/
18758SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18759void sqliteVdbePopStack(Vdbe*,int);
18760SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18761#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18762SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18763#endif
18764SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18765SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18766SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18767SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18768SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18769
18770int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18771SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18772SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
18773SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18774SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18775SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18776SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18777SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18778SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18779SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18780SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18781SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18782SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18783SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18784SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18785#ifdef SQLITE_OMIT_FLOATING_POINT
18786# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18787#else
18788SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18789#endif
18790SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18791SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18792SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18793SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18794SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18795SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18796SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18797SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18798SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18799SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18800SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18801SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18802SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18803SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18804SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18805SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18806SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18807SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18808SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18809SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18810SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
18811
18812#ifndef SQLITE_OMIT_FOREIGN_KEY
18813SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18814#else
18815# define sqlite3VdbeCheckFk(p,i) 0
18816#endif
18817
18818#ifndef SQLITE_OMIT_SHARED_CACHE
18819SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
18820#else
18821# define sqlite3VdbeMutexArrayEnter(p)
18822#endif
18823
18824SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18825#ifdef SQLITE_DEBUG
18826SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18827SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18828#endif
18829SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18830
18831#ifndef SQLITE_OMIT_INCRBLOB
18832SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18833#else
18834  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18835#endif
18836
18837#endif /* !defined(_VDBEINT_H_) */
18838
18839/************** End of vdbeInt.h *********************************************/
18840/************** Continuing where we left off in utf.c ************************/
18841
18842#ifndef SQLITE_AMALGAMATION
18843/*
18844** The following constant value is used by the SQLITE_BIGENDIAN and
18845** SQLITE_LITTLEENDIAN macros.
18846*/
18847SQLITE_PRIVATE const int sqlite3one = 1;
18848#endif /* SQLITE_AMALGAMATION */
18849
18850/*
18851** This lookup table is used to help decode the first byte of
18852** a multi-byte UTF8 character.
18853*/
18854static const unsigned char sqlite3Utf8Trans1[] = {
18855  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18856  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18857  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18858  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18859  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18860  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18861  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18862  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18863};
18864
18865
18866#define WRITE_UTF8(zOut, c) {                          \
18867  if( c<0x00080 ){                                     \
18868    *zOut++ = (u8)(c&0xFF);                            \
18869  }                                                    \
18870  else if( c<0x00800 ){                                \
18871    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
18872    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18873  }                                                    \
18874  else if( c<0x10000 ){                                \
18875    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
18876    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18877    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18878  }else{                                               \
18879    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
18880    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
18881    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18882    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18883  }                                                    \
18884}
18885
18886#define WRITE_UTF16LE(zOut, c) {                                    \
18887  if( c<=0xFFFF ){                                                  \
18888    *zOut++ = (u8)(c&0x00FF);                                       \
18889    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18890  }else{                                                            \
18891    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18892    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18893    *zOut++ = (u8)(c&0x00FF);                                       \
18894    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18895  }                                                                 \
18896}
18897
18898#define WRITE_UTF16BE(zOut, c) {                                    \
18899  if( c<=0xFFFF ){                                                  \
18900    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18901    *zOut++ = (u8)(c&0x00FF);                                       \
18902  }else{                                                            \
18903    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18904    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18905    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18906    *zOut++ = (u8)(c&0x00FF);                                       \
18907  }                                                                 \
18908}
18909
18910#define READ_UTF16LE(zIn, TERM, c){                                   \
18911  c = (*zIn++);                                                       \
18912  c += ((*zIn++)<<8);                                                 \
18913  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18914    int c2 = (*zIn++);                                                \
18915    c2 += ((*zIn++)<<8);                                              \
18916    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18917  }                                                                   \
18918}
18919
18920#define READ_UTF16BE(zIn, TERM, c){                                   \
18921  c = ((*zIn++)<<8);                                                  \
18922  c += (*zIn++);                                                      \
18923  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18924    int c2 = ((*zIn++)<<8);                                           \
18925    c2 += (*zIn++);                                                   \
18926    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18927  }                                                                   \
18928}
18929
18930/*
18931** Translate a single UTF-8 character.  Return the unicode value.
18932**
18933** During translation, assume that the byte that zTerm points
18934** is a 0x00.
18935**
18936** Write a pointer to the next unread byte back into *pzNext.
18937**
18938** Notes On Invalid UTF-8:
18939**
18940**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18941**     be encoded as a multi-byte character.  Any multi-byte character that
18942**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18943**
18944**  *  This routine never allows a UTF16 surrogate value to be encoded.
18945**     If a multi-byte character attempts to encode a value between
18946**     0xd800 and 0xe000 then it is rendered as 0xfffd.
18947**
18948**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18949**     byte of a character are interpreted as single-byte characters
18950**     and rendered as themselves even though they are technically
18951**     invalid characters.
18952**
18953**  *  This routine accepts an infinite number of different UTF8 encodings
18954**     for unicode values 0x80 and greater.  It do not change over-length
18955**     encodings to 0xfffd as some systems recommend.
18956*/
18957#define READ_UTF8(zIn, zTerm, c)                           \
18958  c = *(zIn++);                                            \
18959  if( c>=0xc0 ){                                           \
18960    c = sqlite3Utf8Trans1[c-0xc0];                         \
18961    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18962      c = (c<<6) + (0x3f & *(zIn++));                      \
18963    }                                                      \
18964    if( c<0x80                                             \
18965        || (c&0xFFFFF800)==0xD800                          \
18966        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18967  }
18968SQLITE_PRIVATE int sqlite3Utf8Read(
18969  const unsigned char *zIn,       /* First byte of UTF-8 character */
18970  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18971){
18972  int c;
18973
18974  /* Same as READ_UTF8() above but without the zTerm parameter.
18975  ** For this routine, we assume the UTF8 string is always zero-terminated.
18976  */
18977  c = *(zIn++);
18978  if( c>=0xc0 ){
18979    c = sqlite3Utf8Trans1[c-0xc0];
18980    while( (*zIn & 0xc0)==0x80 ){
18981      c = (c<<6) + (0x3f & *(zIn++));
18982    }
18983    if( c<0x80
18984        || (c&0xFFFFF800)==0xD800
18985        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18986  }
18987  *pzNext = zIn;
18988  return c;
18989}
18990
18991
18992
18993
18994/*
18995** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18996** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18997*/
18998/* #define TRANSLATE_TRACE 1 */
18999
19000#ifndef SQLITE_OMIT_UTF16
19001/*
19002** This routine transforms the internal text encoding used by pMem to
19003** desiredEnc. It is an error if the string is already of the desired
19004** encoding, or if *pMem does not contain a string value.
19005*/
19006SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19007  int len;                    /* Maximum length of output string in bytes */
19008  unsigned char *zOut;                  /* Output buffer */
19009  unsigned char *zIn;                   /* Input iterator */
19010  unsigned char *zTerm;                 /* End of input */
19011  unsigned char *z;                     /* Output iterator */
19012  unsigned int c;
19013
19014  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19015  assert( pMem->flags&MEM_Str );
19016  assert( pMem->enc!=desiredEnc );
19017  assert( pMem->enc!=0 );
19018  assert( pMem->n>=0 );
19019
19020#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19021  {
19022    char zBuf[100];
19023    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19024    fprintf(stderr, "INPUT:  %s\n", zBuf);
19025  }
19026#endif
19027
19028  /* If the translation is between UTF-16 little and big endian, then
19029  ** all that is required is to swap the byte order. This case is handled
19030  ** differently from the others.
19031  */
19032  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19033    u8 temp;
19034    int rc;
19035    rc = sqlite3VdbeMemMakeWriteable(pMem);
19036    if( rc!=SQLITE_OK ){
19037      assert( rc==SQLITE_NOMEM );
19038      return SQLITE_NOMEM;
19039    }
19040    zIn = (u8*)pMem->z;
19041    zTerm = &zIn[pMem->n&~1];
19042    while( zIn<zTerm ){
19043      temp = *zIn;
19044      *zIn = *(zIn+1);
19045      zIn++;
19046      *zIn++ = temp;
19047    }
19048    pMem->enc = desiredEnc;
19049    goto translate_out;
19050  }
19051
19052  /* Set len to the maximum number of bytes required in the output buffer. */
19053  if( desiredEnc==SQLITE_UTF8 ){
19054    /* When converting from UTF-16, the maximum growth results from
19055    ** translating a 2-byte character to a 4-byte UTF-8 character.
19056    ** A single byte is required for the output string
19057    ** nul-terminator.
19058    */
19059    pMem->n &= ~1;
19060    len = pMem->n * 2 + 1;
19061  }else{
19062    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19063    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19064    ** character. Two bytes are required in the output buffer for the
19065    ** nul-terminator.
19066    */
19067    len = pMem->n * 2 + 2;
19068  }
19069
19070  /* Set zIn to point at the start of the input buffer and zTerm to point 1
19071  ** byte past the end.
19072  **
19073  ** Variable zOut is set to point at the output buffer, space obtained
19074  ** from sqlite3_malloc().
19075  */
19076  zIn = (u8*)pMem->z;
19077  zTerm = &zIn[pMem->n];
19078  zOut = sqlite3DbMallocRaw(pMem->db, len);
19079  if( !zOut ){
19080    return SQLITE_NOMEM;
19081  }
19082  z = zOut;
19083
19084  if( pMem->enc==SQLITE_UTF8 ){
19085    if( desiredEnc==SQLITE_UTF16LE ){
19086      /* UTF-8 -> UTF-16 Little-endian */
19087      while( zIn<zTerm ){
19088        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19089        READ_UTF8(zIn, zTerm, c);
19090        WRITE_UTF16LE(z, c);
19091      }
19092    }else{
19093      assert( desiredEnc==SQLITE_UTF16BE );
19094      /* UTF-8 -> UTF-16 Big-endian */
19095      while( zIn<zTerm ){
19096        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19097        READ_UTF8(zIn, zTerm, c);
19098        WRITE_UTF16BE(z, c);
19099      }
19100    }
19101    pMem->n = (int)(z - zOut);
19102    *z++ = 0;
19103  }else{
19104    assert( desiredEnc==SQLITE_UTF8 );
19105    if( pMem->enc==SQLITE_UTF16LE ){
19106      /* UTF-16 Little-endian -> UTF-8 */
19107      while( zIn<zTerm ){
19108        READ_UTF16LE(zIn, zIn<zTerm, c);
19109        WRITE_UTF8(z, c);
19110      }
19111    }else{
19112      /* UTF-16 Big-endian -> UTF-8 */
19113      while( zIn<zTerm ){
19114        READ_UTF16BE(zIn, zIn<zTerm, c);
19115        WRITE_UTF8(z, c);
19116      }
19117    }
19118    pMem->n = (int)(z - zOut);
19119  }
19120  *z = 0;
19121  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19122
19123  sqlite3VdbeMemRelease(pMem);
19124  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19125  pMem->enc = desiredEnc;
19126  pMem->flags |= (MEM_Term|MEM_Dyn);
19127  pMem->z = (char*)zOut;
19128  pMem->zMalloc = pMem->z;
19129
19130translate_out:
19131#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19132  {
19133    char zBuf[100];
19134    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19135    fprintf(stderr, "OUTPUT: %s\n", zBuf);
19136  }
19137#endif
19138  return SQLITE_OK;
19139}
19140
19141/*
19142** This routine checks for a byte-order mark at the beginning of the
19143** UTF-16 string stored in *pMem. If one is present, it is removed and
19144** the encoding of the Mem adjusted. This routine does not do any
19145** byte-swapping, it just sets Mem.enc appropriately.
19146**
19147** The allocation (static, dynamic etc.) and encoding of the Mem may be
19148** changed by this function.
19149*/
19150SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19151  int rc = SQLITE_OK;
19152  u8 bom = 0;
19153
19154  assert( pMem->n>=0 );
19155  if( pMem->n>1 ){
19156    u8 b1 = *(u8 *)pMem->z;
19157    u8 b2 = *(((u8 *)pMem->z) + 1);
19158    if( b1==0xFE && b2==0xFF ){
19159      bom = SQLITE_UTF16BE;
19160    }
19161    if( b1==0xFF && b2==0xFE ){
19162      bom = SQLITE_UTF16LE;
19163    }
19164  }
19165
19166  if( bom ){
19167    rc = sqlite3VdbeMemMakeWriteable(pMem);
19168    if( rc==SQLITE_OK ){
19169      pMem->n -= 2;
19170      memmove(pMem->z, &pMem->z[2], pMem->n);
19171      pMem->z[pMem->n] = '\0';
19172      pMem->z[pMem->n+1] = '\0';
19173      pMem->flags |= MEM_Term;
19174      pMem->enc = bom;
19175    }
19176  }
19177  return rc;
19178}
19179#endif /* SQLITE_OMIT_UTF16 */
19180
19181/*
19182** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19183** return the number of unicode characters in pZ up to (but not including)
19184** the first 0x00 byte. If nByte is not less than zero, return the
19185** number of unicode characters in the first nByte of pZ (or up to
19186** the first 0x00, whichever comes first).
19187*/
19188SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19189  int r = 0;
19190  const u8 *z = (const u8*)zIn;
19191  const u8 *zTerm;
19192  if( nByte>=0 ){
19193    zTerm = &z[nByte];
19194  }else{
19195    zTerm = (const u8*)(-1);
19196  }
19197  assert( z<=zTerm );
19198  while( *z!=0 && z<zTerm ){
19199    SQLITE_SKIP_UTF8(z);
19200    r++;
19201  }
19202  return r;
19203}
19204
19205/* This test function is not currently used by the automated test-suite.
19206** Hence it is only available in debug builds.
19207*/
19208#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19209/*
19210** Translate UTF-8 to UTF-8.
19211**
19212** This has the effect of making sure that the string is well-formed
19213** UTF-8.  Miscoded characters are removed.
19214**
19215** The translation is done in-place (since it is impossible for the
19216** correct UTF-8 encoding to be longer than a malformed encoding).
19217*/
19218SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19219  unsigned char *zOut = zIn;
19220  unsigned char *zStart = zIn;
19221  u32 c;
19222
19223  while( zIn[0] ){
19224    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19225    if( c!=0xfffd ){
19226      WRITE_UTF8(zOut, c);
19227    }
19228  }
19229  *zOut = 0;
19230  return (int)(zOut - zStart);
19231}
19232#endif
19233
19234#ifndef SQLITE_OMIT_UTF16
19235/*
19236** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19237** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19238** be freed by the calling function.
19239**
19240** NULL is returned if there is an allocation error.
19241*/
19242SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19243  Mem m;
19244  memset(&m, 0, sizeof(m));
19245  m.db = db;
19246  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19247  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19248  if( db->mallocFailed ){
19249    sqlite3VdbeMemRelease(&m);
19250    m.z = 0;
19251  }
19252  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19253  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19254  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19255  assert( m.z || db->mallocFailed );
19256  return m.z;
19257}
19258
19259/*
19260** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19261** enc. A pointer to the new string is returned, and the value of *pnOut
19262** is set to the length of the returned string in bytes. The call should
19263** arrange to call sqlite3DbFree() on the returned pointer when it is
19264** no longer required.
19265**
19266** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19267** flag set.
19268*/
19269#ifdef SQLITE_ENABLE_STAT2
19270SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19271  Mem m;
19272  memset(&m, 0, sizeof(m));
19273  m.db = db;
19274  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19275  if( sqlite3VdbeMemTranslate(&m, enc) ){
19276    assert( db->mallocFailed );
19277    return 0;
19278  }
19279  assert( m.z==m.zMalloc );
19280  *pnOut = m.n;
19281  return m.z;
19282}
19283#endif
19284
19285/*
19286** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19287** Return the number of bytes in the first nChar unicode characters
19288** in pZ.  nChar must be non-negative.
19289*/
19290SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19291  int c;
19292  unsigned char const *z = zIn;
19293  int n = 0;
19294
19295  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19296    while( n<nChar ){
19297      READ_UTF16BE(z, 1, c);
19298      n++;
19299    }
19300  }else{
19301    while( n<nChar ){
19302      READ_UTF16LE(z, 1, c);
19303      n++;
19304    }
19305  }
19306  return (int)(z-(unsigned char const *)zIn);
19307}
19308
19309#if defined(SQLITE_TEST)
19310/*
19311** This routine is called from the TCL test function "translate_selftest".
19312** It checks that the primitives for serializing and deserializing
19313** characters in each encoding are inverses of each other.
19314*/
19315SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19316  unsigned int i, t;
19317  unsigned char zBuf[20];
19318  unsigned char *z;
19319  int n;
19320  unsigned int c;
19321
19322  for(i=0; i<0x00110000; i++){
19323    z = zBuf;
19324    WRITE_UTF8(z, i);
19325    n = (int)(z-zBuf);
19326    assert( n>0 && n<=4 );
19327    z[0] = 0;
19328    z = zBuf;
19329    c = sqlite3Utf8Read(z, (const u8**)&z);
19330    t = i;
19331    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19332    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19333    assert( c==t );
19334    assert( (z-zBuf)==n );
19335  }
19336  for(i=0; i<0x00110000; i++){
19337    if( i>=0xD800 && i<0xE000 ) continue;
19338    z = zBuf;
19339    WRITE_UTF16LE(z, i);
19340    n = (int)(z-zBuf);
19341    assert( n>0 && n<=4 );
19342    z[0] = 0;
19343    z = zBuf;
19344    READ_UTF16LE(z, 1, c);
19345    assert( c==i );
19346    assert( (z-zBuf)==n );
19347  }
19348  for(i=0; i<0x00110000; i++){
19349    if( i>=0xD800 && i<0xE000 ) continue;
19350    z = zBuf;
19351    WRITE_UTF16BE(z, i);
19352    n = (int)(z-zBuf);
19353    assert( n>0 && n<=4 );
19354    z[0] = 0;
19355    z = zBuf;
19356    READ_UTF16BE(z, 1, c);
19357    assert( c==i );
19358    assert( (z-zBuf)==n );
19359  }
19360}
19361#endif /* SQLITE_TEST */
19362#endif /* SQLITE_OMIT_UTF16 */
19363
19364/************** End of utf.c *************************************************/
19365/************** Begin file util.c ********************************************/
19366/*
19367** 2001 September 15
19368**
19369** The author disclaims copyright to this source code.  In place of
19370** a legal notice, here is a blessing:
19371**
19372**    May you do good and not evil.
19373**    May you find forgiveness for yourself and forgive others.
19374**    May you share freely, never taking more than you give.
19375**
19376*************************************************************************
19377** Utility functions used throughout sqlite.
19378**
19379** This file contains functions for allocating memory, comparing
19380** strings, and stuff like that.
19381**
19382*/
19383#ifdef SQLITE_HAVE_ISNAN
19384# include <math.h>
19385#endif
19386
19387/*
19388** Routine needed to support the testcase() macro.
19389*/
19390#ifdef SQLITE_COVERAGE_TEST
19391SQLITE_PRIVATE void sqlite3Coverage(int x){
19392  static int dummy = 0;
19393  dummy += x;
19394}
19395#endif
19396
19397#ifndef SQLITE_OMIT_FLOATING_POINT
19398/*
19399** Return true if the floating point value is Not a Number (NaN).
19400**
19401** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19402** Otherwise, we have our own implementation that works on most systems.
19403*/
19404SQLITE_PRIVATE int sqlite3IsNaN(double x){
19405  int rc;   /* The value return */
19406#if !defined(SQLITE_HAVE_ISNAN)
19407  /*
19408  ** Systems that support the isnan() library function should probably
19409  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19410  ** found that many systems do not have a working isnan() function so
19411  ** this implementation is provided as an alternative.
19412  **
19413  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
19414  ** On the other hand, the use of -ffast-math comes with the following
19415  ** warning:
19416  **
19417  **      This option [-ffast-math] should never be turned on by any
19418  **      -O option since it can result in incorrect output for programs
19419  **      which depend on an exact implementation of IEEE or ISO
19420  **      rules/specifications for math functions.
19421  **
19422  ** Under MSVC, this NaN test may fail if compiled with a floating-
19423  ** point precision mode other than /fp:precise.  From the MSDN
19424  ** documentation:
19425  **
19426  **      The compiler [with /fp:precise] will properly handle comparisons
19427  **      involving NaN. For example, x != x evaluates to true if x is NaN
19428  **      ...
19429  */
19430#ifdef __FAST_MATH__
19431# error SQLite will not work correctly with the -ffast-math option of GCC.
19432#endif
19433  volatile double y = x;
19434  volatile double z = y;
19435  rc = (y!=z);
19436#else  /* if defined(SQLITE_HAVE_ISNAN) */
19437  rc = isnan(x);
19438#endif /* SQLITE_HAVE_ISNAN */
19439  testcase( rc );
19440  return rc;
19441}
19442#endif /* SQLITE_OMIT_FLOATING_POINT */
19443
19444/*
19445** Compute a string length that is limited to what can be stored in
19446** lower 30 bits of a 32-bit signed integer.
19447**
19448** The value returned will never be negative.  Nor will it ever be greater
19449** than the actual length of the string.  For very long strings (greater
19450** than 1GiB) the value returned might be less than the true string length.
19451*/
19452SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19453  const char *z2 = z;
19454  if( z==0 ) return 0;
19455  while( *z2 ){ z2++; }
19456  return 0x3fffffff & (int)(z2 - z);
19457}
19458
19459/*
19460** Set the most recent error code and error string for the sqlite
19461** handle "db". The error code is set to "err_code".
19462**
19463** If it is not NULL, string zFormat specifies the format of the
19464** error string in the style of the printf functions: The following
19465** format characters are allowed:
19466**
19467**      %s      Insert a string
19468**      %z      A string that should be freed after use
19469**      %d      Insert an integer
19470**      %T      Insert a token
19471**      %S      Insert the first element of a SrcList
19472**
19473** zFormat and any string tokens that follow it are assumed to be
19474** encoded in UTF-8.
19475**
19476** To clear the most recent error for sqlite handle "db", sqlite3Error
19477** should be called with err_code set to SQLITE_OK and zFormat set
19478** to NULL.
19479*/
19480SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19481  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19482    db->errCode = err_code;
19483    if( zFormat ){
19484      char *z;
19485      va_list ap;
19486      va_start(ap, zFormat);
19487      z = sqlite3VMPrintf(db, zFormat, ap);
19488      va_end(ap);
19489      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19490    }else{
19491      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19492    }
19493  }
19494}
19495
19496/*
19497** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19498** The following formatting characters are allowed:
19499**
19500**      %s      Insert a string
19501**      %z      A string that should be freed after use
19502**      %d      Insert an integer
19503**      %T      Insert a token
19504**      %S      Insert the first element of a SrcList
19505**
19506** This function should be used to report any error that occurs whilst
19507** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19508** last thing the sqlite3_prepare() function does is copy the error
19509** stored by this function into the database handle using sqlite3Error().
19510** Function sqlite3Error() should be used during statement execution
19511** (sqlite3_step() etc.).
19512*/
19513SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19514  char *zMsg;
19515  va_list ap;
19516  sqlite3 *db = pParse->db;
19517  va_start(ap, zFormat);
19518  zMsg = sqlite3VMPrintf(db, zFormat, ap);
19519  va_end(ap);
19520  if( db->suppressErr ){
19521    sqlite3DbFree(db, zMsg);
19522  }else{
19523    pParse->nErr++;
19524    sqlite3DbFree(db, pParse->zErrMsg);
19525    pParse->zErrMsg = zMsg;
19526    pParse->rc = SQLITE_ERROR;
19527  }
19528}
19529
19530/*
19531** Convert an SQL-style quoted string into a normal string by removing
19532** the quote characters.  The conversion is done in-place.  If the
19533** input does not begin with a quote character, then this routine
19534** is a no-op.
19535**
19536** The input string must be zero-terminated.  A new zero-terminator
19537** is added to the dequoted string.
19538**
19539** The return value is -1 if no dequoting occurs or the length of the
19540** dequoted string, exclusive of the zero terminator, if dequoting does
19541** occur.
19542**
19543** 2002-Feb-14: This routine is extended to remove MS-Access style
19544** brackets from around identifers.  For example:  "[a-b-c]" becomes
19545** "a-b-c".
19546*/
19547SQLITE_PRIVATE int sqlite3Dequote(char *z){
19548  char quote;
19549  int i, j;
19550  if( z==0 ) return -1;
19551  quote = z[0];
19552  switch( quote ){
19553    case '\'':  break;
19554    case '"':   break;
19555    case '`':   break;                /* For MySQL compatibility */
19556    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19557    default:    return -1;
19558  }
19559  for(i=1, j=0; ALWAYS(z[i]); i++){
19560    if( z[i]==quote ){
19561      if( z[i+1]==quote ){
19562        z[j++] = quote;
19563        i++;
19564      }else{
19565        break;
19566      }
19567    }else{
19568      z[j++] = z[i];
19569    }
19570  }
19571  z[j] = 0;
19572  return j;
19573}
19574
19575/* Convenient short-hand */
19576#define UpperToLower sqlite3UpperToLower
19577
19578/*
19579** Some systems have stricmp().  Others have strcasecmp().  Because
19580** there is no consistency, we will define our own.
19581*/
19582SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19583  register unsigned char *a, *b;
19584  a = (unsigned char *)zLeft;
19585  b = (unsigned char *)zRight;
19586  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19587  return UpperToLower[*a] - UpperToLower[*b];
19588}
19589SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
19590  register unsigned char *a, *b;
19591  a = (unsigned char *)zLeft;
19592  b = (unsigned char *)zRight;
19593  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19594  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19595}
19596
19597/*
19598** Return TRUE if z is a pure numeric string.  Return FALSE and leave
19599** *realnum unchanged if the string contains any character which is not
19600** part of a number.
19601**
19602** If the string is pure numeric, set *realnum to TRUE if the string
19603** contains the '.' character or an "E+000" style exponentiation suffix.
19604** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
19605** false does not mean that the number can be successfully converted into
19606** an integer - it might be too big.
19607**
19608** An empty string is considered non-numeric.
19609*/
19610SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19611  int incr = (enc==SQLITE_UTF8?1:2);
19612  if( enc==SQLITE_UTF16BE ) z++;
19613  if( *z=='-' || *z=='+' ) z += incr;
19614  if( !sqlite3Isdigit(*z) ){
19615    return 0;
19616  }
19617  z += incr;
19618  *realnum = 0;
19619  while( sqlite3Isdigit(*z) ){ z += incr; }
19620#ifndef SQLITE_OMIT_FLOATING_POINT
19621  if( *z=='.' ){
19622    z += incr;
19623    if( !sqlite3Isdigit(*z) ) return 0;
19624    while( sqlite3Isdigit(*z) ){ z += incr; }
19625    *realnum = 1;
19626  }
19627  if( *z=='e' || *z=='E' ){
19628    z += incr;
19629    if( *z=='+' || *z=='-' ) z += incr;
19630    if( !sqlite3Isdigit(*z) ) return 0;
19631    while( sqlite3Isdigit(*z) ){ z += incr; }
19632    *realnum = 1;
19633  }
19634#endif
19635  return *z==0;
19636}
19637
19638/*
19639** The string z[] is an ASCII representation of a real number.
19640** Convert this string to a double.
19641**
19642** This routine assumes that z[] really is a valid number.  If it
19643** is not, the result is undefined.
19644**
19645** This routine is used instead of the library atof() function because
19646** the library atof() might want to use "," as the decimal point instead
19647** of "." depending on how locale is set.  But that would cause problems
19648** for SQL.  So this routine always uses "." regardless of locale.
19649*/
19650SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19651#ifndef SQLITE_OMIT_FLOATING_POINT
19652  const char *zBegin = z;
19653  /* sign * significand * (10 ^ (esign * exponent)) */
19654  int sign = 1;   /* sign of significand */
19655  i64 s = 0;      /* significand */
19656  int d = 0;      /* adjust exponent for shifting decimal point */
19657  int esign = 1;  /* sign of exponent */
19658  int e = 0;      /* exponent */
19659  double result;
19660  int nDigits = 0;
19661
19662  /* skip leading spaces */
19663  while( sqlite3Isspace(*z) ) z++;
19664  /* get sign of significand */
19665  if( *z=='-' ){
19666    sign = -1;
19667    z++;
19668  }else if( *z=='+' ){
19669    z++;
19670  }
19671  /* skip leading zeroes */
19672  while( z[0]=='0' ) z++, nDigits++;
19673
19674  /* copy max significant digits to significand */
19675  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19676    s = s*10 + (*z - '0');
19677    z++, nDigits++;
19678  }
19679  /* skip non-significant significand digits
19680  ** (increase exponent by d to shift decimal left) */
19681  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
19682
19683  /* if decimal point is present */
19684  if( *z=='.' ){
19685    z++;
19686    /* copy digits from after decimal to significand
19687    ** (decrease exponent by d to shift decimal right) */
19688    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19689      s = s*10 + (*z - '0');
19690      z++, nDigits++, d--;
19691    }
19692    /* skip non-significant digits */
19693    while( sqlite3Isdigit(*z) ) z++, nDigits++;
19694  }
19695
19696  /* if exponent is present */
19697  if( *z=='e' || *z=='E' ){
19698    z++;
19699    /* get sign of exponent */
19700    if( *z=='-' ){
19701      esign = -1;
19702      z++;
19703    }else if( *z=='+' ){
19704      z++;
19705    }
19706    /* copy digits to exponent */
19707    while( sqlite3Isdigit(*z) ){
19708      e = e*10 + (*z - '0');
19709      z++;
19710    }
19711  }
19712
19713  /* adjust exponent by d, and update sign */
19714  e = (e*esign) + d;
19715  if( e<0 ) {
19716    esign = -1;
19717    e *= -1;
19718  } else {
19719    esign = 1;
19720  }
19721
19722  /* if 0 significand */
19723  if( !s ) {
19724    /* In the IEEE 754 standard, zero is signed.
19725    ** Add the sign if we've seen at least one digit */
19726    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
19727  } else {
19728    /* attempt to reduce exponent */
19729    if( esign>0 ){
19730      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
19731    }else{
19732      while( !(s%10) && e>0 ) e--,s/=10;
19733    }
19734
19735    /* adjust the sign of significand */
19736    s = sign<0 ? -s : s;
19737
19738    /* if exponent, scale significand as appropriate
19739    ** and store in result. */
19740    if( e ){
19741      double scale = 1.0;
19742      /* attempt to handle extremely small/large numbers better */
19743      if( e>307 && e<342 ){
19744        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
19745        if( esign<0 ){
19746          result = s / scale;
19747          result /= 1.0e+308;
19748        }else{
19749          result = s * scale;
19750          result *= 1.0e+308;
19751        }
19752      }else{
19753        /* 1.0e+22 is the largest power of 10 than can be
19754        ** represented exactly. */
19755        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
19756        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
19757        if( esign<0 ){
19758          result = s / scale;
19759        }else{
19760          result = s * scale;
19761        }
19762      }
19763    } else {
19764      result = (double)s;
19765    }
19766  }
19767
19768  /* store the result */
19769  *pResult = result;
19770
19771  /* return number of characters used */
19772  return (int)(z - zBegin);
19773#else
19774  return sqlite3Atoi64(z, pResult);
19775#endif /* SQLITE_OMIT_FLOATING_POINT */
19776}
19777
19778/*
19779** Compare the 19-character string zNum against the text representation
19780** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19781** if zNum is less than, equal to, or greater than the string.
19782**
19783** Unlike memcmp() this routine is guaranteed to return the difference
19784** in the values of the last digit if the only difference is in the
19785** last digit.  So, for example,
19786**
19787**      compare2pow63("9223372036854775800")
19788**
19789** will return -8.
19790*/
19791static int compare2pow63(const char *zNum){
19792  int c;
19793  c = memcmp(zNum,"922337203685477580",18)*10;
19794  if( c==0 ){
19795    c = zNum[18] - '8';
19796    testcase( c==(-1) );
19797    testcase( c==0 );
19798    testcase( c==(+1) );
19799  }
19800  return c;
19801}
19802
19803
19804/*
19805** Return TRUE if zNum is a 64-bit signed integer and write
19806** the value of the integer into *pNum.  If zNum is not an integer
19807** or is an integer that is too large to be expressed with 64 bits,
19808** then return false.
19809**
19810** When this routine was originally written it dealt with only
19811** 32-bit numbers.  At that time, it was much faster than the
19812** atoi() library routine in RedHat 7.2.
19813*/
19814SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19815  i64 v = 0;
19816  int neg;
19817  int i, c;
19818  const char *zStart;
19819  while( sqlite3Isspace(*zNum) ) zNum++;
19820  if( *zNum=='-' ){
19821    neg = 1;
19822    zNum++;
19823  }else if( *zNum=='+' ){
19824    neg = 0;
19825    zNum++;
19826  }else{
19827    neg = 0;
19828  }
19829  zStart = zNum;
19830  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19831  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19832    v = v*10 + c - '0';
19833  }
19834  *pNum = neg ? -v : v;
19835  testcase( i==18 );
19836  testcase( i==19 );
19837  testcase( i==20 );
19838  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19839    /* zNum is empty or contains non-numeric text or is longer
19840    ** than 19 digits (thus guaranting that it is too large) */
19841    return 0;
19842  }else if( i<19 ){
19843    /* Less than 19 digits, so we know that it fits in 64 bits */
19844    return 1;
19845  }else{
19846    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19847    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19848    ** is 2^63. */
19849    return compare2pow63(zNum)<neg;
19850  }
19851}
19852
19853/*
19854** The string zNum represents an unsigned integer.  The zNum string
19855** consists of one or more digit characters and is terminated by
19856** a zero character.  Any stray characters in zNum result in undefined
19857** behavior.
19858**
19859** If the unsigned integer that zNum represents will fit in a
19860** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19861**
19862** If the negFlag parameter is true, that means that zNum really represents
19863** a negative number.  (The leading "-" is omitted from zNum.)  This
19864** parameter is needed to determine a boundary case.  A string
19865** of "9223373036854775808" returns false if negFlag is false or true
19866** if negFlag is true.
19867**
19868** Leading zeros are ignored.
19869*/
19870SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19871  int i;
19872  int neg = 0;
19873
19874  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
19875
19876  if( negFlag ) neg = 1-neg;
19877  while( *zNum=='0' ){
19878    zNum++;   /* Skip leading zeros.  Ticket #2454 */
19879  }
19880  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
19881  testcase( i==18 );
19882  testcase( i==19 );
19883  testcase( i==20 );
19884  if( i<19 ){
19885    /* Guaranteed to fit if less than 19 digits */
19886    return 1;
19887  }else if( i>19 ){
19888    /* Guaranteed to be too big if greater than 19 digits */
19889    return 0;
19890  }else{
19891    /* Compare against 2^63. */
19892    return compare2pow63(zNum)<neg;
19893  }
19894}
19895
19896/*
19897** If zNum represents an integer that will fit in 32-bits, then set
19898** *pValue to that integer and return true.  Otherwise return false.
19899**
19900** Any non-numeric characters that following zNum are ignored.
19901** This is different from sqlite3Atoi64() which requires the
19902** input number to be zero-terminated.
19903*/
19904SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19905  sqlite_int64 v = 0;
19906  int i, c;
19907  int neg = 0;
19908  if( zNum[0]=='-' ){
19909    neg = 1;
19910    zNum++;
19911  }else if( zNum[0]=='+' ){
19912    zNum++;
19913  }
19914  while( zNum[0]=='0' ) zNum++;
19915  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19916    v = v*10 + c;
19917  }
19918
19919  /* The longest decimal representation of a 32 bit integer is 10 digits:
19920  **
19921  **             1234567890
19922  **     2^31 -> 2147483648
19923  */
19924  testcase( i==10 );
19925  if( i>10 ){
19926    return 0;
19927  }
19928  testcase( v-neg==2147483647 );
19929  if( v-neg>2147483647 ){
19930    return 0;
19931  }
19932  if( neg ){
19933    v = -v;
19934  }
19935  *pValue = (int)v;
19936  return 1;
19937}
19938
19939/*
19940** The variable-length integer encoding is as follows:
19941**
19942** KEY:
19943**         A = 0xxxxxxx    7 bits of data and one flag bit
19944**         B = 1xxxxxxx    7 bits of data and one flag bit
19945**         C = xxxxxxxx    8 bits of data
19946**
19947**  7 bits - A
19948** 14 bits - BA
19949** 21 bits - BBA
19950** 28 bits - BBBA
19951** 35 bits - BBBBA
19952** 42 bits - BBBBBA
19953** 49 bits - BBBBBBA
19954** 56 bits - BBBBBBBA
19955** 64 bits - BBBBBBBBC
19956*/
19957
19958/*
19959** Write a 64-bit variable-length integer to memory starting at p[0].
19960** The length of data write will be between 1 and 9 bytes.  The number
19961** of bytes written is returned.
19962**
19963** A variable-length integer consists of the lower 7 bits of each byte
19964** for all bytes that have the 8th bit set and one byte with the 8th
19965** bit clear.  Except, if we get to the 9th byte, it stores the full
19966** 8 bits and is the last byte.
19967*/
19968SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19969  int i, j, n;
19970  u8 buf[10];
19971  if( v & (((u64)0xff000000)<<32) ){
19972    p[8] = (u8)v;
19973    v >>= 8;
19974    for(i=7; i>=0; i--){
19975      p[i] = (u8)((v & 0x7f) | 0x80);
19976      v >>= 7;
19977    }
19978    return 9;
19979  }
19980  n = 0;
19981  do{
19982    buf[n++] = (u8)((v & 0x7f) | 0x80);
19983    v >>= 7;
19984  }while( v!=0 );
19985  buf[0] &= 0x7f;
19986  assert( n<=9 );
19987  for(i=0, j=n-1; j>=0; j--, i++){
19988    p[i] = buf[j];
19989  }
19990  return n;
19991}
19992
19993/*
19994** This routine is a faster version of sqlite3PutVarint() that only
19995** works for 32-bit positive integers and which is optimized for
19996** the common case of small integers.  A MACRO version, putVarint32,
19997** is provided which inlines the single-byte case.  All code should use
19998** the MACRO version as this function assumes the single-byte case has
19999** already been handled.
20000*/
20001SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20002#ifndef putVarint32
20003  if( (v & ~0x7f)==0 ){
20004    p[0] = v;
20005    return 1;
20006  }
20007#endif
20008  if( (v & ~0x3fff)==0 ){
20009    p[0] = (u8)((v>>7) | 0x80);
20010    p[1] = (u8)(v & 0x7f);
20011    return 2;
20012  }
20013  return sqlite3PutVarint(p, v);
20014}
20015
20016/*
20017** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20018** are defined here rather than simply putting the constant expressions
20019** inline in order to work around bugs in the RVT compiler.
20020**
20021** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20022**
20023** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20024*/
20025#define SLOT_2_0     0x001fc07f
20026#define SLOT_4_2_0   0xf01fc07f
20027
20028
20029/*
20030** Read a 64-bit variable-length integer from memory starting at p[0].
20031** Return the number of bytes read.  The value is stored in *v.
20032*/
20033SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20034  u32 a,b,s;
20035
20036  a = *p;
20037  /* a: p0 (unmasked) */
20038  if (!(a&0x80))
20039  {
20040    *v = a;
20041    return 1;
20042  }
20043
20044  p++;
20045  b = *p;
20046  /* b: p1 (unmasked) */
20047  if (!(b&0x80))
20048  {
20049    a &= 0x7f;
20050    a = a<<7;
20051    a |= b;
20052    *v = a;
20053    return 2;
20054  }
20055
20056  /* Verify that constants are precomputed correctly */
20057  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20058  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20059
20060  p++;
20061  a = a<<14;
20062  a |= *p;
20063  /* a: p0<<14 | p2 (unmasked) */
20064  if (!(a&0x80))
20065  {
20066    a &= SLOT_2_0;
20067    b &= 0x7f;
20068    b = b<<7;
20069    a |= b;
20070    *v = a;
20071    return 3;
20072  }
20073
20074  /* CSE1 from below */
20075  a &= SLOT_2_0;
20076  p++;
20077  b = b<<14;
20078  b |= *p;
20079  /* b: p1<<14 | p3 (unmasked) */
20080  if (!(b&0x80))
20081  {
20082    b &= SLOT_2_0;
20083    /* moved CSE1 up */
20084    /* a &= (0x7f<<14)|(0x7f); */
20085    a = a<<7;
20086    a |= b;
20087    *v = a;
20088    return 4;
20089  }
20090
20091  /* a: p0<<14 | p2 (masked) */
20092  /* b: p1<<14 | p3 (unmasked) */
20093  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20094  /* moved CSE1 up */
20095  /* a &= (0x7f<<14)|(0x7f); */
20096  b &= SLOT_2_0;
20097  s = a;
20098  /* s: p0<<14 | p2 (masked) */
20099
20100  p++;
20101  a = a<<14;
20102  a |= *p;
20103  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20104  if (!(a&0x80))
20105  {
20106    /* we can skip these cause they were (effectively) done above in calc'ing s */
20107    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20108    /* b &= (0x7f<<14)|(0x7f); */
20109    b = b<<7;
20110    a |= b;
20111    s = s>>18;
20112    *v = ((u64)s)<<32 | a;
20113    return 5;
20114  }
20115
20116  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20117  s = s<<7;
20118  s |= b;
20119  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20120
20121  p++;
20122  b = b<<14;
20123  b |= *p;
20124  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20125  if (!(b&0x80))
20126  {
20127    /* we can skip this cause it was (effectively) done above in calc'ing s */
20128    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20129    a &= SLOT_2_0;
20130    a = a<<7;
20131    a |= b;
20132    s = s>>18;
20133    *v = ((u64)s)<<32 | a;
20134    return 6;
20135  }
20136
20137  p++;
20138  a = a<<14;
20139  a |= *p;
20140  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20141  if (!(a&0x80))
20142  {
20143    a &= SLOT_4_2_0;
20144    b &= SLOT_2_0;
20145    b = b<<7;
20146    a |= b;
20147    s = s>>11;
20148    *v = ((u64)s)<<32 | a;
20149    return 7;
20150  }
20151
20152  /* CSE2 from below */
20153  a &= SLOT_2_0;
20154  p++;
20155  b = b<<14;
20156  b |= *p;
20157  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20158  if (!(b&0x80))
20159  {
20160    b &= SLOT_4_2_0;
20161    /* moved CSE2 up */
20162    /* a &= (0x7f<<14)|(0x7f); */
20163    a = a<<7;
20164    a |= b;
20165    s = s>>4;
20166    *v = ((u64)s)<<32 | a;
20167    return 8;
20168  }
20169
20170  p++;
20171  a = a<<15;
20172  a |= *p;
20173  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20174
20175  /* moved CSE2 up */
20176  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20177  b &= SLOT_2_0;
20178  b = b<<8;
20179  a |= b;
20180
20181  s = s<<4;
20182  b = p[-4];
20183  b &= 0x7f;
20184  b = b>>3;
20185  s |= b;
20186
20187  *v = ((u64)s)<<32 | a;
20188
20189  return 9;
20190}
20191
20192/*
20193** Read a 32-bit variable-length integer from memory starting at p[0].
20194** Return the number of bytes read.  The value is stored in *v.
20195**
20196** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20197** integer, then set *v to 0xffffffff.
20198**
20199** A MACRO version, getVarint32, is provided which inlines the
20200** single-byte case.  All code should use the MACRO version as
20201** this function assumes the single-byte case has already been handled.
20202*/
20203SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20204  u32 a,b;
20205
20206  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20207  ** by the getVarin32() macro */
20208  a = *p;
20209  /* a: p0 (unmasked) */
20210#ifndef getVarint32
20211  if (!(a&0x80))
20212  {
20213    /* Values between 0 and 127 */
20214    *v = a;
20215    return 1;
20216  }
20217#endif
20218
20219  /* The 2-byte case */
20220  p++;
20221  b = *p;
20222  /* b: p1 (unmasked) */
20223  if (!(b&0x80))
20224  {
20225    /* Values between 128 and 16383 */
20226    a &= 0x7f;
20227    a = a<<7;
20228    *v = a | b;
20229    return 2;
20230  }
20231
20232  /* The 3-byte case */
20233  p++;
20234  a = a<<14;
20235  a |= *p;
20236  /* a: p0<<14 | p2 (unmasked) */
20237  if (!(a&0x80))
20238  {
20239    /* Values between 16384 and 2097151 */
20240    a &= (0x7f<<14)|(0x7f);
20241    b &= 0x7f;
20242    b = b<<7;
20243    *v = a | b;
20244    return 3;
20245  }
20246
20247  /* A 32-bit varint is used to store size information in btrees.
20248  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20249  ** A 3-byte varint is sufficient, for example, to record the size
20250  ** of a 1048569-byte BLOB or string.
20251  **
20252  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20253  ** rare larger cases can be handled by the slower 64-bit varint
20254  ** routine.
20255  */
20256#if 1
20257  {
20258    u64 v64;
20259    u8 n;
20260
20261    p -= 2;
20262    n = sqlite3GetVarint(p, &v64);
20263    assert( n>3 && n<=9 );
20264    if( (v64 & SQLITE_MAX_U32)!=v64 ){
20265      *v = 0xffffffff;
20266    }else{
20267      *v = (u32)v64;
20268    }
20269    return n;
20270  }
20271
20272#else
20273  /* For following code (kept for historical record only) shows an
20274  ** unrolling for the 3- and 4-byte varint cases.  This code is
20275  ** slightly faster, but it is also larger and much harder to test.
20276  */
20277  p++;
20278  b = b<<14;
20279  b |= *p;
20280  /* b: p1<<14 | p3 (unmasked) */
20281  if (!(b&0x80))
20282  {
20283    /* Values between 2097152 and 268435455 */
20284    b &= (0x7f<<14)|(0x7f);
20285    a &= (0x7f<<14)|(0x7f);
20286    a = a<<7;
20287    *v = a | b;
20288    return 4;
20289  }
20290
20291  p++;
20292  a = a<<14;
20293  a |= *p;
20294  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20295  if (!(a&0x80))
20296  {
20297    /* Values  between 268435456 and 34359738367 */
20298    a &= SLOT_4_2_0;
20299    b &= SLOT_4_2_0;
20300    b = b<<7;
20301    *v = a | b;
20302    return 5;
20303  }
20304
20305  /* We can only reach this point when reading a corrupt database
20306  ** file.  In that case we are not in any hurry.  Use the (relatively
20307  ** slow) general-purpose sqlite3GetVarint() routine to extract the
20308  ** value. */
20309  {
20310    u64 v64;
20311    u8 n;
20312
20313    p -= 4;
20314    n = sqlite3GetVarint(p, &v64);
20315    assert( n>5 && n<=9 );
20316    *v = (u32)v64;
20317    return n;
20318  }
20319#endif
20320}
20321
20322/*
20323** Return the number of bytes that will be needed to store the given
20324** 64-bit integer.
20325*/
20326SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20327  int i = 0;
20328  do{
20329    i++;
20330    v >>= 7;
20331  }while( v!=0 && ALWAYS(i<9) );
20332  return i;
20333}
20334
20335
20336/*
20337** Read or write a four-byte big-endian integer value.
20338*/
20339SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20340  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20341}
20342SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20343  p[0] = (u8)(v>>24);
20344  p[1] = (u8)(v>>16);
20345  p[2] = (u8)(v>>8);
20346  p[3] = (u8)v;
20347}
20348
20349
20350
20351#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20352/*
20353** Translate a single byte of Hex into an integer.
20354** This routine only works if h really is a valid hexadecimal
20355** character:  0..9a..fA..F
20356*/
20357static u8 hexToInt(int h){
20358  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20359#ifdef SQLITE_ASCII
20360  h += 9*(1&(h>>6));
20361#endif
20362#ifdef SQLITE_EBCDIC
20363  h += 9*(1&~(h>>4));
20364#endif
20365  return (u8)(h & 0xf);
20366}
20367#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20368
20369#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20370/*
20371** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20372** value.  Return a pointer to its binary value.  Space to hold the
20373** binary value has been obtained from malloc and must be freed by
20374** the calling routine.
20375*/
20376SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20377  char *zBlob;
20378  int i;
20379
20380  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20381  n--;
20382  if( zBlob ){
20383    for(i=0; i<n; i+=2){
20384      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20385    }
20386    zBlob[i/2] = 0;
20387  }
20388  return zBlob;
20389}
20390#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20391
20392/*
20393** Log an error that is an API call on a connection pointer that should
20394** not have been used.  The "type" of connection pointer is given as the
20395** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20396*/
20397static void logBadConnection(const char *zType){
20398  sqlite3_log(SQLITE_MISUSE,
20399     "API call with %s database connection pointer",
20400     zType
20401  );
20402}
20403
20404/*
20405** Check to make sure we have a valid db pointer.  This test is not
20406** foolproof but it does provide some measure of protection against
20407** misuse of the interface such as passing in db pointers that are
20408** NULL or which have been previously closed.  If this routine returns
20409** 1 it means that the db pointer is valid and 0 if it should not be
20410** dereferenced for any reason.  The calling function should invoke
20411** SQLITE_MISUSE immediately.
20412**
20413** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20414** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20415** open properly and is not fit for general use but which can be
20416** used as an argument to sqlite3_errmsg() or sqlite3_close().
20417*/
20418SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20419  u32 magic;
20420  if( db==0 ){
20421    logBadConnection("NULL");
20422    return 0;
20423  }
20424  magic = db->magic;
20425  if( magic!=SQLITE_MAGIC_OPEN ){
20426    if( sqlite3SafetyCheckSickOrOk(db) ){
20427      testcase( sqlite3GlobalConfig.xLog!=0 );
20428      logBadConnection("unopened");
20429    }
20430    return 0;
20431  }else{
20432    return 1;
20433  }
20434}
20435SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20436  u32 magic;
20437  magic = db->magic;
20438  if( magic!=SQLITE_MAGIC_SICK &&
20439      magic!=SQLITE_MAGIC_OPEN &&
20440      magic!=SQLITE_MAGIC_BUSY ){
20441    testcase( sqlite3GlobalConfig.xLog!=0 );
20442    logBadConnection("invalid");
20443    return 0;
20444  }else{
20445    return 1;
20446  }
20447}
20448
20449/************** End of util.c ************************************************/
20450/************** Begin file hash.c ********************************************/
20451/*
20452** 2001 September 22
20453**
20454** The author disclaims copyright to this source code.  In place of
20455** a legal notice, here is a blessing:
20456**
20457**    May you do good and not evil.
20458**    May you find forgiveness for yourself and forgive others.
20459**    May you share freely, never taking more than you give.
20460**
20461*************************************************************************
20462** This is the implementation of generic hash-tables
20463** used in SQLite.
20464*/
20465
20466/* Turn bulk memory into a hash table object by initializing the
20467** fields of the Hash structure.
20468**
20469** "pNew" is a pointer to the hash table that is to be initialized.
20470*/
20471SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20472  assert( pNew!=0 );
20473  pNew->first = 0;
20474  pNew->count = 0;
20475  pNew->htsize = 0;
20476  pNew->ht = 0;
20477}
20478
20479/* Remove all entries from a hash table.  Reclaim all memory.
20480** Call this routine to delete a hash table or to reset a hash table
20481** to the empty state.
20482*/
20483SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20484  HashElem *elem;         /* For looping over all elements of the table */
20485
20486  assert( pH!=0 );
20487  elem = pH->first;
20488  pH->first = 0;
20489  sqlite3_free(pH->ht);
20490  pH->ht = 0;
20491  pH->htsize = 0;
20492  while( elem ){
20493    HashElem *next_elem = elem->next;
20494    sqlite3_free(elem);
20495    elem = next_elem;
20496  }
20497  pH->count = 0;
20498}
20499
20500/*
20501** The hashing function.
20502*/
20503static unsigned int strHash(const char *z, int nKey){
20504  int h = 0;
20505  assert( nKey>=0 );
20506  while( nKey > 0  ){
20507    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20508    nKey--;
20509  }
20510  return h;
20511}
20512
20513
20514/* Link pNew element into the hash table pH.  If pEntry!=0 then also
20515** insert pNew into the pEntry hash bucket.
20516*/
20517static void insertElement(
20518  Hash *pH,              /* The complete hash table */
20519  struct _ht *pEntry,    /* The entry into which pNew is inserted */
20520  HashElem *pNew         /* The element to be inserted */
20521){
20522  HashElem *pHead;       /* First element already in pEntry */
20523  if( pEntry ){
20524    pHead = pEntry->count ? pEntry->chain : 0;
20525    pEntry->count++;
20526    pEntry->chain = pNew;
20527  }else{
20528    pHead = 0;
20529  }
20530  if( pHead ){
20531    pNew->next = pHead;
20532    pNew->prev = pHead->prev;
20533    if( pHead->prev ){ pHead->prev->next = pNew; }
20534    else             { pH->first = pNew; }
20535    pHead->prev = pNew;
20536  }else{
20537    pNew->next = pH->first;
20538    if( pH->first ){ pH->first->prev = pNew; }
20539    pNew->prev = 0;
20540    pH->first = pNew;
20541  }
20542}
20543
20544
20545/* Resize the hash table so that it cantains "new_size" buckets.
20546**
20547** The hash table might fail to resize if sqlite3_malloc() fails or
20548** if the new size is the same as the prior size.
20549** Return TRUE if the resize occurs and false if not.
20550*/
20551static int rehash(Hash *pH, unsigned int new_size){
20552  struct _ht *new_ht;            /* The new hash table */
20553  HashElem *elem, *next_elem;    /* For looping over existing elements */
20554
20555#if SQLITE_MALLOC_SOFT_LIMIT>0
20556  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20557    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20558  }
20559  if( new_size==pH->htsize ) return 0;
20560#endif
20561
20562  /* The inability to allocates space for a larger hash table is
20563  ** a performance hit but it is not a fatal error.  So mark the
20564  ** allocation as a benign.
20565  */
20566  sqlite3BeginBenignMalloc();
20567  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
20568  sqlite3EndBenignMalloc();
20569
20570  if( new_ht==0 ) return 0;
20571  sqlite3_free(pH->ht);
20572  pH->ht = new_ht;
20573  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
20574  memset(new_ht, 0, new_size*sizeof(struct _ht));
20575  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20576    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
20577    next_elem = elem->next;
20578    insertElement(pH, &new_ht[h], elem);
20579  }
20580  return 1;
20581}
20582
20583/* This function (for internal use only) locates an element in an
20584** hash table that matches the given key.  The hash for this key has
20585** already been computed and is passed as the 4th parameter.
20586*/
20587static HashElem *findElementGivenHash(
20588  const Hash *pH,     /* The pH to be searched */
20589  const char *pKey,   /* The key we are searching for */
20590  int nKey,           /* Bytes in key (not counting zero terminator) */
20591  unsigned int h      /* The hash for this key. */
20592){
20593  HashElem *elem;                /* Used to loop thru the element list */
20594  int count;                     /* Number of elements left to test */
20595
20596  if( pH->ht ){
20597    struct _ht *pEntry = &pH->ht[h];
20598    elem = pEntry->chain;
20599    count = pEntry->count;
20600  }else{
20601    elem = pH->first;
20602    count = pH->count;
20603  }
20604  while( count-- && ALWAYS(elem) ){
20605    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
20606      return elem;
20607    }
20608    elem = elem->next;
20609  }
20610  return 0;
20611}
20612
20613/* Remove a single entry from the hash table given a pointer to that
20614** element and a hash on the element's key.
20615*/
20616static void removeElementGivenHash(
20617  Hash *pH,         /* The pH containing "elem" */
20618  HashElem* elem,   /* The element to be removed from the pH */
20619  unsigned int h    /* Hash value for the element */
20620){
20621  struct _ht *pEntry;
20622  if( elem->prev ){
20623    elem->prev->next = elem->next;
20624  }else{
20625    pH->first = elem->next;
20626  }
20627  if( elem->next ){
20628    elem->next->prev = elem->prev;
20629  }
20630  if( pH->ht ){
20631    pEntry = &pH->ht[h];
20632    if( pEntry->chain==elem ){
20633      pEntry->chain = elem->next;
20634    }
20635    pEntry->count--;
20636    assert( pEntry->count>=0 );
20637  }
20638  sqlite3_free( elem );
20639  pH->count--;
20640  if( pH->count<=0 ){
20641    assert( pH->first==0 );
20642    assert( pH->count==0 );
20643    sqlite3HashClear(pH);
20644  }
20645}
20646
20647/* Attempt to locate an element of the hash table pH with a key
20648** that matches pKey,nKey.  Return the data for this element if it is
20649** found, or NULL if there is no match.
20650*/
20651SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
20652  HashElem *elem;    /* The element that matches key */
20653  unsigned int h;    /* A hash on key */
20654
20655  assert( pH!=0 );
20656  assert( pKey!=0 );
20657  assert( nKey>=0 );
20658  if( pH->ht ){
20659    h = strHash(pKey, nKey) % pH->htsize;
20660  }else{
20661    h = 0;
20662  }
20663  elem = findElementGivenHash(pH, pKey, nKey, h);
20664  return elem ? elem->data : 0;
20665}
20666
20667/* Insert an element into the hash table pH.  The key is pKey,nKey
20668** and the data is "data".
20669**
20670** If no element exists with a matching key, then a new
20671** element is created and NULL is returned.
20672**
20673** If another element already exists with the same key, then the
20674** new data replaces the old data and the old data is returned.
20675** The key is not copied in this instance.  If a malloc fails, then
20676** the new data is returned and the hash table is unchanged.
20677**
20678** If the "data" parameter to this function is NULL, then the
20679** element corresponding to "key" is removed from the hash table.
20680*/
20681SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
20682  unsigned int h;       /* the hash of the key modulo hash table size */
20683  HashElem *elem;       /* Used to loop thru the element list */
20684  HashElem *new_elem;   /* New element added to the pH */
20685
20686  assert( pH!=0 );
20687  assert( pKey!=0 );
20688  assert( nKey>=0 );
20689  if( pH->htsize ){
20690    h = strHash(pKey, nKey) % pH->htsize;
20691  }else{
20692    h = 0;
20693  }
20694  elem = findElementGivenHash(pH,pKey,nKey,h);
20695  if( elem ){
20696    void *old_data = elem->data;
20697    if( data==0 ){
20698      removeElementGivenHash(pH,elem,h);
20699    }else{
20700      elem->data = data;
20701      elem->pKey = pKey;
20702      assert(nKey==elem->nKey);
20703    }
20704    return old_data;
20705  }
20706  if( data==0 ) return 0;
20707  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20708  if( new_elem==0 ) return data;
20709  new_elem->pKey = pKey;
20710  new_elem->nKey = nKey;
20711  new_elem->data = data;
20712  pH->count++;
20713  if( pH->count>=10 && pH->count > 2*pH->htsize ){
20714    if( rehash(pH, pH->count*2) ){
20715      assert( pH->htsize>0 );
20716      h = strHash(pKey, nKey) % pH->htsize;
20717    }
20718  }
20719  if( pH->ht ){
20720    insertElement(pH, &pH->ht[h], new_elem);
20721  }else{
20722    insertElement(pH, 0, new_elem);
20723  }
20724  return 0;
20725}
20726
20727/************** End of hash.c ************************************************/
20728/************** Begin file opcodes.c *****************************************/
20729/* Automatically generated.  Do not edit */
20730/* See the mkopcodec.awk script for details. */
20731#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20732SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20733 static const char *const azName[] = { "?",
20734     /*   1 */ "Goto",
20735     /*   2 */ "Gosub",
20736     /*   3 */ "Return",
20737     /*   4 */ "Yield",
20738     /*   5 */ "HaltIfNull",
20739     /*   6 */ "Halt",
20740     /*   7 */ "Integer",
20741     /*   8 */ "Int64",
20742     /*   9 */ "String",
20743     /*  10 */ "Null",
20744     /*  11 */ "Blob",
20745     /*  12 */ "Variable",
20746     /*  13 */ "Move",
20747     /*  14 */ "Copy",
20748     /*  15 */ "SCopy",
20749     /*  16 */ "ResultRow",
20750     /*  17 */ "CollSeq",
20751     /*  18 */ "Function",
20752     /*  19 */ "Not",
20753     /*  20 */ "AddImm",
20754     /*  21 */ "MustBeInt",
20755     /*  22 */ "RealAffinity",
20756     /*  23 */ "Permutation",
20757     /*  24 */ "Compare",
20758     /*  25 */ "Jump",
20759     /*  26 */ "If",
20760     /*  27 */ "IfNot",
20761     /*  28 */ "Column",
20762     /*  29 */ "Affinity",
20763     /*  30 */ "MakeRecord",
20764     /*  31 */ "Count",
20765     /*  32 */ "Savepoint",
20766     /*  33 */ "AutoCommit",
20767     /*  34 */ "Transaction",
20768     /*  35 */ "ReadCookie",
20769     /*  36 */ "SetCookie",
20770     /*  37 */ "VerifyCookie",
20771     /*  38 */ "OpenRead",
20772     /*  39 */ "OpenWrite",
20773     /*  40 */ "OpenAutoindex",
20774     /*  41 */ "OpenEphemeral",
20775     /*  42 */ "OpenPseudo",
20776     /*  43 */ "Close",
20777     /*  44 */ "SeekLt",
20778     /*  45 */ "SeekLe",
20779     /*  46 */ "SeekGe",
20780     /*  47 */ "SeekGt",
20781     /*  48 */ "Seek",
20782     /*  49 */ "NotFound",
20783     /*  50 */ "Found",
20784     /*  51 */ "IsUnique",
20785     /*  52 */ "NotExists",
20786     /*  53 */ "Sequence",
20787     /*  54 */ "NewRowid",
20788     /*  55 */ "Insert",
20789     /*  56 */ "InsertInt",
20790     /*  57 */ "Delete",
20791     /*  58 */ "ResetCount",
20792     /*  59 */ "RowKey",
20793     /*  60 */ "RowData",
20794     /*  61 */ "Rowid",
20795     /*  62 */ "NullRow",
20796     /*  63 */ "Last",
20797     /*  64 */ "Sort",
20798     /*  65 */ "Rewind",
20799     /*  66 */ "Prev",
20800     /*  67 */ "Next",
20801     /*  68 */ "Or",
20802     /*  69 */ "And",
20803     /*  70 */ "IdxInsert",
20804     /*  71 */ "IdxDelete",
20805     /*  72 */ "IdxRowid",
20806     /*  73 */ "IsNull",
20807     /*  74 */ "NotNull",
20808     /*  75 */ "Ne",
20809     /*  76 */ "Eq",
20810     /*  77 */ "Gt",
20811     /*  78 */ "Le",
20812     /*  79 */ "Lt",
20813     /*  80 */ "Ge",
20814     /*  81 */ "IdxLT",
20815     /*  82 */ "BitAnd",
20816     /*  83 */ "BitOr",
20817     /*  84 */ "ShiftLeft",
20818     /*  85 */ "ShiftRight",
20819     /*  86 */ "Add",
20820     /*  87 */ "Subtract",
20821     /*  88 */ "Multiply",
20822     /*  89 */ "Divide",
20823     /*  90 */ "Remainder",
20824     /*  91 */ "Concat",
20825     /*  92 */ "IdxGE",
20826     /*  93 */ "BitNot",
20827     /*  94 */ "String8",
20828     /*  95 */ "Destroy",
20829     /*  96 */ "Clear",
20830     /*  97 */ "CreateIndex",
20831     /*  98 */ "CreateTable",
20832     /*  99 */ "ParseSchema",
20833     /* 100 */ "LoadAnalysis",
20834     /* 101 */ "DropTable",
20835     /* 102 */ "DropIndex",
20836     /* 103 */ "DropTrigger",
20837     /* 104 */ "IntegrityCk",
20838     /* 105 */ "RowSetAdd",
20839     /* 106 */ "RowSetRead",
20840     /* 107 */ "RowSetTest",
20841     /* 108 */ "Program",
20842     /* 109 */ "Param",
20843     /* 110 */ "FkCounter",
20844     /* 111 */ "FkIfZero",
20845     /* 112 */ "MemMax",
20846     /* 113 */ "IfPos",
20847     /* 114 */ "IfNeg",
20848     /* 115 */ "IfZero",
20849     /* 116 */ "AggStep",
20850     /* 117 */ "AggFinal",
20851     /* 118 */ "Checkpoint",
20852     /* 119 */ "JournalMode",
20853     /* 120 */ "Vacuum",
20854     /* 121 */ "IncrVacuum",
20855     /* 122 */ "Expire",
20856     /* 123 */ "TableLock",
20857     /* 124 */ "VBegin",
20858     /* 125 */ "VCreate",
20859     /* 126 */ "VDestroy",
20860     /* 127 */ "VOpen",
20861     /* 128 */ "VFilter",
20862     /* 129 */ "VColumn",
20863     /* 130 */ "Real",
20864     /* 131 */ "VNext",
20865     /* 132 */ "VRename",
20866     /* 133 */ "VUpdate",
20867     /* 134 */ "Pagecount",
20868     /* 135 */ "Trace",
20869     /* 136 */ "Noop",
20870     /* 137 */ "Explain",
20871     /* 138 */ "NotUsed_138",
20872     /* 139 */ "NotUsed_139",
20873     /* 140 */ "NotUsed_140",
20874     /* 141 */ "ToText",
20875     /* 142 */ "ToBlob",
20876     /* 143 */ "ToNumeric",
20877     /* 144 */ "ToInt",
20878     /* 145 */ "ToReal",
20879  };
20880  return azName[i];
20881}
20882#endif
20883
20884/************** End of opcodes.c *********************************************/
20885/************** Begin file os_os2.c ******************************************/
20886/*
20887** 2006 Feb 14
20888**
20889** The author disclaims copyright to this source code.  In place of
20890** a legal notice, here is a blessing:
20891**
20892**    May you do good and not evil.
20893**    May you find forgiveness for yourself and forgive others.
20894**    May you share freely, never taking more than you give.
20895**
20896******************************************************************************
20897**
20898** This file contains code that is specific to OS/2.
20899*/
20900
20901
20902#if SQLITE_OS_OS2
20903
20904/*
20905** A Note About Memory Allocation:
20906**
20907** This driver uses malloc()/free() directly rather than going through
20908** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20909** are designed for use on embedded systems where memory is scarce and
20910** malloc failures happen frequently.  OS/2 does not typically run on
20911** embedded systems, and when it does the developers normally have bigger
20912** problems to worry about than running out of memory.  So there is not
20913** a compelling need to use the wrappers.
20914**
20915** But there is a good reason to not use the wrappers.  If we use the
20916** wrappers then we will get simulated malloc() failures within this
20917** driver.  And that causes all kinds of problems for our tests.  We
20918** could enhance SQLite to deal with simulated malloc failures within
20919** the OS driver, but the code to deal with those failure would not
20920** be exercised on Linux (which does not need to malloc() in the driver)
20921** and so we would have difficulty writing coverage tests for that
20922** code.  Better to leave the code out, we think.
20923**
20924** The point of this discussion is as follows:  When creating a new
20925** OS layer for an embedded system, if you use this file as an example,
20926** avoid the use of malloc()/free().  Those routines work ok on OS/2
20927** desktops but not so well in embedded systems.
20928*/
20929
20930/*
20931** Macros used to determine whether or not to use threads.
20932*/
20933#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20934# define SQLITE_OS2_THREADS 1
20935#endif
20936
20937/*
20938** Include code that is common to all os_*.c files
20939*/
20940/************** Include os_common.h in the middle of os_os2.c ****************/
20941/************** Begin file os_common.h ***************************************/
20942/*
20943** 2004 May 22
20944**
20945** The author disclaims copyright to this source code.  In place of
20946** a legal notice, here is a blessing:
20947**
20948**    May you do good and not evil.
20949**    May you find forgiveness for yourself and forgive others.
20950**    May you share freely, never taking more than you give.
20951**
20952******************************************************************************
20953**
20954** This file contains macros and a little bit of code that is common to
20955** all of the platform-specific files (os_*.c) and is #included into those
20956** files.
20957**
20958** This file should be #included by the os_*.c files only.  It is not a
20959** general purpose header file.
20960*/
20961#ifndef _OS_COMMON_H_
20962#define _OS_COMMON_H_
20963
20964/*
20965** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20966** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20967** switch.  The following code should catch this problem at compile-time.
20968*/
20969#ifdef MEMORY_DEBUG
20970# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20971#endif
20972
20973#ifdef SQLITE_DEBUG
20974SQLITE_PRIVATE int sqlite3OSTrace = 0;
20975#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
20976#else
20977#define OSTRACE(X)
20978#endif
20979
20980/*
20981** Macros for performance tracing.  Normally turned off.  Only works
20982** on i486 hardware.
20983*/
20984#ifdef SQLITE_PERFORMANCE_TRACE
20985
20986/*
20987** hwtime.h contains inline assembler code for implementing
20988** high-performance timing routines.
20989*/
20990/************** Include hwtime.h in the middle of os_common.h ****************/
20991/************** Begin file hwtime.h ******************************************/
20992/*
20993** 2008 May 27
20994**
20995** The author disclaims copyright to this source code.  In place of
20996** a legal notice, here is a blessing:
20997**
20998**    May you do good and not evil.
20999**    May you find forgiveness for yourself and forgive others.
21000**    May you share freely, never taking more than you give.
21001**
21002******************************************************************************
21003**
21004** This file contains inline asm code for retrieving "high-performance"
21005** counters for x86 class CPUs.
21006*/
21007#ifndef _HWTIME_H_
21008#define _HWTIME_H_
21009
21010/*
21011** The following routine only works on pentium-class (or newer) processors.
21012** It uses the RDTSC opcode to read the cycle count value out of the
21013** processor and returns that value.  This can be used for high-res
21014** profiling.
21015*/
21016#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21017      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21018
21019  #if defined(__GNUC__)
21020
21021  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21022     unsigned int lo, hi;
21023     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21024     return (sqlite_uint64)hi << 32 | lo;
21025  }
21026
21027  #elif defined(_MSC_VER)
21028
21029  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21030     __asm {
21031        rdtsc
21032        ret       ; return value at EDX:EAX
21033     }
21034  }
21035
21036  #endif
21037
21038#elif (defined(__GNUC__) && defined(__x86_64__))
21039
21040  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21041      unsigned long val;
21042      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21043      return val;
21044  }
21045
21046#elif (defined(__GNUC__) && defined(__ppc__))
21047
21048  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21049      unsigned long long retval;
21050      unsigned long junk;
21051      __asm__ __volatile__ ("\n\
21052          1:      mftbu   %1\n\
21053                  mftb    %L0\n\
21054                  mftbu   %0\n\
21055                  cmpw    %0,%1\n\
21056                  bne     1b"
21057                  : "=r" (retval), "=r" (junk));
21058      return retval;
21059  }
21060
21061#else
21062
21063  #error Need implementation of sqlite3Hwtime() for your platform.
21064
21065  /*
21066  ** To compile without implementing sqlite3Hwtime() for your platform,
21067  ** you can remove the above #error and use the following
21068  ** stub function.  You will lose timing support for many
21069  ** of the debugging and testing utilities, but it should at
21070  ** least compile and run.
21071  */
21072SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21073
21074#endif
21075
21076#endif /* !defined(_HWTIME_H_) */
21077
21078/************** End of hwtime.h **********************************************/
21079/************** Continuing where we left off in os_common.h ******************/
21080
21081static sqlite_uint64 g_start;
21082static sqlite_uint64 g_elapsed;
21083#define TIMER_START       g_start=sqlite3Hwtime()
21084#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21085#define TIMER_ELAPSED     g_elapsed
21086#else
21087#define TIMER_START
21088#define TIMER_END
21089#define TIMER_ELAPSED     ((sqlite_uint64)0)
21090#endif
21091
21092/*
21093** If we compile with the SQLITE_TEST macro set, then the following block
21094** of code will give us the ability to simulate a disk I/O error.  This
21095** is used for testing the I/O recovery logic.
21096*/
21097#ifdef SQLITE_TEST
21098SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21099SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21100SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21101SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21102SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21103SQLITE_API int sqlite3_diskfull_pending = 0;
21104SQLITE_API int sqlite3_diskfull = 0;
21105#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21106#define SimulateIOError(CODE)  \
21107  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21108       || sqlite3_io_error_pending-- == 1 )  \
21109              { local_ioerr(); CODE; }
21110static void local_ioerr(){
21111  IOTRACE(("IOERR\n"));
21112  sqlite3_io_error_hit++;
21113  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21114}
21115#define SimulateDiskfullError(CODE) \
21116   if( sqlite3_diskfull_pending ){ \
21117     if( sqlite3_diskfull_pending == 1 ){ \
21118       local_ioerr(); \
21119       sqlite3_diskfull = 1; \
21120       sqlite3_io_error_hit = 1; \
21121       CODE; \
21122     }else{ \
21123       sqlite3_diskfull_pending--; \
21124     } \
21125   }
21126#else
21127#define SimulateIOErrorBenign(X)
21128#define SimulateIOError(A)
21129#define SimulateDiskfullError(A)
21130#endif
21131
21132/*
21133** When testing, keep a count of the number of open files.
21134*/
21135#ifdef SQLITE_TEST
21136SQLITE_API int sqlite3_open_file_count = 0;
21137#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21138#else
21139#define OpenCounter(X)
21140#endif
21141
21142#endif /* !defined(_OS_COMMON_H_) */
21143
21144/************** End of os_common.h *******************************************/
21145/************** Continuing where we left off in os_os2.c *********************/
21146
21147/*
21148** The os2File structure is subclass of sqlite3_file specific for the OS/2
21149** protability layer.
21150*/
21151typedef struct os2File os2File;
21152struct os2File {
21153  const sqlite3_io_methods *pMethod;  /* Always the first entry */
21154  HFILE h;                  /* Handle for accessing the file */
21155  char* pathToDel;          /* Name of file to delete on close, NULL if not */
21156  unsigned char locktype;   /* Type of lock currently held on this file */
21157};
21158
21159#define LOCK_TIMEOUT 10L /* the default locking timeout */
21160
21161/*****************************************************************************
21162** The next group of routines implement the I/O methods specified
21163** by the sqlite3_io_methods object.
21164******************************************************************************/
21165
21166/*
21167** Close a file.
21168*/
21169static int os2Close( sqlite3_file *id ){
21170  APIRET rc = NO_ERROR;
21171  os2File *pFile;
21172  if( id && (pFile = (os2File*)id) != 0 ){
21173    OSTRACE(( "CLOSE %d\n", pFile->h ));
21174    rc = DosClose( pFile->h );
21175    pFile->locktype = NO_LOCK;
21176    if( pFile->pathToDel != NULL ){
21177      rc = DosForceDelete( (PSZ)pFile->pathToDel );
21178      free( pFile->pathToDel );
21179      pFile->pathToDel = NULL;
21180    }
21181    id = 0;
21182    OpenCounter( -1 );
21183  }
21184
21185  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21186}
21187
21188/*
21189** Read data from a file into a buffer.  Return SQLITE_OK if all
21190** bytes were read successfully and SQLITE_IOERR if anything goes
21191** wrong.
21192*/
21193static int os2Read(
21194  sqlite3_file *id,               /* File to read from */
21195  void *pBuf,                     /* Write content into this buffer */
21196  int amt,                        /* Number of bytes to read */
21197  sqlite3_int64 offset            /* Begin reading at this offset */
21198){
21199  ULONG fileLocation = 0L;
21200  ULONG got;
21201  os2File *pFile = (os2File*)id;
21202  assert( id!=0 );
21203  SimulateIOError( return SQLITE_IOERR_READ );
21204  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21205  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21206    return SQLITE_IOERR;
21207  }
21208  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21209    return SQLITE_IOERR_READ;
21210  }
21211  if( got == (ULONG)amt )
21212    return SQLITE_OK;
21213  else {
21214    /* Unread portions of the input buffer must be zero-filled */
21215    memset(&((char*)pBuf)[got], 0, amt-got);
21216    return SQLITE_IOERR_SHORT_READ;
21217  }
21218}
21219
21220/*
21221** Write data from a buffer into a file.  Return SQLITE_OK on success
21222** or some other error code on failure.
21223*/
21224static int os2Write(
21225  sqlite3_file *id,               /* File to write into */
21226  const void *pBuf,               /* The bytes to be written */
21227  int amt,                        /* Number of bytes to write */
21228  sqlite3_int64 offset            /* Offset into the file to begin writing at */
21229){
21230  ULONG fileLocation = 0L;
21231  APIRET rc = NO_ERROR;
21232  ULONG wrote;
21233  os2File *pFile = (os2File*)id;
21234  assert( id!=0 );
21235  SimulateIOError( return SQLITE_IOERR_WRITE );
21236  SimulateDiskfullError( return SQLITE_FULL );
21237  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21238  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21239    return SQLITE_IOERR;
21240  }
21241  assert( amt>0 );
21242  while( amt > 0 &&
21243         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21244         wrote > 0
21245  ){
21246    amt -= wrote;
21247    pBuf = &((char*)pBuf)[wrote];
21248  }
21249
21250  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21251}
21252
21253/*
21254** Truncate an open file to a specified size
21255*/
21256static int os2Truncate( sqlite3_file *id, i64 nByte ){
21257  APIRET rc = NO_ERROR;
21258  os2File *pFile = (os2File*)id;
21259  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21260  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21261  rc = DosSetFileSize( pFile->h, nByte );
21262  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21263}
21264
21265#ifdef SQLITE_TEST
21266/*
21267** Count the number of fullsyncs and normal syncs.  This is used to test
21268** that syncs and fullsyncs are occuring at the right times.
21269*/
21270SQLITE_API int sqlite3_sync_count = 0;
21271SQLITE_API int sqlite3_fullsync_count = 0;
21272#endif
21273
21274/*
21275** Make sure all writes to a particular file are committed to disk.
21276*/
21277static int os2Sync( sqlite3_file *id, int flags ){
21278  os2File *pFile = (os2File*)id;
21279  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21280#ifdef SQLITE_TEST
21281  if( flags & SQLITE_SYNC_FULL){
21282    sqlite3_fullsync_count++;
21283  }
21284  sqlite3_sync_count++;
21285#endif
21286  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21287  ** no-op
21288  */
21289#ifdef SQLITE_NO_SYNC
21290  UNUSED_PARAMETER(pFile);
21291  return SQLITE_OK;
21292#else
21293  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21294#endif
21295}
21296
21297/*
21298** Determine the current size of a file in bytes
21299*/
21300static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21301  APIRET rc = NO_ERROR;
21302  FILESTATUS3 fsts3FileInfo;
21303  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21304  assert( id!=0 );
21305  SimulateIOError( return SQLITE_IOERR_FSTAT );
21306  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21307  if( rc == NO_ERROR ){
21308    *pSize = fsts3FileInfo.cbFile;
21309    return SQLITE_OK;
21310  }else{
21311    return SQLITE_IOERR_FSTAT;
21312  }
21313}
21314
21315/*
21316** Acquire a reader lock.
21317*/
21318static int getReadLock( os2File *pFile ){
21319  FILELOCK  LockArea,
21320            UnlockArea;
21321  APIRET res;
21322  memset(&LockArea, 0, sizeof(LockArea));
21323  memset(&UnlockArea, 0, sizeof(UnlockArea));
21324  LockArea.lOffset = SHARED_FIRST;
21325  LockArea.lRange = SHARED_SIZE;
21326  UnlockArea.lOffset = 0L;
21327  UnlockArea.lRange = 0L;
21328  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21329  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21330  return res;
21331}
21332
21333/*
21334** Undo a readlock
21335*/
21336static int unlockReadLock( os2File *id ){
21337  FILELOCK  LockArea,
21338            UnlockArea;
21339  APIRET res;
21340  memset(&LockArea, 0, sizeof(LockArea));
21341  memset(&UnlockArea, 0, sizeof(UnlockArea));
21342  LockArea.lOffset = 0L;
21343  LockArea.lRange = 0L;
21344  UnlockArea.lOffset = SHARED_FIRST;
21345  UnlockArea.lRange = SHARED_SIZE;
21346  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21347  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21348  return res;
21349}
21350
21351/*
21352** Lock the file with the lock specified by parameter locktype - one
21353** of the following:
21354**
21355**     (1) SHARED_LOCK
21356**     (2) RESERVED_LOCK
21357**     (3) PENDING_LOCK
21358**     (4) EXCLUSIVE_LOCK
21359**
21360** Sometimes when requesting one lock state, additional lock states
21361** are inserted in between.  The locking might fail on one of the later
21362** transitions leaving the lock state different from what it started but
21363** still short of its goal.  The following chart shows the allowed
21364** transitions and the inserted intermediate states:
21365**
21366**    UNLOCKED -> SHARED
21367**    SHARED -> RESERVED
21368**    SHARED -> (PENDING) -> EXCLUSIVE
21369**    RESERVED -> (PENDING) -> EXCLUSIVE
21370**    PENDING -> EXCLUSIVE
21371**
21372** This routine will only increase a lock.  The os2Unlock() routine
21373** erases all locks at once and returns us immediately to locking level 0.
21374** It is not possible to lower the locking level one step at a time.  You
21375** must go straight to locking level 0.
21376*/
21377static int os2Lock( sqlite3_file *id, int locktype ){
21378  int rc = SQLITE_OK;       /* Return code from subroutines */
21379  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21380  int newLocktype;       /* Set pFile->locktype to this value before exiting */
21381  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21382  FILELOCK  LockArea,
21383            UnlockArea;
21384  os2File *pFile = (os2File*)id;
21385  memset(&LockArea, 0, sizeof(LockArea));
21386  memset(&UnlockArea, 0, sizeof(UnlockArea));
21387  assert( pFile!=0 );
21388  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21389
21390  /* If there is already a lock of this type or more restrictive on the
21391  ** os2File, do nothing. Don't use the end_lock: exit path, as
21392  ** sqlite3_mutex_enter() hasn't been called yet.
21393  */
21394  if( pFile->locktype>=locktype ){
21395    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21396    return SQLITE_OK;
21397  }
21398
21399  /* Make sure the locking sequence is correct
21400  */
21401  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21402  assert( locktype!=PENDING_LOCK );
21403  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21404
21405  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21406  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21407  ** the PENDING_LOCK byte is temporary.
21408  */
21409  newLocktype = pFile->locktype;
21410  if( pFile->locktype==NO_LOCK
21411      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21412  ){
21413    LockArea.lOffset = PENDING_BYTE;
21414    LockArea.lRange = 1L;
21415    UnlockArea.lOffset = 0L;
21416    UnlockArea.lRange = 0L;
21417
21418    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21419    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21420    if( res == NO_ERROR ){
21421      gotPendingLock = 1;
21422      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21423    }
21424  }
21425
21426  /* Acquire a shared lock
21427  */
21428  if( locktype==SHARED_LOCK && res == NO_ERROR ){
21429    assert( pFile->locktype==NO_LOCK );
21430    res = getReadLock(pFile);
21431    if( res == NO_ERROR ){
21432      newLocktype = SHARED_LOCK;
21433    }
21434    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21435  }
21436
21437  /* Acquire a RESERVED lock
21438  */
21439  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21440    assert( pFile->locktype==SHARED_LOCK );
21441    LockArea.lOffset = RESERVED_BYTE;
21442    LockArea.lRange = 1L;
21443    UnlockArea.lOffset = 0L;
21444    UnlockArea.lRange = 0L;
21445    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21446    if( res == NO_ERROR ){
21447      newLocktype = RESERVED_LOCK;
21448    }
21449    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21450  }
21451
21452  /* Acquire a PENDING lock
21453  */
21454  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21455    newLocktype = PENDING_LOCK;
21456    gotPendingLock = 0;
21457    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21458               pFile->h ));
21459  }
21460
21461  /* Acquire an EXCLUSIVE lock
21462  */
21463  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21464    assert( pFile->locktype>=SHARED_LOCK );
21465    res = unlockReadLock(pFile);
21466    OSTRACE(( "unreadlock = %d\n", res ));
21467    LockArea.lOffset = SHARED_FIRST;
21468    LockArea.lRange = SHARED_SIZE;
21469    UnlockArea.lOffset = 0L;
21470    UnlockArea.lRange = 0L;
21471    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21472    if( res == NO_ERROR ){
21473      newLocktype = EXCLUSIVE_LOCK;
21474    }else{
21475      OSTRACE(( "OS/2 error-code = %d\n", res ));
21476      getReadLock(pFile);
21477    }
21478    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21479  }
21480
21481  /* If we are holding a PENDING lock that ought to be released, then
21482  ** release it now.
21483  */
21484  if( gotPendingLock && locktype==SHARED_LOCK ){
21485    int r;
21486    LockArea.lOffset = 0L;
21487    LockArea.lRange = 0L;
21488    UnlockArea.lOffset = PENDING_BYTE;
21489    UnlockArea.lRange = 1L;
21490    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21491    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21492  }
21493
21494  /* Update the state of the lock has held in the file descriptor then
21495  ** return the appropriate result code.
21496  */
21497  if( res == NO_ERROR ){
21498    rc = SQLITE_OK;
21499  }else{
21500    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21501              locktype, newLocktype ));
21502    rc = SQLITE_BUSY;
21503  }
21504  pFile->locktype = newLocktype;
21505  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21506  return rc;
21507}
21508
21509/*
21510** This routine checks if there is a RESERVED lock held on the specified
21511** file by this or any other process. If such a lock is held, return
21512** non-zero, otherwise zero.
21513*/
21514static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21515  int r = 0;
21516  os2File *pFile = (os2File*)id;
21517  assert( pFile!=0 );
21518  if( pFile->locktype>=RESERVED_LOCK ){
21519    r = 1;
21520    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21521  }else{
21522    FILELOCK  LockArea,
21523              UnlockArea;
21524    APIRET rc = NO_ERROR;
21525    memset(&LockArea, 0, sizeof(LockArea));
21526    memset(&UnlockArea, 0, sizeof(UnlockArea));
21527    LockArea.lOffset = RESERVED_BYTE;
21528    LockArea.lRange = 1L;
21529    UnlockArea.lOffset = 0L;
21530    UnlockArea.lRange = 0L;
21531    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21532    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21533    if( rc == NO_ERROR ){
21534      APIRET rcu = NO_ERROR; /* return code for unlocking */
21535      LockArea.lOffset = 0L;
21536      LockArea.lRange = 0L;
21537      UnlockArea.lOffset = RESERVED_BYTE;
21538      UnlockArea.lRange = 1L;
21539      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21540      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
21541    }
21542    r = !(rc == NO_ERROR);
21543    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
21544  }
21545  *pOut = r;
21546  return SQLITE_OK;
21547}
21548
21549/*
21550** Lower the locking level on file descriptor id to locktype.  locktype
21551** must be either NO_LOCK or SHARED_LOCK.
21552**
21553** If the locking level of the file descriptor is already at or below
21554** the requested locking level, this routine is a no-op.
21555**
21556** It is not possible for this routine to fail if the second argument
21557** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21558** might return SQLITE_IOERR;
21559*/
21560static int os2Unlock( sqlite3_file *id, int locktype ){
21561  int type;
21562  os2File *pFile = (os2File*)id;
21563  APIRET rc = SQLITE_OK;
21564  APIRET res = NO_ERROR;
21565  FILELOCK  LockArea,
21566            UnlockArea;
21567  memset(&LockArea, 0, sizeof(LockArea));
21568  memset(&UnlockArea, 0, sizeof(UnlockArea));
21569  assert( pFile!=0 );
21570  assert( locktype<=SHARED_LOCK );
21571  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
21572  type = pFile->locktype;
21573  if( type>=EXCLUSIVE_LOCK ){
21574    LockArea.lOffset = 0L;
21575    LockArea.lRange = 0L;
21576    UnlockArea.lOffset = SHARED_FIRST;
21577    UnlockArea.lRange = SHARED_SIZE;
21578    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21579    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
21580    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21581      /* This should never happen.  We should always be able to
21582      ** reacquire the read lock */
21583      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
21584      rc = SQLITE_IOERR_UNLOCK;
21585    }
21586  }
21587  if( type>=RESERVED_LOCK ){
21588    LockArea.lOffset = 0L;
21589    LockArea.lRange = 0L;
21590    UnlockArea.lOffset = RESERVED_BYTE;
21591    UnlockArea.lRange = 1L;
21592    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21593    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
21594  }
21595  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21596    res = unlockReadLock(pFile);
21597    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
21598              pFile->h, type, locktype, res ));
21599  }
21600  if( type>=PENDING_LOCK ){
21601    LockArea.lOffset = 0L;
21602    LockArea.lRange = 0L;
21603    UnlockArea.lOffset = PENDING_BYTE;
21604    UnlockArea.lRange = 1L;
21605    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21606    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
21607  }
21608  pFile->locktype = locktype;
21609  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
21610  return rc;
21611}
21612
21613/*
21614** Control and query of the open file handle.
21615*/
21616static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21617  switch( op ){
21618    case SQLITE_FCNTL_LOCKSTATE: {
21619      *(int*)pArg = ((os2File*)id)->locktype;
21620      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
21621                ((os2File*)id)->h, ((os2File*)id)->locktype ));
21622      return SQLITE_OK;
21623    }
21624  }
21625  return SQLITE_ERROR;
21626}
21627
21628/*
21629** Return the sector size in bytes of the underlying block device for
21630** the specified file. This is almost always 512 bytes, but may be
21631** larger for some devices.
21632**
21633** SQLite code assumes this function cannot fail. It also assumes that
21634** if two files are created in the same file-system directory (i.e.
21635** a database and its journal file) that the sector size will be the
21636** same for both.
21637*/
21638static int os2SectorSize(sqlite3_file *id){
21639  return SQLITE_DEFAULT_SECTOR_SIZE;
21640}
21641
21642/*
21643** Return a vector of device characteristics.
21644*/
21645static int os2DeviceCharacteristics(sqlite3_file *id){
21646  return 0;
21647}
21648
21649
21650/*
21651** Character set conversion objects used by conversion routines.
21652*/
21653static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21654static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21655
21656/*
21657** Helper function to initialize the conversion objects from and to UTF-8.
21658*/
21659static void initUconvObjects( void ){
21660  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21661    ucUtf8 = NULL;
21662  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21663    uclCp = NULL;
21664}
21665
21666/*
21667** Helper function to free the conversion objects from and to UTF-8.
21668*/
21669static void freeUconvObjects( void ){
21670  if ( ucUtf8 )
21671    UniFreeUconvObject( ucUtf8 );
21672  if ( uclCp )
21673    UniFreeUconvObject( uclCp );
21674  ucUtf8 = NULL;
21675  uclCp = NULL;
21676}
21677
21678/*
21679** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21680** The two-step process: first convert the incoming UTF-8 string
21681** into UCS-2 and then from UCS-2 to the current codepage.
21682** The returned char pointer has to be freed.
21683*/
21684static char *convertUtf8PathToCp( const char *in ){
21685  UniChar tempPath[CCHMAXPATH];
21686  char *out = (char *)calloc( CCHMAXPATH, 1 );
21687
21688  if( !out )
21689    return NULL;
21690
21691  if( !ucUtf8 || !uclCp )
21692    initUconvObjects();
21693
21694  /* determine string for the conversion of UTF-8 which is CP1208 */
21695  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21696    return out; /* if conversion fails, return the empty string */
21697
21698  /* conversion for current codepage which can be used for paths */
21699  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21700
21701  return out;
21702}
21703
21704/*
21705** Helper function to convert filenames from local codepage to UTF-8.
21706** The two-step process: first convert the incoming codepage-specific
21707** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21708** The returned char pointer has to be freed.
21709**
21710** This function is non-static to be able to use this in shell.c and
21711** similar applications that take command line arguments.
21712*/
21713char *convertCpPathToUtf8( const char *in ){
21714  UniChar tempPath[CCHMAXPATH];
21715  char *out = (char *)calloc( CCHMAXPATH, 1 );
21716
21717  if( !out )
21718    return NULL;
21719
21720  if( !ucUtf8 || !uclCp )
21721    initUconvObjects();
21722
21723  /* conversion for current codepage which can be used for paths */
21724  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21725    return out; /* if conversion fails, return the empty string */
21726
21727  /* determine string for the conversion of UTF-8 which is CP1208 */
21728  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21729
21730  return out;
21731}
21732
21733/*
21734** This vector defines all the methods that can operate on an
21735** sqlite3_file for os2.
21736*/
21737static const sqlite3_io_methods os2IoMethod = {
21738  1,                        /* iVersion */
21739  os2Close,
21740  os2Read,
21741  os2Write,
21742  os2Truncate,
21743  os2Sync,
21744  os2FileSize,
21745  os2Lock,
21746  os2Unlock,
21747  os2CheckReservedLock,
21748  os2FileControl,
21749  os2SectorSize,
21750  os2DeviceCharacteristics
21751};
21752
21753/***************************************************************************
21754** Here ends the I/O methods that form the sqlite3_io_methods object.
21755**
21756** The next block of code implements the VFS methods.
21757****************************************************************************/
21758
21759/*
21760** Create a temporary file name in zBuf.  zBuf must be big enough to
21761** hold at pVfs->mxPathname characters.
21762*/
21763static int getTempname(int nBuf, char *zBuf ){
21764  static const unsigned char zChars[] =
21765    "abcdefghijklmnopqrstuvwxyz"
21766    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21767    "0123456789";
21768  int i, j;
21769  char zTempPathBuf[3];
21770  PSZ zTempPath = (PSZ)&zTempPathBuf;
21771  if( sqlite3_temp_directory ){
21772    zTempPath = sqlite3_temp_directory;
21773  }else{
21774    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21775      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21776        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21777           ULONG ulDriveNum = 0, ulDriveMap = 0;
21778           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21779           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21780        }
21781      }
21782    }
21783  }
21784  /* Strip off a trailing slashes or backslashes, otherwise we would get *
21785   * multiple (back)slashes which causes DosOpen() to fail.              *
21786   * Trailing spaces are not allowed, either.                            */
21787  j = sqlite3Strlen30(zTempPath);
21788  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21789                    || zTempPath[j-1] == ' ' ) ){
21790    j--;
21791  }
21792  zTempPath[j] = '\0';
21793  if( !sqlite3_temp_directory ){
21794    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21795    sqlite3_snprintf( nBuf-30, zBuf,
21796                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21797    free( zTempPathUTF );
21798  }else{
21799    sqlite3_snprintf( nBuf-30, zBuf,
21800                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21801  }
21802  j = sqlite3Strlen30( zBuf );
21803  sqlite3_randomness( 20, &zBuf[j] );
21804  for( i = 0; i < 20; i++, j++ ){
21805    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21806  }
21807  zBuf[j] = 0;
21808  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
21809  return SQLITE_OK;
21810}
21811
21812
21813/*
21814** Turn a relative pathname into a full pathname.  Write the full
21815** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21816** bytes in size.
21817*/
21818static int os2FullPathname(
21819  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21820  const char *zRelative,      /* Possibly relative input path */
21821  int nFull,                  /* Size of output buffer in bytes */
21822  char *zFull                 /* Output buffer */
21823){
21824  char *zRelativeCp = convertUtf8PathToCp( zRelative );
21825  char zFullCp[CCHMAXPATH] = "\0";
21826  char *zFullUTF;
21827  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21828                                CCHMAXPATH );
21829  free( zRelativeCp );
21830  zFullUTF = convertCpPathToUtf8( zFullCp );
21831  sqlite3_snprintf( nFull, zFull, zFullUTF );
21832  free( zFullUTF );
21833  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21834}
21835
21836
21837/*
21838** Open a file.
21839*/
21840static int os2Open(
21841  sqlite3_vfs *pVfs,            /* Not used */
21842  const char *zName,            /* Name of the file */
21843  sqlite3_file *id,             /* Write the SQLite file handle here */
21844  int flags,                    /* Open mode flags */
21845  int *pOutFlags                /* Status return flags */
21846){
21847  HFILE h;
21848  ULONG ulFileAttribute = FILE_NORMAL;
21849  ULONG ulOpenFlags = 0;
21850  ULONG ulOpenMode = 0;
21851  os2File *pFile = (os2File*)id;
21852  APIRET rc = NO_ERROR;
21853  ULONG ulAction;
21854  char *zNameCp;
21855  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21856
21857  /* If the second argument to this function is NULL, generate a
21858  ** temporary file name to use
21859  */
21860  if( !zName ){
21861    int rc = getTempname(CCHMAXPATH+1, zTmpname);
21862    if( rc!=SQLITE_OK ){
21863      return rc;
21864    }
21865    zName = zTmpname;
21866  }
21867
21868
21869  memset( pFile, 0, sizeof(*pFile) );
21870
21871  OSTRACE( "OPEN want %d\n", flags ));
21872
21873  if( flags & SQLITE_OPEN_READWRITE ){
21874    ulOpenMode |= OPEN_ACCESS_READWRITE;
21875    OSTRACE(( "OPEN read/write\n" ));
21876  }else{
21877    ulOpenMode |= OPEN_ACCESS_READONLY;
21878    OSTRACE(( "OPEN read only\n" ));
21879  }
21880
21881  if( flags & SQLITE_OPEN_CREATE ){
21882    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21883    OSTRACE(( "OPEN open new/create\n" ));
21884  }else{
21885    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21886    OSTRACE(( "OPEN open existing\n" ));
21887  }
21888
21889  if( flags & SQLITE_OPEN_MAIN_DB ){
21890    ulOpenMode |= OPEN_SHARE_DENYNONE;
21891    OSTRACE(( "OPEN share read/write\n" ));
21892  }else{
21893    ulOpenMode |= OPEN_SHARE_DENYWRITE;
21894    OSTRACE(( "OPEN share read only\n" ));
21895  }
21896
21897  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21898    char pathUtf8[CCHMAXPATH];
21899#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21900    ulFileAttribute = FILE_HIDDEN;
21901#endif
21902    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21903    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21904    OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
21905  }else{
21906    pFile->pathToDel = NULL;
21907    OSTRACE(( "OPEN normal file attribute\n" ));
21908  }
21909
21910  /* always open in random access mode for possibly better speed */
21911  ulOpenMode |= OPEN_FLAGS_RANDOM;
21912  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21913  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21914
21915  zNameCp = convertUtf8PathToCp( zName );
21916  rc = DosOpen( (PSZ)zNameCp,
21917                &h,
21918                &ulAction,
21919                0L,
21920                ulFileAttribute,
21921                ulOpenFlags,
21922                ulOpenMode,
21923                (PEAOP2)NULL );
21924  free( zNameCp );
21925  if( rc != NO_ERROR ){
21926    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21927              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
21928    if( pFile->pathToDel )
21929      free( pFile->pathToDel );
21930    pFile->pathToDel = NULL;
21931    if( flags & SQLITE_OPEN_READWRITE ){
21932      OSTRACE(( "OPEN %d Invalid handle\n",
21933                ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
21934      return os2Open( pVfs, zName, id,
21935                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21936                      pOutFlags );
21937    }else{
21938      return SQLITE_CANTOPEN;
21939    }
21940  }
21941
21942  if( pOutFlags ){
21943    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21944  }
21945
21946  pFile->pMethod = &os2IoMethod;
21947  pFile->h = h;
21948  OpenCounter(+1);
21949  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
21950  return SQLITE_OK;
21951}
21952
21953/*
21954** Delete the named file.
21955*/
21956static int os2Delete(
21957  sqlite3_vfs *pVfs,                     /* Not used on os2 */
21958  const char *zFilename,                 /* Name of file to delete */
21959  int syncDir                            /* Not used on os2 */
21960){
21961  APIRET rc = NO_ERROR;
21962  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21963  SimulateIOError( return SQLITE_IOERR_DELETE );
21964  rc = DosDelete( (PSZ)zFilenameCp );
21965  free( zFilenameCp );
21966  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
21967  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21968}
21969
21970/*
21971** Check the existance and status of a file.
21972*/
21973static int os2Access(
21974  sqlite3_vfs *pVfs,        /* Not used on os2 */
21975  const char *zFilename,    /* Name of file to check */
21976  int flags,                /* Type of test to make on this file */
21977  int *pOut                 /* Write results here */
21978){
21979  FILESTATUS3 fsts3ConfigInfo;
21980  APIRET rc = NO_ERROR;
21981  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21982
21983  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21984  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21985                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21986  free( zFilenameCp );
21987  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21988            fsts3ConfigInfo.attrFile, flags, rc ));
21989  switch( flags ){
21990    case SQLITE_ACCESS_READ:
21991    case SQLITE_ACCESS_EXISTS:
21992      rc = (rc == NO_ERROR);
21993      OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
21994      break;
21995    case SQLITE_ACCESS_READWRITE:
21996      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21997      OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
21998      break;
21999    default:
22000      assert( !"Invalid flags argument" );
22001  }
22002  *pOut = rc;
22003  return SQLITE_OK;
22004}
22005
22006
22007#ifndef SQLITE_OMIT_LOAD_EXTENSION
22008/*
22009** Interfaces for opening a shared library, finding entry points
22010** within the shared library, and closing the shared library.
22011*/
22012/*
22013** Interfaces for opening a shared library, finding entry points
22014** within the shared library, and closing the shared library.
22015*/
22016static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22017  UCHAR loadErr[256];
22018  HMODULE hmod;
22019  APIRET rc;
22020  char *zFilenameCp = convertUtf8PathToCp(zFilename);
22021  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22022  free(zFilenameCp);
22023  return rc != NO_ERROR ? 0 : (void*)hmod;
22024}
22025/*
22026** A no-op since the error code is returned on the DosLoadModule call.
22027** os2Dlopen returns zero if DosLoadModule is not successful.
22028*/
22029static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22030/* no-op */
22031}
22032static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22033  PFN pfn;
22034  APIRET rc;
22035  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22036  if( rc != NO_ERROR ){
22037    /* if the symbol itself was not found, search again for the same
22038     * symbol with an extra underscore, that might be needed depending
22039     * on the calling convention */
22040    char _zSymbol[256] = "_";
22041    strncat(_zSymbol, zSymbol, 255);
22042    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22043  }
22044  return rc != NO_ERROR ? 0 : (void*)pfn;
22045}
22046static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22047  DosFreeModule((HMODULE)pHandle);
22048}
22049#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22050  #define os2DlOpen 0
22051  #define os2DlError 0
22052  #define os2DlSym 0
22053  #define os2DlClose 0
22054#endif
22055
22056
22057/*
22058** Write up to nBuf bytes of randomness into zBuf.
22059*/
22060static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22061  int n = 0;
22062#if defined(SQLITE_TEST)
22063  n = nBuf;
22064  memset(zBuf, 0, nBuf);
22065#else
22066  int sizeofULong = sizeof(ULONG);
22067  if( (int)sizeof(DATETIME) <= nBuf - n ){
22068    DATETIME x;
22069    DosGetDateTime(&x);
22070    memcpy(&zBuf[n], &x, sizeof(x));
22071    n += sizeof(x);
22072  }
22073
22074  if( sizeofULong <= nBuf - n ){
22075    PPIB ppib;
22076    DosGetInfoBlocks(NULL, &ppib);
22077    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22078    n += sizeofULong;
22079  }
22080
22081  if( sizeofULong <= nBuf - n ){
22082    PTIB ptib;
22083    DosGetInfoBlocks(&ptib, NULL);
22084    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22085    n += sizeofULong;
22086  }
22087
22088  /* if we still haven't filled the buffer yet the following will */
22089  /* grab everything once instead of making several calls for a single item */
22090  if( sizeofULong <= nBuf - n ){
22091    ULONG ulSysInfo[QSV_MAX];
22092    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22093
22094    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22095    n += sizeofULong;
22096
22097    if( sizeofULong <= nBuf - n ){
22098      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22099      n += sizeofULong;
22100    }
22101    if( sizeofULong <= nBuf - n ){
22102      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22103      n += sizeofULong;
22104    }
22105    if( sizeofULong <= nBuf - n ){
22106      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22107      n += sizeofULong;
22108    }
22109    if( sizeofULong <= nBuf - n ){
22110      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22111      n += sizeofULong;
22112    }
22113  }
22114#endif
22115
22116  return n;
22117}
22118
22119/*
22120** Sleep for a little while.  Return the amount of time slept.
22121** The argument is the number of microseconds we want to sleep.
22122** The return value is the number of microseconds of sleep actually
22123** requested from the underlying operating system, a number which
22124** might be greater than or equal to the argument, but not less
22125** than the argument.
22126*/
22127static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22128  DosSleep( (microsec/1000) );
22129  return microsec;
22130}
22131
22132/*
22133** The following variable, if set to a non-zero value, becomes the result
22134** returned from sqlite3OsCurrentTime().  This is used for testing.
22135*/
22136#ifdef SQLITE_TEST
22137SQLITE_API int sqlite3_current_time = 0;
22138#endif
22139
22140/*
22141** Find the current time (in Universal Coordinated Time).  Write the
22142** current time and date as a Julian Day number into *prNow and
22143** return 0.  Return 1 if the time and date cannot be found.
22144*/
22145int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22146  double now;
22147  SHORT minute; /* needs to be able to cope with negative timezone offset */
22148  USHORT second, hour,
22149         day, month, year;
22150  DATETIME dt;
22151  DosGetDateTime( &dt );
22152  second = (USHORT)dt.seconds;
22153  minute = (SHORT)dt.minutes + dt.timezone;
22154  hour = (USHORT)dt.hours;
22155  day = (USHORT)dt.day;
22156  month = (USHORT)dt.month;
22157  year = (USHORT)dt.year;
22158
22159  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22160     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22161  /* Calculate the Julian days */
22162  now = day - 32076 +
22163    1461*(year + 4800 + (month - 14)/12)/4 +
22164    367*(month - 2 - (month - 14)/12*12)/12 -
22165    3*((year + 4900 + (month - 14)/12)/100)/4;
22166
22167  /* Add the fractional hours, mins and seconds */
22168  now += (hour + 12.0)/24.0;
22169  now += minute/1440.0;
22170  now += second/86400.0;
22171  *prNow = now;
22172#ifdef SQLITE_TEST
22173  if( sqlite3_current_time ){
22174    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22175  }
22176#endif
22177  return 0;
22178}
22179
22180static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22181  return 0;
22182}
22183
22184/*
22185** Initialize and deinitialize the operating system interface.
22186*/
22187SQLITE_API int sqlite3_os_init(void){
22188  static sqlite3_vfs os2Vfs = {
22189    1,                 /* iVersion */
22190    sizeof(os2File),   /* szOsFile */
22191    CCHMAXPATH,        /* mxPathname */
22192    0,                 /* pNext */
22193    "os2",             /* zName */
22194    0,                 /* pAppData */
22195
22196    os2Open,           /* xOpen */
22197    os2Delete,         /* xDelete */
22198    os2Access,         /* xAccess */
22199    os2FullPathname,   /* xFullPathname */
22200    os2DlOpen,         /* xDlOpen */
22201    os2DlError,        /* xDlError */
22202    os2DlSym,          /* xDlSym */
22203    os2DlClose,        /* xDlClose */
22204    os2Randomness,     /* xRandomness */
22205    os2Sleep,          /* xSleep */
22206    os2CurrentTime,    /* xCurrentTime */
22207    os2GetLastError,   /* xGetLastError */
22208  };
22209  sqlite3_vfs_register(&os2Vfs, 1);
22210  initUconvObjects();
22211  return SQLITE_OK;
22212}
22213SQLITE_API int sqlite3_os_end(void){
22214  freeUconvObjects();
22215  return SQLITE_OK;
22216}
22217
22218#endif /* SQLITE_OS_OS2 */
22219
22220/************** End of os_os2.c **********************************************/
22221/************** Begin file os_unix.c *****************************************/
22222/*
22223** 2004 May 22
22224**
22225** The author disclaims copyright to this source code.  In place of
22226** a legal notice, here is a blessing:
22227**
22228**    May you do good and not evil.
22229**    May you find forgiveness for yourself and forgive others.
22230**    May you share freely, never taking more than you give.
22231**
22232******************************************************************************
22233**
22234** This file contains the VFS implementation for unix-like operating systems
22235** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22236**
22237** There are actually several different VFS implementations in this file.
22238** The differences are in the way that file locking is done.  The default
22239** implementation uses Posix Advisory Locks.  Alternative implementations
22240** use flock(), dot-files, various proprietary locking schemas, or simply
22241** skip locking all together.
22242**
22243** This source file is organized into divisions where the logic for various
22244** subfunctions is contained within the appropriate division.  PLEASE
22245** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22246** in the correct division and should be clearly labeled.
22247**
22248** The layout of divisions is as follows:
22249**
22250**   *  General-purpose declarations and utility functions.
22251**   *  Unique file ID logic used by VxWorks.
22252**   *  Various locking primitive implementations (all except proxy locking):
22253**      + for Posix Advisory Locks
22254**      + for no-op locks
22255**      + for dot-file locks
22256**      + for flock() locking
22257**      + for named semaphore locks (VxWorks only)
22258**      + for AFP filesystem locks (MacOSX only)
22259**   *  sqlite3_file methods not associated with locking.
22260**   *  Definitions of sqlite3_io_methods objects for all locking
22261**      methods plus "finder" functions for each locking method.
22262**   *  sqlite3_vfs method implementations.
22263**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22264**   *  Definitions of sqlite3_vfs objects for all locking methods
22265**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22266*/
22267#if SQLITE_OS_UNIX              /* This file is used on unix only */
22268
22269/*
22270** There are various methods for file locking used for concurrency
22271** control:
22272**
22273**   1. POSIX locking (the default),
22274**   2. No locking,
22275**   3. Dot-file locking,
22276**   4. flock() locking,
22277**   5. AFP locking (OSX only),
22278**   6. Named POSIX semaphores (VXWorks only),
22279**   7. proxy locking. (OSX only)
22280**
22281** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22282** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22283** selection of the appropriate locking style based on the filesystem
22284** where the database is located.
22285*/
22286#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22287#  if defined(__APPLE__)
22288#    define SQLITE_ENABLE_LOCKING_STYLE 1
22289#  else
22290#    define SQLITE_ENABLE_LOCKING_STYLE 0
22291#  endif
22292#endif
22293
22294/*
22295** Define the OS_VXWORKS pre-processor macro to 1 if building on
22296** vxworks, or 0 otherwise.
22297*/
22298#ifndef OS_VXWORKS
22299#  if defined(__RTP__) || defined(_WRS_KERNEL)
22300#    define OS_VXWORKS 1
22301#  else
22302#    define OS_VXWORKS 0
22303#  endif
22304#endif
22305
22306/*
22307** These #defines should enable >2GB file support on Posix if the
22308** underlying operating system supports it.  If the OS lacks
22309** large file support, these should be no-ops.
22310**
22311** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22312** on the compiler command line.  This is necessary if you are compiling
22313** on a recent machine (ex: RedHat 7.2) but you want your code to work
22314** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22315** without this option, LFS is enable.  But LFS does not exist in the kernel
22316** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22317** portability you should omit LFS.
22318**
22319** The previous paragraph was written in 2005.  (This paragraph is written
22320** on 2008-11-28.) These days, all Linux kernels support large files, so
22321** you should probably leave LFS enabled.  But some embedded platforms might
22322** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22323*/
22324#ifndef SQLITE_DISABLE_LFS
22325# define _LARGE_FILE       1
22326# ifndef _FILE_OFFSET_BITS
22327#   define _FILE_OFFSET_BITS 64
22328# endif
22329# define _LARGEFILE_SOURCE 1
22330#endif
22331
22332/*
22333** standard include files.
22334*/
22335#include <sys/types.h>
22336#include <sys/stat.h>
22337#include <fcntl.h>
22338#include <unistd.h>
22339#include <sys/time.h>
22340#include <errno.h>
22341#include <sys/mman.h>
22342
22343#if SQLITE_ENABLE_LOCKING_STYLE
22344# include <sys/ioctl.h>
22345# if OS_VXWORKS
22346#  include <semaphore.h>
22347#  include <limits.h>
22348# else
22349#  include <sys/file.h>
22350#  include <sys/param.h>
22351# endif
22352#endif /* SQLITE_ENABLE_LOCKING_STYLE */
22353
22354#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22355# include <sys/mount.h>
22356#endif
22357
22358/*
22359** Allowed values of unixFile.fsFlags
22360*/
22361#define SQLITE_FSFLAGS_IS_MSDOS     0x1
22362
22363/*
22364** If we are to be thread-safe, include the pthreads header and define
22365** the SQLITE_UNIX_THREADS macro.
22366*/
22367#if SQLITE_THREADSAFE
22368# define SQLITE_UNIX_THREADS 1
22369#endif
22370
22371/*
22372** Default permissions when creating a new file
22373*/
22374#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22375# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22376#endif
22377
22378/*
22379 ** Default permissions when creating auto proxy dir
22380 */
22381#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22382# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22383#endif
22384
22385/*
22386** Maximum supported path-length.
22387*/
22388#define MAX_PATHNAME 512
22389
22390/*
22391** Only set the lastErrno if the error code is a real error and not
22392** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22393*/
22394#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22395
22396/* Forward references */
22397typedef struct unixShm unixShm;               /* Connection shared memory */
22398typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22399typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22400typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22401
22402/*
22403** Sometimes, after a file handle is closed by SQLite, the file descriptor
22404** cannot be closed immediately. In these cases, instances of the following
22405** structure are used to store the file descriptor while waiting for an
22406** opportunity to either close or reuse it.
22407*/
22408struct UnixUnusedFd {
22409  int fd;                   /* File descriptor to close */
22410  int flags;                /* Flags this file descriptor was opened with */
22411  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22412};
22413
22414/*
22415** The unixFile structure is subclass of sqlite3_file specific to the unix
22416** VFS implementations.
22417*/
22418typedef struct unixFile unixFile;
22419struct unixFile {
22420  sqlite3_io_methods const *pMethod;  /* Always the first entry */
22421  unixInodeInfo *pInode;              /* Info about locks on this inode */
22422  int h;                              /* The file descriptor */
22423  int dirfd;                          /* File descriptor for the directory */
22424  unsigned char eFileLock;            /* The type of lock held on this fd */
22425  int lastErrno;                      /* The unix errno from last I/O error */
22426  void *lockingContext;               /* Locking style specific state */
22427  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22428  int fileFlags;                      /* Miscellanous flags */
22429  const char *zPath;                  /* Name of the file */
22430  unixShm *pShm;                      /* Shared memory segment information */
22431#if SQLITE_ENABLE_LOCKING_STYLE
22432  int openFlags;                      /* The flags specified at open() */
22433#endif
22434#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22435  unsigned fsFlags;                   /* cached details from statfs() */
22436#endif
22437#if OS_VXWORKS
22438  int isDelete;                       /* Delete on close if true */
22439  struct vxworksFileId *pId;          /* Unique file ID */
22440#endif
22441#ifndef NDEBUG
22442  /* The next group of variables are used to track whether or not the
22443  ** transaction counter in bytes 24-27 of database files are updated
22444  ** whenever any part of the database changes.  An assertion fault will
22445  ** occur if a file is updated without also updating the transaction
22446  ** counter.  This test is made to avoid new problems similar to the
22447  ** one described by ticket #3584.
22448  */
22449  unsigned char transCntrChng;   /* True if the transaction counter changed */
22450  unsigned char dbUpdate;        /* True if any part of database file changed */
22451  unsigned char inNormalWrite;   /* True if in a normal write operation */
22452#endif
22453#ifdef SQLITE_TEST
22454  /* In test mode, increase the size of this structure a bit so that
22455  ** it is larger than the struct CrashFile defined in test6.c.
22456  */
22457  char aPadding[32];
22458#endif
22459};
22460
22461/*
22462** The following macros define bits in unixFile.fileFlags
22463*/
22464#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22465
22466/*
22467** Include code that is common to all os_*.c files
22468*/
22469/************** Include os_common.h in the middle of os_unix.c ***************/
22470/************** Begin file os_common.h ***************************************/
22471/*
22472** 2004 May 22
22473**
22474** The author disclaims copyright to this source code.  In place of
22475** a legal notice, here is a blessing:
22476**
22477**    May you do good and not evil.
22478**    May you find forgiveness for yourself and forgive others.
22479**    May you share freely, never taking more than you give.
22480**
22481******************************************************************************
22482**
22483** This file contains macros and a little bit of code that is common to
22484** all of the platform-specific files (os_*.c) and is #included into those
22485** files.
22486**
22487** This file should be #included by the os_*.c files only.  It is not a
22488** general purpose header file.
22489*/
22490#ifndef _OS_COMMON_H_
22491#define _OS_COMMON_H_
22492
22493/*
22494** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22495** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22496** switch.  The following code should catch this problem at compile-time.
22497*/
22498#ifdef MEMORY_DEBUG
22499# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22500#endif
22501
22502#ifdef SQLITE_DEBUG
22503SQLITE_PRIVATE int sqlite3OSTrace = 0;
22504#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22505#else
22506#define OSTRACE(X)
22507#endif
22508
22509/*
22510** Macros for performance tracing.  Normally turned off.  Only works
22511** on i486 hardware.
22512*/
22513#ifdef SQLITE_PERFORMANCE_TRACE
22514
22515/*
22516** hwtime.h contains inline assembler code for implementing
22517** high-performance timing routines.
22518*/
22519/************** Include hwtime.h in the middle of os_common.h ****************/
22520/************** Begin file hwtime.h ******************************************/
22521/*
22522** 2008 May 27
22523**
22524** The author disclaims copyright to this source code.  In place of
22525** a legal notice, here is a blessing:
22526**
22527**    May you do good and not evil.
22528**    May you find forgiveness for yourself and forgive others.
22529**    May you share freely, never taking more than you give.
22530**
22531******************************************************************************
22532**
22533** This file contains inline asm code for retrieving "high-performance"
22534** counters for x86 class CPUs.
22535*/
22536#ifndef _HWTIME_H_
22537#define _HWTIME_H_
22538
22539/*
22540** The following routine only works on pentium-class (or newer) processors.
22541** It uses the RDTSC opcode to read the cycle count value out of the
22542** processor and returns that value.  This can be used for high-res
22543** profiling.
22544*/
22545#if (defined(__GNUC__) || defined(_MSC_VER)) && \
22546      (defined(i386) || defined(__i386__) || defined(_M_IX86))
22547
22548  #if defined(__GNUC__)
22549
22550  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22551     unsigned int lo, hi;
22552     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22553     return (sqlite_uint64)hi << 32 | lo;
22554  }
22555
22556  #elif defined(_MSC_VER)
22557
22558  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22559     __asm {
22560        rdtsc
22561        ret       ; return value at EDX:EAX
22562     }
22563  }
22564
22565  #endif
22566
22567#elif (defined(__GNUC__) && defined(__x86_64__))
22568
22569  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22570      unsigned long val;
22571      __asm__ __volatile__ ("rdtsc" : "=A" (val));
22572      return val;
22573  }
22574
22575#elif (defined(__GNUC__) && defined(__ppc__))
22576
22577  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22578      unsigned long long retval;
22579      unsigned long junk;
22580      __asm__ __volatile__ ("\n\
22581          1:      mftbu   %1\n\
22582                  mftb    %L0\n\
22583                  mftbu   %0\n\
22584                  cmpw    %0,%1\n\
22585                  bne     1b"
22586                  : "=r" (retval), "=r" (junk));
22587      return retval;
22588  }
22589
22590#else
22591
22592  #error Need implementation of sqlite3Hwtime() for your platform.
22593
22594  /*
22595  ** To compile without implementing sqlite3Hwtime() for your platform,
22596  ** you can remove the above #error and use the following
22597  ** stub function.  You will lose timing support for many
22598  ** of the debugging and testing utilities, but it should at
22599  ** least compile and run.
22600  */
22601SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22602
22603#endif
22604
22605#endif /* !defined(_HWTIME_H_) */
22606
22607/************** End of hwtime.h **********************************************/
22608/************** Continuing where we left off in os_common.h ******************/
22609
22610static sqlite_uint64 g_start;
22611static sqlite_uint64 g_elapsed;
22612#define TIMER_START       g_start=sqlite3Hwtime()
22613#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22614#define TIMER_ELAPSED     g_elapsed
22615#else
22616#define TIMER_START
22617#define TIMER_END
22618#define TIMER_ELAPSED     ((sqlite_uint64)0)
22619#endif
22620
22621/*
22622** If we compile with the SQLITE_TEST macro set, then the following block
22623** of code will give us the ability to simulate a disk I/O error.  This
22624** is used for testing the I/O recovery logic.
22625*/
22626#ifdef SQLITE_TEST
22627SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22628SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22629SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22630SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22631SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22632SQLITE_API int sqlite3_diskfull_pending = 0;
22633SQLITE_API int sqlite3_diskfull = 0;
22634#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22635#define SimulateIOError(CODE)  \
22636  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22637       || sqlite3_io_error_pending-- == 1 )  \
22638              { local_ioerr(); CODE; }
22639static void local_ioerr(){
22640  IOTRACE(("IOERR\n"));
22641  sqlite3_io_error_hit++;
22642  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22643}
22644#define SimulateDiskfullError(CODE) \
22645   if( sqlite3_diskfull_pending ){ \
22646     if( sqlite3_diskfull_pending == 1 ){ \
22647       local_ioerr(); \
22648       sqlite3_diskfull = 1; \
22649       sqlite3_io_error_hit = 1; \
22650       CODE; \
22651     }else{ \
22652       sqlite3_diskfull_pending--; \
22653     } \
22654   }
22655#else
22656#define SimulateIOErrorBenign(X)
22657#define SimulateIOError(A)
22658#define SimulateDiskfullError(A)
22659#endif
22660
22661/*
22662** When testing, keep a count of the number of open files.
22663*/
22664#ifdef SQLITE_TEST
22665SQLITE_API int sqlite3_open_file_count = 0;
22666#define OpenCounter(X)  sqlite3_open_file_count+=(X)
22667#else
22668#define OpenCounter(X)
22669#endif
22670
22671#endif /* !defined(_OS_COMMON_H_) */
22672
22673/************** End of os_common.h *******************************************/
22674/************** Continuing where we left off in os_unix.c ********************/
22675
22676/*
22677** Define various macros that are missing from some systems.
22678*/
22679#ifndef O_LARGEFILE
22680# define O_LARGEFILE 0
22681#endif
22682#ifdef SQLITE_DISABLE_LFS
22683# undef O_LARGEFILE
22684# define O_LARGEFILE 0
22685#endif
22686#ifndef O_NOFOLLOW
22687# define O_NOFOLLOW 0
22688#endif
22689#ifndef O_BINARY
22690# define O_BINARY 0
22691#endif
22692
22693/*
22694** The DJGPP compiler environment looks mostly like Unix, but it
22695** lacks the fcntl() system call.  So redefine fcntl() to be something
22696** that always succeeds.  This means that locking does not occur under
22697** DJGPP.  But it is DOS - what did you expect?
22698*/
22699#ifdef __DJGPP__
22700# define fcntl(A,B,C) 0
22701#endif
22702
22703/*
22704** The threadid macro resolves to the thread-id or to 0.  Used for
22705** testing and debugging only.
22706*/
22707#if SQLITE_THREADSAFE
22708#define threadid pthread_self()
22709#else
22710#define threadid 0
22711#endif
22712
22713
22714/*
22715** Helper functions to obtain and relinquish the global mutex. The
22716** global mutex is used to protect the unixInodeInfo and
22717** vxworksFileId objects used by this file, all of which may be
22718** shared by multiple threads.
22719**
22720** Function unixMutexHeld() is used to assert() that the global mutex
22721** is held when required. This function is only used as part of assert()
22722** statements. e.g.
22723**
22724**   unixEnterMutex()
22725**     assert( unixMutexHeld() );
22726**   unixEnterLeave()
22727*/
22728static void unixEnterMutex(void){
22729  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22730}
22731static void unixLeaveMutex(void){
22732  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22733}
22734#ifdef SQLITE_DEBUG
22735static int unixMutexHeld(void) {
22736  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22737}
22738#endif
22739
22740
22741#ifdef SQLITE_DEBUG
22742/*
22743** Helper function for printing out trace information from debugging
22744** binaries. This returns the string represetation of the supplied
22745** integer lock-type.
22746*/
22747static const char *azFileLock(int eFileLock){
22748  switch( eFileLock ){
22749    case NO_LOCK: return "NONE";
22750    case SHARED_LOCK: return "SHARED";
22751    case RESERVED_LOCK: return "RESERVED";
22752    case PENDING_LOCK: return "PENDING";
22753    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22754  }
22755  return "ERROR";
22756}
22757#endif
22758
22759#ifdef SQLITE_LOCK_TRACE
22760/*
22761** Print out information about all locking operations.
22762**
22763** This routine is used for troubleshooting locks on multithreaded
22764** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22765** command-line option on the compiler.  This code is normally
22766** turned off.
22767*/
22768static int lockTrace(int fd, int op, struct flock *p){
22769  char *zOpName, *zType;
22770  int s;
22771  int savedErrno;
22772  if( op==F_GETLK ){
22773    zOpName = "GETLK";
22774  }else if( op==F_SETLK ){
22775    zOpName = "SETLK";
22776  }else{
22777    s = fcntl(fd, op, p);
22778    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22779    return s;
22780  }
22781  if( p->l_type==F_RDLCK ){
22782    zType = "RDLCK";
22783  }else if( p->l_type==F_WRLCK ){
22784    zType = "WRLCK";
22785  }else if( p->l_type==F_UNLCK ){
22786    zType = "UNLCK";
22787  }else{
22788    assert( 0 );
22789  }
22790  assert( p->l_whence==SEEK_SET );
22791  s = fcntl(fd, op, p);
22792  savedErrno = errno;
22793  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22794     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22795     (int)p->l_pid, s);
22796  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22797    struct flock l2;
22798    l2 = *p;
22799    fcntl(fd, F_GETLK, &l2);
22800    if( l2.l_type==F_RDLCK ){
22801      zType = "RDLCK";
22802    }else if( l2.l_type==F_WRLCK ){
22803      zType = "WRLCK";
22804    }else if( l2.l_type==F_UNLCK ){
22805      zType = "UNLCK";
22806    }else{
22807      assert( 0 );
22808    }
22809    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22810       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22811  }
22812  errno = savedErrno;
22813  return s;
22814}
22815#define fcntl lockTrace
22816#endif /* SQLITE_LOCK_TRACE */
22817
22818
22819
22820/*
22821** This routine translates a standard POSIX errno code into something
22822** useful to the clients of the sqlite3 functions.  Specifically, it is
22823** intended to translate a variety of "try again" errors into SQLITE_BUSY
22824** and a variety of "please close the file descriptor NOW" errors into
22825** SQLITE_IOERR
22826**
22827** Errors during initialization of locks, or file system support for locks,
22828** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22829*/
22830static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22831  switch (posixError) {
22832  case 0:
22833    return SQLITE_OK;
22834
22835  case EAGAIN:
22836  case ETIMEDOUT:
22837  case EBUSY:
22838  case EINTR:
22839  case ENOLCK:
22840    /* random NFS retry error, unless during file system support
22841     * introspection, in which it actually means what it says */
22842    return SQLITE_BUSY;
22843
22844  case EACCES:
22845    /* EACCES is like EAGAIN during locking operations, but not any other time*/
22846    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
22847	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
22848	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22849	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22850      return SQLITE_BUSY;
22851    }
22852    /* else fall through */
22853  case EPERM:
22854    return SQLITE_PERM;
22855
22856  case EDEADLK:
22857    return SQLITE_IOERR_BLOCKED;
22858
22859#if EOPNOTSUPP!=ENOTSUP
22860  case EOPNOTSUPP:
22861    /* something went terribly awry, unless during file system support
22862     * introspection, in which it actually means what it says */
22863#endif
22864#ifdef ENOTSUP
22865  case ENOTSUP:
22866    /* invalid fd, unless during file system support introspection, in which
22867     * it actually means what it says */
22868#endif
22869  case EIO:
22870  case EBADF:
22871  case EINVAL:
22872  case ENOTCONN:
22873  case ENODEV:
22874  case ENXIO:
22875  case ENOENT:
22876  case ESTALE:
22877  case ENOSYS:
22878    /* these should force the client to close the file and reconnect */
22879
22880  default:
22881    return sqliteIOErr;
22882  }
22883}
22884
22885
22886
22887/******************************************************************************
22888****************** Begin Unique File ID Utility Used By VxWorks ***************
22889**
22890** On most versions of unix, we can get a unique ID for a file by concatenating
22891** the device number and the inode number.  But this does not work on VxWorks.
22892** On VxWorks, a unique file id must be based on the canonical filename.
22893**
22894** A pointer to an instance of the following structure can be used as a
22895** unique file ID in VxWorks.  Each instance of this structure contains
22896** a copy of the canonical filename.  There is also a reference count.
22897** The structure is reclaimed when the number of pointers to it drops to
22898** zero.
22899**
22900** There are never very many files open at one time and lookups are not
22901** a performance-critical path, so it is sufficient to put these
22902** structures on a linked list.
22903*/
22904struct vxworksFileId {
22905  struct vxworksFileId *pNext;  /* Next in a list of them all */
22906  int nRef;                     /* Number of references to this one */
22907  int nName;                    /* Length of the zCanonicalName[] string */
22908  char *zCanonicalName;         /* Canonical filename */
22909};
22910
22911#if OS_VXWORKS
22912/*
22913** All unique filenames are held on a linked list headed by this
22914** variable:
22915*/
22916static struct vxworksFileId *vxworksFileList = 0;
22917
22918/*
22919** Simplify a filename into its canonical form
22920** by making the following changes:
22921**
22922**  * removing any trailing and duplicate /
22923**  * convert /./ into just /
22924**  * convert /A/../ where A is any simple name into just /
22925**
22926** Changes are made in-place.  Return the new name length.
22927**
22928** The original filename is in z[0..n-1].  Return the number of
22929** characters in the simplified name.
22930*/
22931static int vxworksSimplifyName(char *z, int n){
22932  int i, j;
22933  while( n>1 && z[n-1]=='/' ){ n--; }
22934  for(i=j=0; i<n; i++){
22935    if( z[i]=='/' ){
22936      if( z[i+1]=='/' ) continue;
22937      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22938        i += 1;
22939        continue;
22940      }
22941      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22942        while( j>0 && z[j-1]!='/' ){ j--; }
22943        if( j>0 ){ j--; }
22944        i += 2;
22945        continue;
22946      }
22947    }
22948    z[j++] = z[i];
22949  }
22950  z[j] = 0;
22951  return j;
22952}
22953
22954/*
22955** Find a unique file ID for the given absolute pathname.  Return
22956** a pointer to the vxworksFileId object.  This pointer is the unique
22957** file ID.
22958**
22959** The nRef field of the vxworksFileId object is incremented before
22960** the object is returned.  A new vxworksFileId object is created
22961** and added to the global list if necessary.
22962**
22963** If a memory allocation error occurs, return NULL.
22964*/
22965static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22966  struct vxworksFileId *pNew;         /* search key and new file ID */
22967  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22968  int n;                              /* Length of zAbsoluteName string */
22969
22970  assert( zAbsoluteName[0]=='/' );
22971  n = (int)strlen(zAbsoluteName);
22972  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22973  if( pNew==0 ) return 0;
22974  pNew->zCanonicalName = (char*)&pNew[1];
22975  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22976  n = vxworksSimplifyName(pNew->zCanonicalName, n);
22977
22978  /* Search for an existing entry that matching the canonical name.
22979  ** If found, increment the reference count and return a pointer to
22980  ** the existing file ID.
22981  */
22982  unixEnterMutex();
22983  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22984    if( pCandidate->nName==n
22985     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22986    ){
22987       sqlite3_free(pNew);
22988       pCandidate->nRef++;
22989       unixLeaveMutex();
22990       return pCandidate;
22991    }
22992  }
22993
22994  /* No match was found.  We will make a new file ID */
22995  pNew->nRef = 1;
22996  pNew->nName = n;
22997  pNew->pNext = vxworksFileList;
22998  vxworksFileList = pNew;
22999  unixLeaveMutex();
23000  return pNew;
23001}
23002
23003/*
23004** Decrement the reference count on a vxworksFileId object.  Free
23005** the object when the reference count reaches zero.
23006*/
23007static void vxworksReleaseFileId(struct vxworksFileId *pId){
23008  unixEnterMutex();
23009  assert( pId->nRef>0 );
23010  pId->nRef--;
23011  if( pId->nRef==0 ){
23012    struct vxworksFileId **pp;
23013    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23014    assert( *pp==pId );
23015    *pp = pId->pNext;
23016    sqlite3_free(pId);
23017  }
23018  unixLeaveMutex();
23019}
23020#endif /* OS_VXWORKS */
23021/*************** End of Unique File ID Utility Used By VxWorks ****************
23022******************************************************************************/
23023
23024
23025/******************************************************************************
23026*************************** Posix Advisory Locking ****************************
23027**
23028** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23029** section 6.5.2.2 lines 483 through 490 specify that when a process
23030** sets or clears a lock, that operation overrides any prior locks set
23031** by the same process.  It does not explicitly say so, but this implies
23032** that it overrides locks set by the same process using a different
23033** file descriptor.  Consider this test case:
23034**
23035**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23036**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23037**
23038** Suppose ./file1 and ./file2 are really the same file (because
23039** one is a hard or symbolic link to the other) then if you set
23040** an exclusive lock on fd1, then try to get an exclusive lock
23041** on fd2, it works.  I would have expected the second lock to
23042** fail since there was already a lock on the file due to fd1.
23043** But not so.  Since both locks came from the same process, the
23044** second overrides the first, even though they were on different
23045** file descriptors opened on different file names.
23046**
23047** This means that we cannot use POSIX locks to synchronize file access
23048** among competing threads of the same process.  POSIX locks will work fine
23049** to synchronize access for threads in separate processes, but not
23050** threads within the same process.
23051**
23052** To work around the problem, SQLite has to manage file locks internally
23053** on its own.  Whenever a new database is opened, we have to find the
23054** specific inode of the database file (the inode is determined by the
23055** st_dev and st_ino fields of the stat structure that fstat() fills in)
23056** and check for locks already existing on that inode.  When locks are
23057** created or removed, we have to look at our own internal record of the
23058** locks to see if another thread has previously set a lock on that same
23059** inode.
23060**
23061** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23062** For VxWorks, we have to use the alternative unique ID system based on
23063** canonical filename and implemented in the previous division.)
23064**
23065** The sqlite3_file structure for POSIX is no longer just an integer file
23066** descriptor.  It is now a structure that holds the integer file
23067** descriptor and a pointer to a structure that describes the internal
23068** locks on the corresponding inode.  There is one locking structure
23069** per inode, so if the same inode is opened twice, both unixFile structures
23070** point to the same locking structure.  The locking structure keeps
23071** a reference count (so we will know when to delete it) and a "cnt"
23072** field that tells us its internal lock status.  cnt==0 means the
23073** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23074** cnt>0 means there are cnt shared locks on the file.
23075**
23076** Any attempt to lock or unlock a file first checks the locking
23077** structure.  The fcntl() system call is only invoked to set a
23078** POSIX lock if the internal lock structure transitions between
23079** a locked and an unlocked state.
23080**
23081** But wait:  there are yet more problems with POSIX advisory locks.
23082**
23083** If you close a file descriptor that points to a file that has locks,
23084** all locks on that file that are owned by the current process are
23085** released.  To work around this problem, each unixInodeInfo object
23086** maintains a count of the number of pending locks on tha inode.
23087** When an attempt is made to close an unixFile, if there are
23088** other unixFile open on the same inode that are holding locks, the call
23089** to close() the file descriptor is deferred until all of the locks clear.
23090** The unixInodeInfo structure keeps a list of file descriptors that need to
23091** be closed and that list is walked (and cleared) when the last lock
23092** clears.
23093**
23094** Yet another problem:  LinuxThreads do not play well with posix locks.
23095**
23096** Many older versions of linux use the LinuxThreads library which is
23097** not posix compliant.  Under LinuxThreads, a lock created by thread
23098** A cannot be modified or overridden by a different thread B.
23099** Only thread A can modify the lock.  Locking behavior is correct
23100** if the appliation uses the newer Native Posix Thread Library (NPTL)
23101** on linux - with NPTL a lock created by thread A can override locks
23102** in thread B.  But there is no way to know at compile-time which
23103** threading library is being used.  So there is no way to know at
23104** compile-time whether or not thread A can override locks on thread B.
23105** One has to do a run-time check to discover the behavior of the
23106** current process.
23107**
23108** SQLite used to support LinuxThreads.  But support for LinuxThreads
23109** was dropped beginning with version 3.7.0.  SQLite will still work with
23110** LinuxThreads provided that (1) there is no more than one connection
23111** per database file in the same process and (2) database connections
23112** do not move across threads.
23113*/
23114
23115/*
23116** An instance of the following structure serves as the key used
23117** to locate a particular unixInodeInfo object.
23118*/
23119struct unixFileId {
23120  dev_t dev;                  /* Device number */
23121#if OS_VXWORKS
23122  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23123#else
23124  ino_t ino;                  /* Inode number */
23125#endif
23126};
23127
23128/*
23129** An instance of the following structure is allocated for each open
23130** inode.  Or, on LinuxThreads, there is one of these structures for
23131** each inode opened by each thread.
23132**
23133** A single inode can have multiple file descriptors, so each unixFile
23134** structure contains a pointer to an instance of this object and this
23135** object keeps a count of the number of unixFile pointing to it.
23136*/
23137struct unixInodeInfo {
23138  struct unixFileId fileId;       /* The lookup key */
23139  int nShared;                    /* Number of SHARED locks held */
23140  int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23141  int nRef;                       /* Number of pointers to this structure */
23142  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23143  int nLock;                      /* Number of outstanding file locks */
23144  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23145  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23146  unixInodeInfo *pPrev;           /*    .... doubly linked */
23147#if defined(SQLITE_ENABLE_LOCKING_STYLE)
23148  unsigned long long sharedByte;  /* for AFP simulated shared lock */
23149#endif
23150#if OS_VXWORKS
23151  sem_t *pSem;                    /* Named POSIX semaphore */
23152  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23153#endif
23154};
23155
23156/*
23157** A lists of all unixInodeInfo objects.
23158*/
23159static unixInodeInfo *inodeList = 0;
23160
23161/*
23162** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23163** If all such file descriptors are closed without error, the list is
23164** cleared and SQLITE_OK returned.
23165**
23166** Otherwise, if an error occurs, then successfully closed file descriptor
23167** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
23168** not deleted and SQLITE_IOERR_CLOSE returned.
23169*/
23170static int closePendingFds(unixFile *pFile){
23171  int rc = SQLITE_OK;
23172  unixInodeInfo *pInode = pFile->pInode;
23173  UnixUnusedFd *pError = 0;
23174  UnixUnusedFd *p;
23175  UnixUnusedFd *pNext;
23176  for(p=pInode->pUnused; p; p=pNext){
23177    pNext = p->pNext;
23178    if( close(p->fd) ){
23179      pFile->lastErrno = errno;
23180      rc = SQLITE_IOERR_CLOSE;
23181      p->pNext = pError;
23182      pError = p;
23183    }else{
23184      sqlite3_free(p);
23185    }
23186  }
23187  pInode->pUnused = pError;
23188  return rc;
23189}
23190
23191/*
23192** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23193**
23194** The mutex entered using the unixEnterMutex() function must be held
23195** when this function is called.
23196*/
23197static void releaseInodeInfo(unixFile *pFile){
23198  unixInodeInfo *pInode = pFile->pInode;
23199  assert( unixMutexHeld() );
23200  if( pInode ){
23201    pInode->nRef--;
23202    if( pInode->nRef==0 ){
23203      assert( pInode->pShmNode==0 );
23204      closePendingFds(pFile);
23205      if( pInode->pPrev ){
23206        assert( pInode->pPrev->pNext==pInode );
23207        pInode->pPrev->pNext = pInode->pNext;
23208      }else{
23209        assert( inodeList==pInode );
23210        inodeList = pInode->pNext;
23211      }
23212      if( pInode->pNext ){
23213        assert( pInode->pNext->pPrev==pInode );
23214        pInode->pNext->pPrev = pInode->pPrev;
23215      }
23216      sqlite3_free(pInode);
23217    }
23218  }
23219}
23220
23221/*
23222** Given a file descriptor, locate the unixInodeInfo object that
23223** describes that file descriptor.  Create a new one if necessary.  The
23224** return value might be uninitialized if an error occurs.
23225**
23226** The mutex entered using the unixEnterMutex() function must be held
23227** when this function is called.
23228**
23229** Return an appropriate error code.
23230*/
23231static int findInodeInfo(
23232  unixFile *pFile,               /* Unix file with file desc used in the key */
23233  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23234){
23235  int rc;                        /* System call return code */
23236  int fd;                        /* The file descriptor for pFile */
23237  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23238  struct stat statbuf;           /* Low-level file information */
23239  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23240
23241  assert( unixMutexHeld() );
23242
23243  /* Get low-level information about the file that we can used to
23244  ** create a unique name for the file.
23245  */
23246  fd = pFile->h;
23247  rc = fstat(fd, &statbuf);
23248  if( rc!=0 ){
23249    pFile->lastErrno = errno;
23250#ifdef EOVERFLOW
23251    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23252#endif
23253    return SQLITE_IOERR;
23254  }
23255
23256#ifdef __APPLE__
23257  /* On OS X on an msdos filesystem, the inode number is reported
23258  ** incorrectly for zero-size files.  See ticket #3260.  To work
23259  ** around this problem (we consider it a bug in OS X, not SQLite)
23260  ** we always increase the file size to 1 by writing a single byte
23261  ** prior to accessing the inode number.  The one byte written is
23262  ** an ASCII 'S' character which also happens to be the first byte
23263  ** in the header of every SQLite database.  In this way, if there
23264  ** is a race condition such that another thread has already populated
23265  ** the first page of the database, no damage is done.
23266  */
23267  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23268    rc = write(fd, "S", 1);
23269    if( rc!=1 ){
23270      pFile->lastErrno = errno;
23271      return SQLITE_IOERR;
23272    }
23273    rc = fstat(fd, &statbuf);
23274    if( rc!=0 ){
23275      pFile->lastErrno = errno;
23276      return SQLITE_IOERR;
23277    }
23278  }
23279#endif
23280
23281  memset(&fileId, 0, sizeof(fileId));
23282  fileId.dev = statbuf.st_dev;
23283#if OS_VXWORKS
23284  fileId.pId = pFile->pId;
23285#else
23286  fileId.ino = statbuf.st_ino;
23287#endif
23288  pInode = inodeList;
23289  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23290    pInode = pInode->pNext;
23291  }
23292  if( pInode==0 ){
23293    pInode = sqlite3_malloc( sizeof(*pInode) );
23294    if( pInode==0 ){
23295      return SQLITE_NOMEM;
23296    }
23297    memset(pInode, 0, sizeof(*pInode));
23298    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23299    pInode->nRef = 1;
23300    pInode->pNext = inodeList;
23301    pInode->pPrev = 0;
23302    if( inodeList ) inodeList->pPrev = pInode;
23303    inodeList = pInode;
23304  }else{
23305    pInode->nRef++;
23306  }
23307  *ppInode = pInode;
23308  return SQLITE_OK;
23309}
23310
23311
23312/*
23313** This routine checks if there is a RESERVED lock held on the specified
23314** file by this or any other process. If such a lock is held, set *pResOut
23315** to a non-zero value otherwise *pResOut is set to zero.  The return value
23316** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23317*/
23318static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23319  int rc = SQLITE_OK;
23320  int reserved = 0;
23321  unixFile *pFile = (unixFile*)id;
23322
23323  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23324
23325  assert( pFile );
23326  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23327
23328  /* Check if a thread in this process holds such a lock */
23329  if( pFile->pInode->eFileLock>SHARED_LOCK ){
23330    reserved = 1;
23331  }
23332
23333  /* Otherwise see if some other process holds it.
23334  */
23335#ifndef __DJGPP__
23336  if( !reserved ){
23337    struct flock lock;
23338    lock.l_whence = SEEK_SET;
23339    lock.l_start = RESERVED_BYTE;
23340    lock.l_len = 1;
23341    lock.l_type = F_WRLCK;
23342    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23343      int tErrno = errno;
23344      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23345      pFile->lastErrno = tErrno;
23346    } else if( lock.l_type!=F_UNLCK ){
23347      reserved = 1;
23348    }
23349  }
23350#endif
23351
23352  unixLeaveMutex();
23353  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23354
23355  *pResOut = reserved;
23356  return rc;
23357}
23358
23359/*
23360** Lock the file with the lock specified by parameter eFileLock - one
23361** of the following:
23362**
23363**     (1) SHARED_LOCK
23364**     (2) RESERVED_LOCK
23365**     (3) PENDING_LOCK
23366**     (4) EXCLUSIVE_LOCK
23367**
23368** Sometimes when requesting one lock state, additional lock states
23369** are inserted in between.  The locking might fail on one of the later
23370** transitions leaving the lock state different from what it started but
23371** still short of its goal.  The following chart shows the allowed
23372** transitions and the inserted intermediate states:
23373**
23374**    UNLOCKED -> SHARED
23375**    SHARED -> RESERVED
23376**    SHARED -> (PENDING) -> EXCLUSIVE
23377**    RESERVED -> (PENDING) -> EXCLUSIVE
23378**    PENDING -> EXCLUSIVE
23379**
23380** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23381** routine to lower a locking level.
23382*/
23383static int unixLock(sqlite3_file *id, int eFileLock){
23384  /* The following describes the implementation of the various locks and
23385  ** lock transitions in terms of the POSIX advisory shared and exclusive
23386  ** lock primitives (called read-locks and write-locks below, to avoid
23387  ** confusion with SQLite lock names). The algorithms are complicated
23388  ** slightly in order to be compatible with windows systems simultaneously
23389  ** accessing the same database file, in case that is ever required.
23390  **
23391  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23392  ** byte', each single bytes at well known offsets, and the 'shared byte
23393  ** range', a range of 510 bytes at a well known offset.
23394  **
23395  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23396  ** byte'.  If this is successful, a random byte from the 'shared byte
23397  ** range' is read-locked and the lock on the 'pending byte' released.
23398  **
23399  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23400  ** A RESERVED lock is implemented by grabbing a write-lock on the
23401  ** 'reserved byte'.
23402  **
23403  ** A process may only obtain a PENDING lock after it has obtained a
23404  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23405  ** on the 'pending byte'. This ensures that no new SHARED locks can be
23406  ** obtained, but existing SHARED locks are allowed to persist. A process
23407  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23408  ** This property is used by the algorithm for rolling back a journal file
23409  ** after a crash.
23410  **
23411  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23412  ** implemented by obtaining a write-lock on the entire 'shared byte
23413  ** range'. Since all other locks require a read-lock on one of the bytes
23414  ** within this range, this ensures that no other locks are held on the
23415  ** database.
23416  **
23417  ** The reason a single byte cannot be used instead of the 'shared byte
23418  ** range' is that some versions of windows do not support read-locks. By
23419  ** locking a random byte from a range, concurrent SHARED locks may exist
23420  ** even if the locking primitive used is always a write-lock.
23421  */
23422  int rc = SQLITE_OK;
23423  unixFile *pFile = (unixFile*)id;
23424  unixInodeInfo *pInode = pFile->pInode;
23425  struct flock lock;
23426  int s = 0;
23427  int tErrno = 0;
23428
23429  assert( pFile );
23430  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23431      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23432      azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23433
23434  /* If there is already a lock of this type or more restrictive on the
23435  ** unixFile, do nothing. Don't use the end_lock: exit path, as
23436  ** unixEnterMutex() hasn't been called yet.
23437  */
23438  if( pFile->eFileLock>=eFileLock ){
23439    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23440            azFileLock(eFileLock)));
23441    return SQLITE_OK;
23442  }
23443
23444  /* Make sure the locking sequence is correct.
23445  **  (1) We never move from unlocked to anything higher than shared lock.
23446  **  (2) SQLite never explicitly requests a pendig lock.
23447  **  (3) A shared lock is always held when a reserve lock is requested.
23448  */
23449  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23450  assert( eFileLock!=PENDING_LOCK );
23451  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23452
23453  /* This mutex is needed because pFile->pInode is shared across threads
23454  */
23455  unixEnterMutex();
23456  pInode = pFile->pInode;
23457
23458  /* If some thread using this PID has a lock via a different unixFile*
23459  ** handle that precludes the requested lock, return BUSY.
23460  */
23461  if( (pFile->eFileLock!=pInode->eFileLock &&
23462          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23463  ){
23464    rc = SQLITE_BUSY;
23465    goto end_lock;
23466  }
23467
23468  /* If a SHARED lock is requested, and some thread using this PID already
23469  ** has a SHARED or RESERVED lock, then increment reference counts and
23470  ** return SQLITE_OK.
23471  */
23472  if( eFileLock==SHARED_LOCK &&
23473      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23474    assert( eFileLock==SHARED_LOCK );
23475    assert( pFile->eFileLock==0 );
23476    assert( pInode->nShared>0 );
23477    pFile->eFileLock = SHARED_LOCK;
23478    pInode->nShared++;
23479    pInode->nLock++;
23480    goto end_lock;
23481  }
23482
23483
23484  /* A PENDING lock is needed before acquiring a SHARED lock and before
23485  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23486  ** be released.
23487  */
23488  lock.l_len = 1L;
23489  lock.l_whence = SEEK_SET;
23490  if( eFileLock==SHARED_LOCK
23491      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23492  ){
23493    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23494    lock.l_start = PENDING_BYTE;
23495    s = fcntl(pFile->h, F_SETLK, &lock);
23496    if( s==(-1) ){
23497      tErrno = errno;
23498      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23499      if( IS_LOCK_ERROR(rc) ){
23500        pFile->lastErrno = tErrno;
23501      }
23502      goto end_lock;
23503    }
23504  }
23505
23506
23507  /* If control gets to this point, then actually go ahead and make
23508  ** operating system calls for the specified lock.
23509  */
23510  if( eFileLock==SHARED_LOCK ){
23511    assert( pInode->nShared==0 );
23512    assert( pInode->eFileLock==0 );
23513
23514    /* Now get the read-lock */
23515    lock.l_start = SHARED_FIRST;
23516    lock.l_len = SHARED_SIZE;
23517    if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23518      tErrno = errno;
23519    }
23520    /* Drop the temporary PENDING lock */
23521    lock.l_start = PENDING_BYTE;
23522    lock.l_len = 1L;
23523    lock.l_type = F_UNLCK;
23524    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23525      if( s != -1 ){
23526        /* This could happen with a network mount */
23527        tErrno = errno;
23528        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23529        if( IS_LOCK_ERROR(rc) ){
23530          pFile->lastErrno = tErrno;
23531        }
23532        goto end_lock;
23533      }
23534    }
23535    if( s==(-1) ){
23536      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23537      if( IS_LOCK_ERROR(rc) ){
23538        pFile->lastErrno = tErrno;
23539      }
23540    }else{
23541      pFile->eFileLock = SHARED_LOCK;
23542      pInode->nLock++;
23543      pInode->nShared = 1;
23544    }
23545  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
23546    /* We are trying for an exclusive lock but another thread in this
23547    ** same process is still holding a shared lock. */
23548    rc = SQLITE_BUSY;
23549  }else{
23550    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23551    ** assumed that there is a SHARED or greater lock on the file
23552    ** already.
23553    */
23554    assert( 0!=pFile->eFileLock );
23555    lock.l_type = F_WRLCK;
23556    switch( eFileLock ){
23557      case RESERVED_LOCK:
23558        lock.l_start = RESERVED_BYTE;
23559        break;
23560      case EXCLUSIVE_LOCK:
23561        lock.l_start = SHARED_FIRST;
23562        lock.l_len = SHARED_SIZE;
23563        break;
23564      default:
23565        assert(0);
23566    }
23567    s = fcntl(pFile->h, F_SETLK, &lock);
23568    if( s==(-1) ){
23569      tErrno = errno;
23570      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23571      if( IS_LOCK_ERROR(rc) ){
23572        pFile->lastErrno = tErrno;
23573      }
23574    }
23575  }
23576
23577
23578#ifndef NDEBUG
23579  /* Set up the transaction-counter change checking flags when
23580  ** transitioning from a SHARED to a RESERVED lock.  The change
23581  ** from SHARED to RESERVED marks the beginning of a normal
23582  ** write operation (not a hot journal rollback).
23583  */
23584  if( rc==SQLITE_OK
23585   && pFile->eFileLock<=SHARED_LOCK
23586   && eFileLock==RESERVED_LOCK
23587  ){
23588    pFile->transCntrChng = 0;
23589    pFile->dbUpdate = 0;
23590    pFile->inNormalWrite = 1;
23591  }
23592#endif
23593
23594
23595  if( rc==SQLITE_OK ){
23596    pFile->eFileLock = eFileLock;
23597    pInode->eFileLock = eFileLock;
23598  }else if( eFileLock==EXCLUSIVE_LOCK ){
23599    pFile->eFileLock = PENDING_LOCK;
23600    pInode->eFileLock = PENDING_LOCK;
23601  }
23602
23603end_lock:
23604  unixLeaveMutex();
23605  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
23606      rc==SQLITE_OK ? "ok" : "failed"));
23607  return rc;
23608}
23609
23610/*
23611** Add the file descriptor used by file handle pFile to the corresponding
23612** pUnused list.
23613*/
23614static void setPendingFd(unixFile *pFile){
23615  unixInodeInfo *pInode = pFile->pInode;
23616  UnixUnusedFd *p = pFile->pUnused;
23617  p->pNext = pInode->pUnused;
23618  pInode->pUnused = p;
23619  pFile->h = -1;
23620  pFile->pUnused = 0;
23621}
23622
23623/*
23624** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23625** must be either NO_LOCK or SHARED_LOCK.
23626**
23627** If the locking level of the file descriptor is already at or below
23628** the requested locking level, this routine is a no-op.
23629**
23630** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
23631** the byte range is divided into 2 parts and the first part is unlocked then
23632** set to a read lock, then the other part is simply unlocked.  This works
23633** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
23634** remove the write lock on a region when a read lock is set.
23635*/
23636static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
23637  unixFile *pFile = (unixFile*)id;
23638  unixInodeInfo *pInode;
23639  struct flock lock;
23640  int rc = SQLITE_OK;
23641  int h;
23642  int tErrno;                      /* Error code from system call errors */
23643
23644  assert( pFile );
23645  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
23646      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
23647      getpid()));
23648
23649  assert( eFileLock<=SHARED_LOCK );
23650  if( pFile->eFileLock<=eFileLock ){
23651    return SQLITE_OK;
23652  }
23653  unixEnterMutex();
23654  h = pFile->h;
23655  pInode = pFile->pInode;
23656  assert( pInode->nShared!=0 );
23657  if( pFile->eFileLock>SHARED_LOCK ){
23658    assert( pInode->eFileLock==pFile->eFileLock );
23659    SimulateIOErrorBenign(1);
23660    SimulateIOError( h=(-1) )
23661    SimulateIOErrorBenign(0);
23662
23663#ifndef NDEBUG
23664    /* When reducing a lock such that other processes can start
23665    ** reading the database file again, make sure that the
23666    ** transaction counter was updated if any part of the database
23667    ** file changed.  If the transaction counter is not updated,
23668    ** other connections to the same file might not realize that
23669    ** the file has changed and hence might not know to flush their
23670    ** cache.  The use of a stale cache can lead to database corruption.
23671    */
23672#if 0
23673    assert( pFile->inNormalWrite==0
23674         || pFile->dbUpdate==0
23675         || pFile->transCntrChng==1 );
23676#endif
23677    pFile->inNormalWrite = 0;
23678#endif
23679
23680    /* downgrading to a shared lock on NFS involves clearing the write lock
23681    ** before establishing the readlock - to avoid a race condition we downgrade
23682    ** the lock in 2 blocks, so that part of the range will be covered by a
23683    ** write lock until the rest is covered by a read lock:
23684    **  1:   [WWWWW]
23685    **  2:   [....W]
23686    **  3:   [RRRRW]
23687    **  4:   [RRRR.]
23688    */
23689    if( eFileLock==SHARED_LOCK ){
23690      if( handleNFSUnlock ){
23691        off_t divSize = SHARED_SIZE - 1;
23692
23693        lock.l_type = F_UNLCK;
23694        lock.l_whence = SEEK_SET;
23695        lock.l_start = SHARED_FIRST;
23696        lock.l_len = divSize;
23697        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23698          tErrno = errno;
23699          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23700          if( IS_LOCK_ERROR(rc) ){
23701            pFile->lastErrno = tErrno;
23702          }
23703          goto end_unlock;
23704        }
23705        lock.l_type = F_RDLCK;
23706        lock.l_whence = SEEK_SET;
23707        lock.l_start = SHARED_FIRST;
23708        lock.l_len = divSize;
23709        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23710          tErrno = errno;
23711          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23712          if( IS_LOCK_ERROR(rc) ){
23713            pFile->lastErrno = tErrno;
23714          }
23715          goto end_unlock;
23716        }
23717        lock.l_type = F_UNLCK;
23718        lock.l_whence = SEEK_SET;
23719        lock.l_start = SHARED_FIRST+divSize;
23720        lock.l_len = SHARED_SIZE-divSize;
23721        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23722          tErrno = errno;
23723          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23724          if( IS_LOCK_ERROR(rc) ){
23725            pFile->lastErrno = tErrno;
23726          }
23727          goto end_unlock;
23728        }
23729      }else{
23730        lock.l_type = F_RDLCK;
23731        lock.l_whence = SEEK_SET;
23732        lock.l_start = SHARED_FIRST;
23733        lock.l_len = SHARED_SIZE;
23734        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23735          tErrno = errno;
23736          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23737          if( IS_LOCK_ERROR(rc) ){
23738            pFile->lastErrno = tErrno;
23739          }
23740          goto end_unlock;
23741        }
23742      }
23743    }
23744    lock.l_type = F_UNLCK;
23745    lock.l_whence = SEEK_SET;
23746    lock.l_start = PENDING_BYTE;
23747    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23748    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23749      pInode->eFileLock = SHARED_LOCK;
23750    }else{
23751      tErrno = errno;
23752      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23753      if( IS_LOCK_ERROR(rc) ){
23754        pFile->lastErrno = tErrno;
23755      }
23756      goto end_unlock;
23757    }
23758  }
23759  if( eFileLock==NO_LOCK ){
23760    /* Decrement the shared lock counter.  Release the lock using an
23761    ** OS call only when all threads in this same process have released
23762    ** the lock.
23763    */
23764    pInode->nShared--;
23765    if( pInode->nShared==0 ){
23766      lock.l_type = F_UNLCK;
23767      lock.l_whence = SEEK_SET;
23768      lock.l_start = lock.l_len = 0L;
23769      SimulateIOErrorBenign(1);
23770      SimulateIOError( h=(-1) )
23771      SimulateIOErrorBenign(0);
23772      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23773        pInode->eFileLock = NO_LOCK;
23774      }else{
23775        tErrno = errno;
23776        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23777        if( IS_LOCK_ERROR(rc) ){
23778          pFile->lastErrno = tErrno;
23779        }
23780        pInode->eFileLock = NO_LOCK;
23781        pFile->eFileLock = NO_LOCK;
23782      }
23783    }
23784
23785    /* Decrement the count of locks against this same file.  When the
23786    ** count reaches zero, close any other file descriptors whose close
23787    ** was deferred because of outstanding locks.
23788    */
23789    pInode->nLock--;
23790    assert( pInode->nLock>=0 );
23791    if( pInode->nLock==0 ){
23792      int rc2 = closePendingFds(pFile);
23793      if( rc==SQLITE_OK ){
23794        rc = rc2;
23795      }
23796    }
23797  }
23798
23799end_unlock:
23800  unixLeaveMutex();
23801  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
23802  return rc;
23803}
23804
23805/*
23806** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23807** must be either NO_LOCK or SHARED_LOCK.
23808**
23809** If the locking level of the file descriptor is already at or below
23810** the requested locking level, this routine is a no-op.
23811*/
23812static int unixUnlock(sqlite3_file *id, int eFileLock){
23813  return _posixUnlock(id, eFileLock, 0);
23814}
23815
23816/*
23817** This function performs the parts of the "close file" operation
23818** common to all locking schemes. It closes the directory and file
23819** handles, if they are valid, and sets all fields of the unixFile
23820** structure to 0.
23821**
23822** It is *not* necessary to hold the mutex when this routine is called,
23823** even on VxWorks.  A mutex will be acquired on VxWorks by the
23824** vxworksReleaseFileId() routine.
23825*/
23826static int closeUnixFile(sqlite3_file *id){
23827  unixFile *pFile = (unixFile*)id;
23828  if( pFile ){
23829    if( pFile->dirfd>=0 ){
23830      int err = close(pFile->dirfd);
23831      if( err ){
23832        pFile->lastErrno = errno;
23833        return SQLITE_IOERR_DIR_CLOSE;
23834      }else{
23835        pFile->dirfd=-1;
23836      }
23837    }
23838    if( pFile->h>=0 ){
23839      int err = close(pFile->h);
23840      if( err ){
23841        pFile->lastErrno = errno;
23842        return SQLITE_IOERR_CLOSE;
23843      }
23844    }
23845#if OS_VXWORKS
23846    if( pFile->pId ){
23847      if( pFile->isDelete ){
23848        unlink(pFile->pId->zCanonicalName);
23849      }
23850      vxworksReleaseFileId(pFile->pId);
23851      pFile->pId = 0;
23852    }
23853#endif
23854    OSTRACE(("CLOSE   %-3d\n", pFile->h));
23855    OpenCounter(-1);
23856    sqlite3_free(pFile->pUnused);
23857    memset(pFile, 0, sizeof(unixFile));
23858  }
23859  return SQLITE_OK;
23860}
23861
23862/*
23863** Close a file.
23864*/
23865static int unixClose(sqlite3_file *id){
23866  int rc = SQLITE_OK;
23867  if( id ){
23868    unixFile *pFile = (unixFile *)id;
23869    unixUnlock(id, NO_LOCK);
23870    unixEnterMutex();
23871    if( pFile->pInode && pFile->pInode->nLock ){
23872      /* If there are outstanding locks, do not actually close the file just
23873      ** yet because that would clear those locks.  Instead, add the file
23874      ** descriptor to pInode->pUnused list.  It will be automatically closed
23875      ** when the last lock is cleared.
23876      */
23877      setPendingFd(pFile);
23878    }
23879    releaseInodeInfo(pFile);
23880    rc = closeUnixFile(id);
23881    unixLeaveMutex();
23882  }
23883  return rc;
23884}
23885
23886/************** End of the posix advisory lock implementation *****************
23887******************************************************************************/
23888
23889/******************************************************************************
23890****************************** No-op Locking **********************************
23891**
23892** Of the various locking implementations available, this is by far the
23893** simplest:  locking is ignored.  No attempt is made to lock the database
23894** file for reading or writing.
23895**
23896** This locking mode is appropriate for use on read-only databases
23897** (ex: databases that are burned into CD-ROM, for example.)  It can
23898** also be used if the application employs some external mechanism to
23899** prevent simultaneous access of the same database by two or more
23900** database connections.  But there is a serious risk of database
23901** corruption if this locking mode is used in situations where multiple
23902** database connections are accessing the same database file at the same
23903** time and one or more of those connections are writing.
23904*/
23905
23906static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23907  UNUSED_PARAMETER(NotUsed);
23908  *pResOut = 0;
23909  return SQLITE_OK;
23910}
23911static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23912  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23913  return SQLITE_OK;
23914}
23915static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23916  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23917  return SQLITE_OK;
23918}
23919
23920/*
23921** Close the file.
23922*/
23923static int nolockClose(sqlite3_file *id) {
23924  return closeUnixFile(id);
23925}
23926
23927/******************* End of the no-op lock implementation *********************
23928******************************************************************************/
23929
23930/******************************************************************************
23931************************* Begin dot-file Locking ******************************
23932**
23933** The dotfile locking implementation uses the existance of separate lock
23934** files in order to control access to the database.  This works on just
23935** about every filesystem imaginable.  But there are serious downsides:
23936**
23937**    (1)  There is zero concurrency.  A single reader blocks all other
23938**         connections from reading or writing the database.
23939**
23940**    (2)  An application crash or power loss can leave stale lock files
23941**         sitting around that need to be cleared manually.
23942**
23943** Nevertheless, a dotlock is an appropriate locking mode for use if no
23944** other locking strategy is available.
23945**
23946** Dotfile locking works by creating a file in the same directory as the
23947** database and with the same name but with a ".lock" extension added.
23948** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23949** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23950*/
23951
23952/*
23953** The file suffix added to the data base filename in order to create the
23954** lock file.
23955*/
23956#define DOTLOCK_SUFFIX ".lock"
23957
23958/*
23959** This routine checks if there is a RESERVED lock held on the specified
23960** file by this or any other process. If such a lock is held, set *pResOut
23961** to a non-zero value otherwise *pResOut is set to zero.  The return value
23962** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23963**
23964** In dotfile locking, either a lock exists or it does not.  So in this
23965** variation of CheckReservedLock(), *pResOut is set to true if any lock
23966** is held on the file and false if the file is unlocked.
23967*/
23968static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23969  int rc = SQLITE_OK;
23970  int reserved = 0;
23971  unixFile *pFile = (unixFile*)id;
23972
23973  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23974
23975  assert( pFile );
23976
23977  /* Check if a thread in this process holds such a lock */
23978  if( pFile->eFileLock>SHARED_LOCK ){
23979    /* Either this connection or some other connection in the same process
23980    ** holds a lock on the file.  No need to check further. */
23981    reserved = 1;
23982  }else{
23983    /* The lock is held if and only if the lockfile exists */
23984    const char *zLockFile = (const char*)pFile->lockingContext;
23985    reserved = access(zLockFile, 0)==0;
23986  }
23987  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
23988  *pResOut = reserved;
23989  return rc;
23990}
23991
23992/*
23993** Lock the file with the lock specified by parameter eFileLock - one
23994** of the following:
23995**
23996**     (1) SHARED_LOCK
23997**     (2) RESERVED_LOCK
23998**     (3) PENDING_LOCK
23999**     (4) EXCLUSIVE_LOCK
24000**
24001** Sometimes when requesting one lock state, additional lock states
24002** are inserted in between.  The locking might fail on one of the later
24003** transitions leaving the lock state different from what it started but
24004** still short of its goal.  The following chart shows the allowed
24005** transitions and the inserted intermediate states:
24006**
24007**    UNLOCKED -> SHARED
24008**    SHARED -> RESERVED
24009**    SHARED -> (PENDING) -> EXCLUSIVE
24010**    RESERVED -> (PENDING) -> EXCLUSIVE
24011**    PENDING -> EXCLUSIVE
24012**
24013** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24014** routine to lower a locking level.
24015**
24016** With dotfile locking, we really only support state (4): EXCLUSIVE.
24017** But we track the other locking levels internally.
24018*/
24019static int dotlockLock(sqlite3_file *id, int eFileLock) {
24020  unixFile *pFile = (unixFile*)id;
24021  int fd;
24022  char *zLockFile = (char *)pFile->lockingContext;
24023  int rc = SQLITE_OK;
24024
24025
24026  /* If we have any lock, then the lock file already exists.  All we have
24027  ** to do is adjust our internal record of the lock level.
24028  */
24029  if( pFile->eFileLock > NO_LOCK ){
24030    pFile->eFileLock = eFileLock;
24031#if !OS_VXWORKS
24032    /* Always update the timestamp on the old file */
24033    utimes(zLockFile, NULL);
24034#endif
24035    return SQLITE_OK;
24036  }
24037
24038  /* grab an exclusive lock */
24039  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24040  if( fd<0 ){
24041    /* failed to open/create the file, someone else may have stolen the lock */
24042    int tErrno = errno;
24043    if( EEXIST == tErrno ){
24044      rc = SQLITE_BUSY;
24045    } else {
24046      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24047      if( IS_LOCK_ERROR(rc) ){
24048        pFile->lastErrno = tErrno;
24049      }
24050    }
24051    return rc;
24052  }
24053  if( close(fd) ){
24054    pFile->lastErrno = errno;
24055    rc = SQLITE_IOERR_CLOSE;
24056  }
24057
24058  /* got it, set the type and return ok */
24059  pFile->eFileLock = eFileLock;
24060  return rc;
24061}
24062
24063/*
24064** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24065** must be either NO_LOCK or SHARED_LOCK.
24066**
24067** If the locking level of the file descriptor is already at or below
24068** the requested locking level, this routine is a no-op.
24069**
24070** When the locking level reaches NO_LOCK, delete the lock file.
24071*/
24072static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24073  unixFile *pFile = (unixFile*)id;
24074  char *zLockFile = (char *)pFile->lockingContext;
24075
24076  assert( pFile );
24077  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24078	   pFile->eFileLock, getpid()));
24079  assert( eFileLock<=SHARED_LOCK );
24080
24081  /* no-op if possible */
24082  if( pFile->eFileLock==eFileLock ){
24083    return SQLITE_OK;
24084  }
24085
24086  /* To downgrade to shared, simply update our internal notion of the
24087  ** lock state.  No need to mess with the file on disk.
24088  */
24089  if( eFileLock==SHARED_LOCK ){
24090    pFile->eFileLock = SHARED_LOCK;
24091    return SQLITE_OK;
24092  }
24093
24094  /* To fully unlock the database, delete the lock file */
24095  assert( eFileLock==NO_LOCK );
24096  if( unlink(zLockFile) ){
24097    int rc = 0;
24098    int tErrno = errno;
24099    if( ENOENT != tErrno ){
24100      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24101    }
24102    if( IS_LOCK_ERROR(rc) ){
24103      pFile->lastErrno = tErrno;
24104    }
24105    return rc;
24106  }
24107  pFile->eFileLock = NO_LOCK;
24108  return SQLITE_OK;
24109}
24110
24111/*
24112** Close a file.  Make sure the lock has been released before closing.
24113*/
24114static int dotlockClose(sqlite3_file *id) {
24115  int rc;
24116  if( id ){
24117    unixFile *pFile = (unixFile*)id;
24118    dotlockUnlock(id, NO_LOCK);
24119    sqlite3_free(pFile->lockingContext);
24120  }
24121  rc = closeUnixFile(id);
24122  return rc;
24123}
24124/****************** End of the dot-file lock implementation *******************
24125******************************************************************************/
24126
24127/******************************************************************************
24128************************** Begin flock Locking ********************************
24129**
24130** Use the flock() system call to do file locking.
24131**
24132** flock() locking is like dot-file locking in that the various
24133** fine-grain locking levels supported by SQLite are collapsed into
24134** a single exclusive lock.  In other words, SHARED, RESERVED, and
24135** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24136** still works when you do this, but concurrency is reduced since
24137** only a single process can be reading the database at a time.
24138**
24139** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24140** compiling for VXWORKS.
24141*/
24142#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24143
24144/*
24145** This routine checks if there is a RESERVED lock held on the specified
24146** file by this or any other process. If such a lock is held, set *pResOut
24147** to a non-zero value otherwise *pResOut is set to zero.  The return value
24148** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24149*/
24150static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24151  int rc = SQLITE_OK;
24152  int reserved = 0;
24153  unixFile *pFile = (unixFile*)id;
24154
24155  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24156
24157  assert( pFile );
24158
24159  /* Check if a thread in this process holds such a lock */
24160  if( pFile->eFileLock>SHARED_LOCK ){
24161    reserved = 1;
24162  }
24163
24164  /* Otherwise see if some other process holds it. */
24165  if( !reserved ){
24166    /* attempt to get the lock */
24167    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24168    if( !lrc ){
24169      /* got the lock, unlock it */
24170      lrc = flock(pFile->h, LOCK_UN);
24171      if ( lrc ) {
24172        int tErrno = errno;
24173        /* unlock failed with an error */
24174        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24175        if( IS_LOCK_ERROR(lrc) ){
24176          pFile->lastErrno = tErrno;
24177          rc = lrc;
24178        }
24179      }
24180    } else {
24181      int tErrno = errno;
24182      reserved = 1;
24183      /* someone else might have it reserved */
24184      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24185      if( IS_LOCK_ERROR(lrc) ){
24186        pFile->lastErrno = tErrno;
24187        rc = lrc;
24188      }
24189    }
24190  }
24191  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24192
24193#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24194  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24195    rc = SQLITE_OK;
24196    reserved=1;
24197  }
24198#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24199  *pResOut = reserved;
24200  return rc;
24201}
24202
24203/*
24204** Lock the file with the lock specified by parameter eFileLock - one
24205** of the following:
24206**
24207**     (1) SHARED_LOCK
24208**     (2) RESERVED_LOCK
24209**     (3) PENDING_LOCK
24210**     (4) EXCLUSIVE_LOCK
24211**
24212** Sometimes when requesting one lock state, additional lock states
24213** are inserted in between.  The locking might fail on one of the later
24214** transitions leaving the lock state different from what it started but
24215** still short of its goal.  The following chart shows the allowed
24216** transitions and the inserted intermediate states:
24217**
24218**    UNLOCKED -> SHARED
24219**    SHARED -> RESERVED
24220**    SHARED -> (PENDING) -> EXCLUSIVE
24221**    RESERVED -> (PENDING) -> EXCLUSIVE
24222**    PENDING -> EXCLUSIVE
24223**
24224** flock() only really support EXCLUSIVE locks.  We track intermediate
24225** lock states in the sqlite3_file structure, but all locks SHARED or
24226** above are really EXCLUSIVE locks and exclude all other processes from
24227** access the file.
24228**
24229** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24230** routine to lower a locking level.
24231*/
24232static int flockLock(sqlite3_file *id, int eFileLock) {
24233  int rc = SQLITE_OK;
24234  unixFile *pFile = (unixFile*)id;
24235
24236  assert( pFile );
24237
24238  /* if we already have a lock, it is exclusive.
24239  ** Just adjust level and punt on outta here. */
24240  if (pFile->eFileLock > NO_LOCK) {
24241    pFile->eFileLock = eFileLock;
24242    return SQLITE_OK;
24243  }
24244
24245  /* grab an exclusive lock */
24246
24247  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24248    int tErrno = errno;
24249    /* didn't get, must be busy */
24250    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24251    if( IS_LOCK_ERROR(rc) ){
24252      pFile->lastErrno = tErrno;
24253    }
24254  } else {
24255    /* got it, set the type and return ok */
24256    pFile->eFileLock = eFileLock;
24257  }
24258  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
24259           rc==SQLITE_OK ? "ok" : "failed"));
24260#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24261  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24262    rc = SQLITE_BUSY;
24263  }
24264#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24265  return rc;
24266}
24267
24268
24269/*
24270** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24271** must be either NO_LOCK or SHARED_LOCK.
24272**
24273** If the locking level of the file descriptor is already at or below
24274** the requested locking level, this routine is a no-op.
24275*/
24276static int flockUnlock(sqlite3_file *id, int eFileLock) {
24277  unixFile *pFile = (unixFile*)id;
24278
24279  assert( pFile );
24280  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24281           pFile->eFileLock, getpid()));
24282  assert( eFileLock<=SHARED_LOCK );
24283
24284  /* no-op if possible */
24285  if( pFile->eFileLock==eFileLock ){
24286    return SQLITE_OK;
24287  }
24288
24289  /* shared can just be set because we always have an exclusive */
24290  if (eFileLock==SHARED_LOCK) {
24291    pFile->eFileLock = eFileLock;
24292    return SQLITE_OK;
24293  }
24294
24295  /* no, really, unlock. */
24296  int rc = flock(pFile->h, LOCK_UN);
24297  if (rc) {
24298    int r, tErrno = errno;
24299    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24300    if( IS_LOCK_ERROR(r) ){
24301      pFile->lastErrno = tErrno;
24302    }
24303#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24304    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24305      r = SQLITE_BUSY;
24306    }
24307#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24308
24309    return r;
24310  } else {
24311    pFile->eFileLock = NO_LOCK;
24312    return SQLITE_OK;
24313  }
24314}
24315
24316/*
24317** Close a file.
24318*/
24319static int flockClose(sqlite3_file *id) {
24320  if( id ){
24321    flockUnlock(id, NO_LOCK);
24322  }
24323  return closeUnixFile(id);
24324}
24325
24326#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24327
24328/******************* End of the flock lock implementation *********************
24329******************************************************************************/
24330
24331/******************************************************************************
24332************************ Begin Named Semaphore Locking ************************
24333**
24334** Named semaphore locking is only supported on VxWorks.
24335**
24336** Semaphore locking is like dot-lock and flock in that it really only
24337** supports EXCLUSIVE locking.  Only a single process can read or write
24338** the database file at a time.  This reduces potential concurrency, but
24339** makes the lock implementation much easier.
24340*/
24341#if OS_VXWORKS
24342
24343/*
24344** This routine checks if there is a RESERVED lock held on the specified
24345** file by this or any other process. If such a lock is held, set *pResOut
24346** to a non-zero value otherwise *pResOut is set to zero.  The return value
24347** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24348*/
24349static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24350  int rc = SQLITE_OK;
24351  int reserved = 0;
24352  unixFile *pFile = (unixFile*)id;
24353
24354  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24355
24356  assert( pFile );
24357
24358  /* Check if a thread in this process holds such a lock */
24359  if( pFile->eFileLock>SHARED_LOCK ){
24360    reserved = 1;
24361  }
24362
24363  /* Otherwise see if some other process holds it. */
24364  if( !reserved ){
24365    sem_t *pSem = pFile->pInode->pSem;
24366    struct stat statBuf;
24367
24368    if( sem_trywait(pSem)==-1 ){
24369      int tErrno = errno;
24370      if( EAGAIN != tErrno ){
24371        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24372        pFile->lastErrno = tErrno;
24373      } else {
24374        /* someone else has the lock when we are in NO_LOCK */
24375        reserved = (pFile->eFileLock < SHARED_LOCK);
24376      }
24377    }else{
24378      /* we could have it if we want it */
24379      sem_post(pSem);
24380    }
24381  }
24382  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24383
24384  *pResOut = reserved;
24385  return rc;
24386}
24387
24388/*
24389** Lock the file with the lock specified by parameter eFileLock - one
24390** of the following:
24391**
24392**     (1) SHARED_LOCK
24393**     (2) RESERVED_LOCK
24394**     (3) PENDING_LOCK
24395**     (4) EXCLUSIVE_LOCK
24396**
24397** Sometimes when requesting one lock state, additional lock states
24398** are inserted in between.  The locking might fail on one of the later
24399** transitions leaving the lock state different from what it started but
24400** still short of its goal.  The following chart shows the allowed
24401** transitions and the inserted intermediate states:
24402**
24403**    UNLOCKED -> SHARED
24404**    SHARED -> RESERVED
24405**    SHARED -> (PENDING) -> EXCLUSIVE
24406**    RESERVED -> (PENDING) -> EXCLUSIVE
24407**    PENDING -> EXCLUSIVE
24408**
24409** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24410** lock states in the sqlite3_file structure, but all locks SHARED or
24411** above are really EXCLUSIVE locks and exclude all other processes from
24412** access the file.
24413**
24414** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24415** routine to lower a locking level.
24416*/
24417static int semLock(sqlite3_file *id, int eFileLock) {
24418  unixFile *pFile = (unixFile*)id;
24419  int fd;
24420  sem_t *pSem = pFile->pInode->pSem;
24421  int rc = SQLITE_OK;
24422
24423  /* if we already have a lock, it is exclusive.
24424  ** Just adjust level and punt on outta here. */
24425  if (pFile->eFileLock > NO_LOCK) {
24426    pFile->eFileLock = eFileLock;
24427    rc = SQLITE_OK;
24428    goto sem_end_lock;
24429  }
24430
24431  /* lock semaphore now but bail out when already locked. */
24432  if( sem_trywait(pSem)==-1 ){
24433    rc = SQLITE_BUSY;
24434    goto sem_end_lock;
24435  }
24436
24437  /* got it, set the type and return ok */
24438  pFile->eFileLock = eFileLock;
24439
24440 sem_end_lock:
24441  return rc;
24442}
24443
24444/*
24445** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24446** must be either NO_LOCK or SHARED_LOCK.
24447**
24448** If the locking level of the file descriptor is already at or below
24449** the requested locking level, this routine is a no-op.
24450*/
24451static int semUnlock(sqlite3_file *id, int eFileLock) {
24452  unixFile *pFile = (unixFile*)id;
24453  sem_t *pSem = pFile->pInode->pSem;
24454
24455  assert( pFile );
24456  assert( pSem );
24457  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24458	   pFile->eFileLock, getpid()));
24459  assert( eFileLock<=SHARED_LOCK );
24460
24461  /* no-op if possible */
24462  if( pFile->eFileLock==eFileLock ){
24463    return SQLITE_OK;
24464  }
24465
24466  /* shared can just be set because we always have an exclusive */
24467  if (eFileLock==SHARED_LOCK) {
24468    pFile->eFileLock = eFileLock;
24469    return SQLITE_OK;
24470  }
24471
24472  /* no, really unlock. */
24473  if ( sem_post(pSem)==-1 ) {
24474    int rc, tErrno = errno;
24475    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24476    if( IS_LOCK_ERROR(rc) ){
24477      pFile->lastErrno = tErrno;
24478    }
24479    return rc;
24480  }
24481  pFile->eFileLock = NO_LOCK;
24482  return SQLITE_OK;
24483}
24484
24485/*
24486 ** Close a file.
24487 */
24488static int semClose(sqlite3_file *id) {
24489  if( id ){
24490    unixFile *pFile = (unixFile*)id;
24491    semUnlock(id, NO_LOCK);
24492    assert( pFile );
24493    unixEnterMutex();
24494    releaseInodeInfo(pFile);
24495    unixLeaveMutex();
24496    closeUnixFile(id);
24497  }
24498  return SQLITE_OK;
24499}
24500
24501#endif /* OS_VXWORKS */
24502/*
24503** Named semaphore locking is only available on VxWorks.
24504**
24505*************** End of the named semaphore lock implementation ****************
24506******************************************************************************/
24507
24508
24509/******************************************************************************
24510*************************** Begin AFP Locking *********************************
24511**
24512** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24513** on Apple Macintosh computers - both OS9 and OSX.
24514**
24515** Third-party implementations of AFP are available.  But this code here
24516** only works on OSX.
24517*/
24518
24519#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24520/*
24521** The afpLockingContext structure contains all afp lock specific state
24522*/
24523typedef struct afpLockingContext afpLockingContext;
24524struct afpLockingContext {
24525  int reserved;
24526  const char *dbPath;             /* Name of the open file */
24527};
24528
24529struct ByteRangeLockPB2
24530{
24531  unsigned long long offset;        /* offset to first byte to lock */
24532  unsigned long long length;        /* nbr of bytes to lock */
24533  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24534  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24535  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24536  int fd;                           /* file desc to assoc this lock with */
24537};
24538
24539#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24540
24541/*
24542** This is a utility for setting or clearing a bit-range lock on an
24543** AFP filesystem.
24544**
24545** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24546*/
24547static int afpSetLock(
24548  const char *path,              /* Name of the file to be locked or unlocked */
24549  unixFile *pFile,               /* Open file descriptor on path */
24550  unsigned long long offset,     /* First byte to be locked */
24551  unsigned long long length,     /* Number of bytes to lock */
24552  int setLockFlag                /* True to set lock.  False to clear lock */
24553){
24554  struct ByteRangeLockPB2 pb;
24555  int err;
24556
24557  pb.unLockFlag = setLockFlag ? 0 : 1;
24558  pb.startEndFlag = 0;
24559  pb.offset = offset;
24560  pb.length = length;
24561  pb.fd = pFile->h;
24562
24563  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
24564    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24565    offset, length));
24566  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24567  if ( err==-1 ) {
24568    int rc;
24569    int tErrno = errno;
24570    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24571             path, tErrno, strerror(tErrno)));
24572#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24573    rc = SQLITE_BUSY;
24574#else
24575    rc = sqliteErrorFromPosixError(tErrno,
24576                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24577#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24578    if( IS_LOCK_ERROR(rc) ){
24579      pFile->lastErrno = tErrno;
24580    }
24581    return rc;
24582  } else {
24583    return SQLITE_OK;
24584  }
24585}
24586
24587/*
24588** This routine checks if there is a RESERVED lock held on the specified
24589** file by this or any other process. If such a lock is held, set *pResOut
24590** to a non-zero value otherwise *pResOut is set to zero.  The return value
24591** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24592*/
24593static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24594  int rc = SQLITE_OK;
24595  int reserved = 0;
24596  unixFile *pFile = (unixFile*)id;
24597
24598  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24599
24600  assert( pFile );
24601  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24602  if( context->reserved ){
24603    *pResOut = 1;
24604    return SQLITE_OK;
24605  }
24606  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24607
24608  /* Check if a thread in this process holds such a lock */
24609  if( pFile->pInode->eFileLock>SHARED_LOCK ){
24610    reserved = 1;
24611  }
24612
24613  /* Otherwise see if some other process holds it.
24614   */
24615  if( !reserved ){
24616    /* lock the RESERVED byte */
24617    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24618    if( SQLITE_OK==lrc ){
24619      /* if we succeeded in taking the reserved lock, unlock it to restore
24620      ** the original state */
24621      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24622    } else {
24623      /* if we failed to get the lock then someone else must have it */
24624      reserved = 1;
24625    }
24626    if( IS_LOCK_ERROR(lrc) ){
24627      rc=lrc;
24628    }
24629  }
24630
24631  unixLeaveMutex();
24632  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
24633
24634  *pResOut = reserved;
24635  return rc;
24636}
24637
24638/*
24639** Lock the file with the lock specified by parameter eFileLock - one
24640** of the following:
24641**
24642**     (1) SHARED_LOCK
24643**     (2) RESERVED_LOCK
24644**     (3) PENDING_LOCK
24645**     (4) EXCLUSIVE_LOCK
24646**
24647** Sometimes when requesting one lock state, additional lock states
24648** are inserted in between.  The locking might fail on one of the later
24649** transitions leaving the lock state different from what it started but
24650** still short of its goal.  The following chart shows the allowed
24651** transitions and the inserted intermediate states:
24652**
24653**    UNLOCKED -> SHARED
24654**    SHARED -> RESERVED
24655**    SHARED -> (PENDING) -> EXCLUSIVE
24656**    RESERVED -> (PENDING) -> EXCLUSIVE
24657**    PENDING -> EXCLUSIVE
24658**
24659** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24660** routine to lower a locking level.
24661*/
24662static int afpLock(sqlite3_file *id, int eFileLock){
24663  int rc = SQLITE_OK;
24664  unixFile *pFile = (unixFile*)id;
24665  unixInodeInfo *pInode = pFile->pInode;
24666  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24667
24668  assert( pFile );
24669  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24670           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24671           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24672
24673  /* If there is already a lock of this type or more restrictive on the
24674  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24675  ** unixEnterMutex() hasn't been called yet.
24676  */
24677  if( pFile->eFileLock>=eFileLock ){
24678    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24679           azFileLock(eFileLock)));
24680    return SQLITE_OK;
24681  }
24682
24683  /* Make sure the locking sequence is correct
24684  **  (1) We never move from unlocked to anything higher than shared lock.
24685  **  (2) SQLite never explicitly requests a pendig lock.
24686  **  (3) A shared lock is always held when a reserve lock is requested.
24687  */
24688  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24689  assert( eFileLock!=PENDING_LOCK );
24690  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24691
24692  /* This mutex is needed because pFile->pInode is shared across threads
24693  */
24694  unixEnterMutex();
24695  pInode = pFile->pInode;
24696
24697  /* If some thread using this PID has a lock via a different unixFile*
24698  ** handle that precludes the requested lock, return BUSY.
24699  */
24700  if( (pFile->eFileLock!=pInode->eFileLock &&
24701       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24702     ){
24703    rc = SQLITE_BUSY;
24704    goto afp_end_lock;
24705  }
24706
24707  /* If a SHARED lock is requested, and some thread using this PID already
24708  ** has a SHARED or RESERVED lock, then increment reference counts and
24709  ** return SQLITE_OK.
24710  */
24711  if( eFileLock==SHARED_LOCK &&
24712     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24713    assert( eFileLock==SHARED_LOCK );
24714    assert( pFile->eFileLock==0 );
24715    assert( pInode->nShared>0 );
24716    pFile->eFileLock = SHARED_LOCK;
24717    pInode->nShared++;
24718    pInode->nLock++;
24719    goto afp_end_lock;
24720  }
24721
24722  /* A PENDING lock is needed before acquiring a SHARED lock and before
24723  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24724  ** be released.
24725  */
24726  if( eFileLock==SHARED_LOCK
24727      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24728  ){
24729    int failed;
24730    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24731    if (failed) {
24732      rc = failed;
24733      goto afp_end_lock;
24734    }
24735  }
24736
24737  /* If control gets to this point, then actually go ahead and make
24738  ** operating system calls for the specified lock.
24739  */
24740  if( eFileLock==SHARED_LOCK ){
24741    int lrc1, lrc2, lrc1Errno;
24742    long lk, mask;
24743
24744    assert( pInode->nShared==0 );
24745    assert( pInode->eFileLock==0 );
24746
24747    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24748    /* Now get the read-lock SHARED_LOCK */
24749    /* note that the quality of the randomness doesn't matter that much */
24750    lk = random();
24751    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24752    lrc1 = afpSetLock(context->dbPath, pFile,
24753          SHARED_FIRST+pInode->sharedByte, 1, 1);
24754    if( IS_LOCK_ERROR(lrc1) ){
24755      lrc1Errno = pFile->lastErrno;
24756    }
24757    /* Drop the temporary PENDING lock */
24758    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24759
24760    if( IS_LOCK_ERROR(lrc1) ) {
24761      pFile->lastErrno = lrc1Errno;
24762      rc = lrc1;
24763      goto afp_end_lock;
24764    } else if( IS_LOCK_ERROR(lrc2) ){
24765      rc = lrc2;
24766      goto afp_end_lock;
24767    } else if( lrc1 != SQLITE_OK ) {
24768      rc = lrc1;
24769    } else {
24770      pFile->eFileLock = SHARED_LOCK;
24771      pInode->nLock++;
24772      pInode->nShared = 1;
24773    }
24774  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24775    /* We are trying for an exclusive lock but another thread in this
24776     ** same process is still holding a shared lock. */
24777    rc = SQLITE_BUSY;
24778  }else{
24779    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24780    ** assumed that there is a SHARED or greater lock on the file
24781    ** already.
24782    */
24783    int failed = 0;
24784    assert( 0!=pFile->eFileLock );
24785    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
24786        /* Acquire a RESERVED lock */
24787        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24788      if( !failed ){
24789        context->reserved = 1;
24790      }
24791    }
24792    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
24793      /* Acquire an EXCLUSIVE lock */
24794
24795      /* Remove the shared lock before trying the range.  we'll need to
24796      ** reestablish the shared lock if we can't get the  afpUnlock
24797      */
24798      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24799                         pInode->sharedByte, 1, 0)) ){
24800        int failed2 = SQLITE_OK;
24801        /* now attemmpt to get the exclusive lock range */
24802        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
24803                               SHARED_SIZE, 1);
24804        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
24805                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
24806          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24807          ** a critical I/O error
24808          */
24809          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
24810               SQLITE_IOERR_LOCK;
24811          goto afp_end_lock;
24812        }
24813      }else{
24814        rc = failed;
24815      }
24816    }
24817    if( failed ){
24818      rc = failed;
24819    }
24820  }
24821
24822  if( rc==SQLITE_OK ){
24823    pFile->eFileLock = eFileLock;
24824    pInode->eFileLock = eFileLock;
24825  }else if( eFileLock==EXCLUSIVE_LOCK ){
24826    pFile->eFileLock = PENDING_LOCK;
24827    pInode->eFileLock = PENDING_LOCK;
24828  }
24829
24830afp_end_lock:
24831  unixLeaveMutex();
24832  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
24833         rc==SQLITE_OK ? "ok" : "failed"));
24834  return rc;
24835}
24836
24837/*
24838** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24839** must be either NO_LOCK or SHARED_LOCK.
24840**
24841** If the locking level of the file descriptor is already at or below
24842** the requested locking level, this routine is a no-op.
24843*/
24844static int afpUnlock(sqlite3_file *id, int eFileLock) {
24845  int rc = SQLITE_OK;
24846  unixFile *pFile = (unixFile*)id;
24847  unixInodeInfo *pInode;
24848  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24849  int skipShared = 0;
24850#ifdef SQLITE_TEST
24851  int h = pFile->h;
24852#endif
24853
24854  assert( pFile );
24855  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
24856           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24857           getpid()));
24858
24859  assert( eFileLock<=SHARED_LOCK );
24860  if( pFile->eFileLock<=eFileLock ){
24861    return SQLITE_OK;
24862  }
24863  unixEnterMutex();
24864  pInode = pFile->pInode;
24865  assert( pInode->nShared!=0 );
24866  if( pFile->eFileLock>SHARED_LOCK ){
24867    assert( pInode->eFileLock==pFile->eFileLock );
24868    SimulateIOErrorBenign(1);
24869    SimulateIOError( h=(-1) )
24870    SimulateIOErrorBenign(0);
24871
24872#ifndef NDEBUG
24873    /* When reducing a lock such that other processes can start
24874    ** reading the database file again, make sure that the
24875    ** transaction counter was updated if any part of the database
24876    ** file changed.  If the transaction counter is not updated,
24877    ** other connections to the same file might not realize that
24878    ** the file has changed and hence might not know to flush their
24879    ** cache.  The use of a stale cache can lead to database corruption.
24880    */
24881    assert( pFile->inNormalWrite==0
24882           || pFile->dbUpdate==0
24883           || pFile->transCntrChng==1 );
24884    pFile->inNormalWrite = 0;
24885#endif
24886
24887    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
24888      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24889      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
24890        /* only re-establish the shared lock if necessary */
24891        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24892        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
24893      } else {
24894        skipShared = 1;
24895      }
24896    }
24897    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
24898      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24899    }
24900    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
24901      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24902      if( !rc ){
24903        context->reserved = 0;
24904      }
24905    }
24906    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
24907      pInode->eFileLock = SHARED_LOCK;
24908    }
24909  }
24910  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
24911
24912    /* Decrement the shared lock counter.  Release the lock using an
24913    ** OS call only when all threads in this same process have released
24914    ** the lock.
24915    */
24916    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24917    pInode->nShared--;
24918    if( pInode->nShared==0 ){
24919      SimulateIOErrorBenign(1);
24920      SimulateIOError( h=(-1) )
24921      SimulateIOErrorBenign(0);
24922      if( !skipShared ){
24923        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
24924      }
24925      if( !rc ){
24926        pInode->eFileLock = NO_LOCK;
24927        pFile->eFileLock = NO_LOCK;
24928      }
24929    }
24930    if( rc==SQLITE_OK ){
24931      pInode->nLock--;
24932      assert( pInode->nLock>=0 );
24933      if( pInode->nLock==0 ){
24934        rc = closePendingFds(pFile);
24935      }
24936    }
24937  }
24938
24939  unixLeaveMutex();
24940  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24941  return rc;
24942}
24943
24944/*
24945** Close a file & cleanup AFP specific locking context
24946*/
24947static int afpClose(sqlite3_file *id) {
24948  int rc = SQLITE_OK;
24949  if( id ){
24950    unixFile *pFile = (unixFile*)id;
24951    afpUnlock(id, NO_LOCK);
24952    unixEnterMutex();
24953    if( pFile->pInode && pFile->pInode->nLock ){
24954      /* If there are outstanding locks, do not actually close the file just
24955      ** yet because that would clear those locks.  Instead, add the file
24956      ** descriptor to pInode->aPending.  It will be automatically closed when
24957      ** the last lock is cleared.
24958      */
24959      setPendingFd(pFile);
24960    }
24961    releaseInodeInfo(pFile);
24962    sqlite3_free(pFile->lockingContext);
24963    rc = closeUnixFile(id);
24964    unixLeaveMutex();
24965  }
24966  return rc;
24967}
24968
24969#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24970/*
24971** The code above is the AFP lock implementation.  The code is specific
24972** to MacOSX and does not work on other unix platforms.  No alternative
24973** is available.  If you don't compile for a mac, then the "unix-afp"
24974** VFS is not available.
24975**
24976********************* End of the AFP lock implementation **********************
24977******************************************************************************/
24978
24979/******************************************************************************
24980*************************** Begin NFS Locking ********************************/
24981
24982#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24983/*
24984 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24985 ** must be either NO_LOCK or SHARED_LOCK.
24986 **
24987 ** If the locking level of the file descriptor is already at or below
24988 ** the requested locking level, this routine is a no-op.
24989 */
24990static int nfsUnlock(sqlite3_file *id, int eFileLock){
24991  return _posixUnlock(id, eFileLock, 1);
24992}
24993
24994#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24995/*
24996** The code above is the NFS lock implementation.  The code is specific
24997** to MacOSX and does not work on other unix platforms.  No alternative
24998** is available.
24999**
25000********************* End of the NFS lock implementation **********************
25001******************************************************************************/
25002
25003/******************************************************************************
25004**************** Non-locking sqlite3_file methods *****************************
25005**
25006** The next division contains implementations for all methods of the
25007** sqlite3_file object other than the locking methods.  The locking
25008** methods were defined in divisions above (one locking method per
25009** division).  Those methods that are common to all locking modes
25010** are gather together into this division.
25011*/
25012
25013/*
25014** Seek to the offset passed as the second argument, then read cnt
25015** bytes into pBuf. Return the number of bytes actually read.
25016**
25017** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25018** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25019** one system to another.  Since SQLite does not define USE_PREAD
25020** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25021** See tickets #2741 and #2681.
25022**
25023** To avoid stomping the errno value on a failed read the lastErrno value
25024** is set before returning.
25025*/
25026static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25027  int got;
25028#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25029  i64 newOffset;
25030#endif
25031  TIMER_START;
25032#if defined(USE_PREAD)
25033  got = pread(id->h, pBuf, cnt, offset);
25034  SimulateIOError( got = -1 );
25035#elif defined(USE_PREAD64)
25036  got = pread64(id->h, pBuf, cnt, offset);
25037  SimulateIOError( got = -1 );
25038#else
25039  newOffset = lseek(id->h, offset, SEEK_SET);
25040  SimulateIOError( newOffset-- );
25041  if( newOffset!=offset ){
25042    if( newOffset == -1 ){
25043      ((unixFile*)id)->lastErrno = errno;
25044    }else{
25045      ((unixFile*)id)->lastErrno = 0;
25046    }
25047    return -1;
25048  }
25049  got = read(id->h, pBuf, cnt);
25050#endif
25051  TIMER_END;
25052  if( got<0 ){
25053    ((unixFile*)id)->lastErrno = errno;
25054  }
25055  OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25056  return got;
25057}
25058
25059/*
25060** Read data from a file into a buffer.  Return SQLITE_OK if all
25061** bytes were read successfully and SQLITE_IOERR if anything goes
25062** wrong.
25063*/
25064static int unixRead(
25065  sqlite3_file *id,
25066  void *pBuf,
25067  int amt,
25068  sqlite3_int64 offset
25069){
25070  unixFile *pFile = (unixFile *)id;
25071  int got;
25072  assert( id );
25073
25074  /* If this is a database file (not a journal, master-journal or temp
25075  ** file), the bytes in the locking range should never be read or written. */
25076#if 0
25077  assert( pFile->pUnused==0
25078       || offset>=PENDING_BYTE+512
25079       || offset+amt<=PENDING_BYTE
25080  );
25081#endif
25082
25083  got = seekAndRead(pFile, offset, pBuf, amt);
25084  if( got==amt ){
25085    return SQLITE_OK;
25086  }else if( got<0 ){
25087    /* lastErrno set by seekAndRead */
25088    return SQLITE_IOERR_READ;
25089  }else{
25090    pFile->lastErrno = 0; /* not a system error */
25091    /* Unread parts of the buffer must be zero-filled */
25092    memset(&((char*)pBuf)[got], 0, amt-got);
25093    return SQLITE_IOERR_SHORT_READ;
25094  }
25095}
25096
25097/*
25098** Seek to the offset in id->offset then read cnt bytes into pBuf.
25099** Return the number of bytes actually read.  Update the offset.
25100**
25101** To avoid stomping the errno value on a failed write the lastErrno value
25102** is set before returning.
25103*/
25104static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25105  int got;
25106#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25107  i64 newOffset;
25108#endif
25109  TIMER_START;
25110#if defined(USE_PREAD)
25111  got = pwrite(id->h, pBuf, cnt, offset);
25112#elif defined(USE_PREAD64)
25113  got = pwrite64(id->h, pBuf, cnt, offset);
25114#else
25115  newOffset = lseek(id->h, offset, SEEK_SET);
25116  if( newOffset!=offset ){
25117    if( newOffset == -1 ){
25118      ((unixFile*)id)->lastErrno = errno;
25119    }else{
25120      ((unixFile*)id)->lastErrno = 0;
25121    }
25122    return -1;
25123  }
25124  got = write(id->h, pBuf, cnt);
25125#endif
25126  TIMER_END;
25127  if( got<0 ){
25128    ((unixFile*)id)->lastErrno = errno;
25129  }
25130
25131  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25132  return got;
25133}
25134
25135
25136/*
25137** Write data from a buffer into a file.  Return SQLITE_OK on success
25138** or some other error code on failure.
25139*/
25140static int unixWrite(
25141  sqlite3_file *id,
25142  const void *pBuf,
25143  int amt,
25144  sqlite3_int64 offset
25145){
25146  unixFile *pFile = (unixFile*)id;
25147  int wrote = 0;
25148  assert( id );
25149  assert( amt>0 );
25150
25151  /* If this is a database file (not a journal, master-journal or temp
25152  ** file), the bytes in the locking range should never be read or written. */
25153#if 0
25154  assert( pFile->pUnused==0
25155       || offset>=PENDING_BYTE+512
25156       || offset+amt<=PENDING_BYTE
25157  );
25158#endif
25159
25160#ifndef NDEBUG
25161  /* If we are doing a normal write to a database file (as opposed to
25162  ** doing a hot-journal rollback or a write to some file other than a
25163  ** normal database file) then record the fact that the database
25164  ** has changed.  If the transaction counter is modified, record that
25165  ** fact too.
25166  */
25167  if( pFile->inNormalWrite ){
25168    pFile->dbUpdate = 1;  /* The database has been modified */
25169    if( offset<=24 && offset+amt>=27 ){
25170      int rc;
25171      char oldCntr[4];
25172      SimulateIOErrorBenign(1);
25173      rc = seekAndRead(pFile, 24, oldCntr, 4);
25174      SimulateIOErrorBenign(0);
25175      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25176        pFile->transCntrChng = 1;  /* The transaction counter has changed */
25177      }
25178    }
25179  }
25180#endif
25181
25182  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25183    amt -= wrote;
25184    offset += wrote;
25185    pBuf = &((char*)pBuf)[wrote];
25186  }
25187  SimulateIOError(( wrote=(-1), amt=1 ));
25188  SimulateDiskfullError(( wrote=0, amt=1 ));
25189  if( amt>0 ){
25190    if( wrote<0 ){
25191      /* lastErrno set by seekAndWrite */
25192      return SQLITE_IOERR_WRITE;
25193    }else{
25194      pFile->lastErrno = 0; /* not a system error */
25195      return SQLITE_FULL;
25196    }
25197  }
25198  return SQLITE_OK;
25199}
25200
25201#ifdef SQLITE_TEST
25202/*
25203** Count the number of fullsyncs and normal syncs.  This is used to test
25204** that syncs and fullsyncs are occurring at the right times.
25205*/
25206SQLITE_API int sqlite3_sync_count = 0;
25207SQLITE_API int sqlite3_fullsync_count = 0;
25208#endif
25209
25210/*
25211** We do not trust systems to provide a working fdatasync().  Some do.
25212** Others do no.  To be safe, we will stick with the (slower) fsync().
25213** If you know that your system does support fdatasync() correctly,
25214** then simply compile with -Dfdatasync=fdatasync
25215*/
25216#if !defined(fdatasync) && !defined(__linux__)
25217# define fdatasync fsync
25218#endif
25219
25220/*
25221** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25222** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25223** only available on Mac OS X.  But that could change.
25224*/
25225#ifdef F_FULLFSYNC
25226# define HAVE_FULLFSYNC 1
25227#else
25228# define HAVE_FULLFSYNC 0
25229#endif
25230
25231
25232/*
25233** The fsync() system call does not work as advertised on many
25234** unix systems.  The following procedure is an attempt to make
25235** it work better.
25236**
25237** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25238** for testing when we want to run through the test suite quickly.
25239** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25240** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25241** or power failure will likely corrupt the database file.
25242**
25243** SQLite sets the dataOnly flag if the size of the file is unchanged.
25244** The idea behind dataOnly is that it should only write the file content
25245** to disk, not the inode.  We only set dataOnly if the file size is
25246** unchanged since the file size is part of the inode.  However,
25247** Ted Ts'o tells us that fdatasync() will also write the inode if the
25248** file size has changed.  The only real difference between fdatasync()
25249** and fsync(), Ted tells us, is that fdatasync() will not flush the
25250** inode if the mtime or owner or other inode attributes have changed.
25251** We only care about the file size, not the other file attributes, so
25252** as far as SQLite is concerned, an fdatasync() is always adequate.
25253** So, we always use fdatasync() if it is available, regardless of
25254** the value of the dataOnly flag.
25255*/
25256static int full_fsync(int fd, int fullSync, int dataOnly){
25257  int rc;
25258
25259  /* The following "ifdef/elif/else/" block has the same structure as
25260  ** the one below. It is replicated here solely to avoid cluttering
25261  ** up the real code with the UNUSED_PARAMETER() macros.
25262  */
25263#ifdef SQLITE_NO_SYNC
25264  UNUSED_PARAMETER(fd);
25265  UNUSED_PARAMETER(fullSync);
25266  UNUSED_PARAMETER(dataOnly);
25267#elif HAVE_FULLFSYNC
25268  UNUSED_PARAMETER(dataOnly);
25269#else
25270  UNUSED_PARAMETER(fullSync);
25271  UNUSED_PARAMETER(dataOnly);
25272#endif
25273
25274  /* Record the number of times that we do a normal fsync() and
25275  ** FULLSYNC.  This is used during testing to verify that this procedure
25276  ** gets called with the correct arguments.
25277  */
25278#ifdef SQLITE_TEST
25279  if( fullSync ) sqlite3_fullsync_count++;
25280  sqlite3_sync_count++;
25281#endif
25282
25283  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25284  ** no-op
25285  */
25286#ifdef SQLITE_NO_SYNC
25287  rc = SQLITE_OK;
25288#elif HAVE_FULLFSYNC
25289  if( fullSync ){
25290    rc = fcntl(fd, F_FULLFSYNC, 0);
25291  }else{
25292    rc = 1;
25293  }
25294  /* If the FULLFSYNC failed, fall back to attempting an fsync().
25295  ** It shouldn't be possible for fullfsync to fail on the local
25296  ** file system (on OSX), so failure indicates that FULLFSYNC
25297  ** isn't supported for this file system. So, attempt an fsync
25298  ** and (for now) ignore the overhead of a superfluous fcntl call.
25299  ** It'd be better to detect fullfsync support once and avoid
25300  ** the fcntl call every time sync is called.
25301  */
25302  if( rc ) rc = fsync(fd);
25303
25304#elif defined(__APPLE__)
25305  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25306  ** so currently we default to the macro that redefines fdatasync to fsync
25307  */
25308  rc = fsync(fd);
25309#else
25310  rc = fdatasync(fd);
25311#if OS_VXWORKS
25312  if( rc==-1 && errno==ENOTSUP ){
25313    rc = fsync(fd);
25314  }
25315#endif /* OS_VXWORKS */
25316#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25317
25318  if( OS_VXWORKS && rc!= -1 ){
25319    rc = 0;
25320  }
25321  return rc;
25322}
25323
25324/*
25325** Make sure all writes to a particular file are committed to disk.
25326**
25327** If dataOnly==0 then both the file itself and its metadata (file
25328** size, access time, etc) are synced.  If dataOnly!=0 then only the
25329** file data is synced.
25330**
25331** Under Unix, also make sure that the directory entry for the file
25332** has been created by fsync-ing the directory that contains the file.
25333** If we do not do this and we encounter a power failure, the directory
25334** entry for the journal might not exist after we reboot.  The next
25335** SQLite to access the file will not know that the journal exists (because
25336** the directory entry for the journal was never created) and the transaction
25337** will not roll back - possibly leading to database corruption.
25338*/
25339static int unixSync(sqlite3_file *id, int flags){
25340  int rc;
25341  unixFile *pFile = (unixFile*)id;
25342
25343  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25344  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25345
25346  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25347  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25348      || (flags&0x0F)==SQLITE_SYNC_FULL
25349  );
25350
25351  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25352  ** line is to test that doing so does not cause any problems.
25353  */
25354  SimulateDiskfullError( return SQLITE_FULL );
25355
25356  assert( pFile );
25357  OSTRACE(("SYNC    %-3d\n", pFile->h));
25358  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25359  SimulateIOError( rc=1 );
25360  if( rc ){
25361    pFile->lastErrno = errno;
25362    return SQLITE_IOERR_FSYNC;
25363  }
25364  if( pFile->dirfd>=0 ){
25365    int err;
25366    OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25367            HAVE_FULLFSYNC, isFullsync));
25368#ifndef SQLITE_DISABLE_DIRSYNC
25369    /* The directory sync is only attempted if full_fsync is
25370    ** turned off or unavailable.  If a full_fsync occurred above,
25371    ** then the directory sync is superfluous.
25372    */
25373    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25374       /*
25375       ** We have received multiple reports of fsync() returning
25376       ** errors when applied to directories on certain file systems.
25377       ** A failed directory sync is not a big deal.  So it seems
25378       ** better to ignore the error.  Ticket #1657
25379       */
25380       /* pFile->lastErrno = errno; */
25381       /* return SQLITE_IOERR; */
25382    }
25383#endif
25384    err = close(pFile->dirfd); /* Only need to sync once, so close the */
25385    if( err==0 ){              /* directory when we are done */
25386      pFile->dirfd = -1;
25387    }else{
25388      pFile->lastErrno = errno;
25389      rc = SQLITE_IOERR_DIR_CLOSE;
25390    }
25391  }
25392  return rc;
25393}
25394
25395/*
25396** Truncate an open file to a specified size
25397*/
25398static int unixTruncate(sqlite3_file *id, i64 nByte){
25399  int rc;
25400  assert( id );
25401  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25402  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25403  if( rc ){
25404    ((unixFile*)id)->lastErrno = errno;
25405    return SQLITE_IOERR_TRUNCATE;
25406  }else{
25407#ifndef NDEBUG
25408    /* If we are doing a normal write to a database file (as opposed to
25409    ** doing a hot-journal rollback or a write to some file other than a
25410    ** normal database file) and we truncate the file to zero length,
25411    ** that effectively updates the change counter.  This might happen
25412    ** when restoring a database using the backup API from a zero-length
25413    ** source.
25414    */
25415    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
25416      ((unixFile*)id)->transCntrChng = 1;
25417    }
25418#endif
25419
25420    return SQLITE_OK;
25421  }
25422}
25423
25424/*
25425** Determine the current size of a file in bytes
25426*/
25427static int unixFileSize(sqlite3_file *id, i64 *pSize){
25428  int rc;
25429  struct stat buf;
25430  assert( id );
25431  rc = fstat(((unixFile*)id)->h, &buf);
25432  SimulateIOError( rc=1 );
25433  if( rc!=0 ){
25434    ((unixFile*)id)->lastErrno = errno;
25435    return SQLITE_IOERR_FSTAT;
25436  }
25437  *pSize = buf.st_size;
25438
25439  /* When opening a zero-size database, the findInodeInfo() procedure
25440  ** writes a single byte into that file in order to work around a bug
25441  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25442  ** layers, we need to report this file size as zero even though it is
25443  ** really 1.   Ticket #3260.
25444  */
25445  if( *pSize==1 ) *pSize = 0;
25446
25447
25448  return SQLITE_OK;
25449}
25450
25451#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25452/*
25453** Handler for proxy-locking file-control verbs.  Defined below in the
25454** proxying locking division.
25455*/
25456static int proxyFileControl(sqlite3_file*,int,void*);
25457#endif
25458
25459
25460/*
25461** Information and control of an open file handle.
25462*/
25463static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25464  switch( op ){
25465    case SQLITE_FCNTL_LOCKSTATE: {
25466      *(int*)pArg = ((unixFile*)id)->eFileLock;
25467      return SQLITE_OK;
25468    }
25469    case SQLITE_LAST_ERRNO: {
25470      *(int*)pArg = ((unixFile*)id)->lastErrno;
25471      return SQLITE_OK;
25472    }
25473    case SQLITE_FCNTL_SIZE_HINT: {
25474#if 0 /* No performance advantage seen on Linux */
25475      sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
25476      unixFile *pFile = (unixFile*)id;
25477      ftruncate(pFile->h, szFile);
25478#endif
25479      return SQLITE_OK;
25480    }
25481#ifndef NDEBUG
25482    /* The pager calls this method to signal that it has done
25483    ** a rollback and that the database is therefore unchanged and
25484    ** it hence it is OK for the transaction change counter to be
25485    ** unchanged.
25486    */
25487    case SQLITE_FCNTL_DB_UNCHANGED: {
25488      ((unixFile*)id)->dbUpdate = 0;
25489      return SQLITE_OK;
25490    }
25491#endif
25492#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25493    case SQLITE_SET_LOCKPROXYFILE:
25494    case SQLITE_GET_LOCKPROXYFILE: {
25495      return proxyFileControl(id,op,pArg);
25496    }
25497#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25498  }
25499  return SQLITE_ERROR;
25500}
25501
25502/*
25503** Return the sector size in bytes of the underlying block device for
25504** the specified file. This is almost always 512 bytes, but may be
25505** larger for some devices.
25506**
25507** SQLite code assumes this function cannot fail. It also assumes that
25508** if two files are created in the same file-system directory (i.e.
25509** a database and its journal file) that the sector size will be the
25510** same for both.
25511*/
25512static int unixSectorSize(sqlite3_file *NotUsed){
25513  UNUSED_PARAMETER(NotUsed);
25514  return SQLITE_DEFAULT_SECTOR_SIZE;
25515}
25516
25517/*
25518** Return the device characteristics for the file. This is always 0 for unix.
25519*/
25520static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25521  UNUSED_PARAMETER(NotUsed);
25522  return 0;
25523}
25524
25525#ifndef SQLITE_OMIT_WAL
25526
25527
25528/*
25529** Object used to represent an shared memory buffer.
25530**
25531** When multiple threads all reference the same wal-index, each thread
25532** has its own unixShm object, but they all point to a single instance
25533** of this unixShmNode object.  In other words, each wal-index is opened
25534** only once per process.
25535**
25536** Each unixShmNode object is connected to a single unixInodeInfo object.
25537** We could coalesce this object into unixInodeInfo, but that would mean
25538** every open file that does not use shared memory (in other words, most
25539** open files) would have to carry around this extra information.  So
25540** the unixInodeInfo object contains a pointer to this unixShmNode object
25541** and the unixShmNode object is created only when needed.
25542**
25543** unixMutexHeld() must be true when creating or destroying
25544** this object or while reading or writing the following fields:
25545**
25546**      nRef
25547**
25548** The following fields are read-only after the object is created:
25549**
25550**      fid
25551**      zFilename
25552**
25553** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
25554** unixMutexHeld() is true when reading or writing any other field
25555** in this structure.
25556*/
25557struct unixShmNode {
25558  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
25559  sqlite3_mutex *mutex;      /* Mutex to access this object */
25560  char *zFilename;           /* Name of the mmapped file */
25561  int h;                     /* Open file descriptor */
25562  int szRegion;              /* Size of shared-memory regions */
25563  int nRegion;               /* Size of array apRegion */
25564  char **apRegion;           /* Array of mapped shared-memory regions */
25565  int nRef;                  /* Number of unixShm objects pointing to this */
25566  unixShm *pFirst;           /* All unixShm objects pointing to this */
25567#ifdef SQLITE_DEBUG
25568  u8 exclMask;               /* Mask of exclusive locks held */
25569  u8 sharedMask;             /* Mask of shared locks held */
25570  u8 nextShmId;              /* Next available unixShm.id value */
25571#endif
25572};
25573
25574/*
25575** Structure used internally by this VFS to record the state of an
25576** open shared memory connection.
25577**
25578** The following fields are initialized when this object is created and
25579** are read-only thereafter:
25580**
25581**    unixShm.pFile
25582**    unixShm.id
25583**
25584** All other fields are read/write.  The unixShm.pFile->mutex must be held
25585** while accessing any read/write fields.
25586*/
25587struct unixShm {
25588  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
25589  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
25590  u8 hasMutex;               /* True if holding the unixShmNode mutex */
25591  u16 sharedMask;            /* Mask of shared locks held */
25592  u16 exclMask;              /* Mask of exclusive locks held */
25593#ifdef SQLITE_DEBUG
25594  u8 id;                     /* Id of this connection within its unixShmNode */
25595#endif
25596};
25597
25598/*
25599** Constants used for locking
25600*/
25601#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
25602#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
25603
25604/*
25605** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
25606**
25607** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
25608** otherwise.
25609*/
25610static int unixShmSystemLock(
25611  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
25612  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
25613  int ofst,              /* First byte of the locking range */
25614  int n                  /* Number of bytes to lock */
25615){
25616  struct flock f;       /* The posix advisory locking structure */
25617  int rc = SQLITE_OK;   /* Result code form fcntl() */
25618
25619  /* Access to the unixShmNode object is serialized by the caller */
25620  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
25621
25622  /* Shared locks never span more than one byte */
25623  assert( n==1 || lockType!=F_RDLCK );
25624
25625  /* Locks are within range */
25626  assert( n>=1 && n<SQLITE_SHM_NLOCK );
25627
25628  /* Initialize the locking parameters */
25629  memset(&f, 0, sizeof(f));
25630  f.l_type = lockType;
25631  f.l_whence = SEEK_SET;
25632  f.l_start = ofst;
25633  f.l_len = n;
25634
25635  rc = fcntl(pShmNode->h, F_SETLK, &f);
25636  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
25637
25638  /* Update the global lock state and do debug tracing */
25639#ifdef SQLITE_DEBUG
25640  { u16 mask;
25641  OSTRACE(("SHM-LOCK "));
25642  mask = (1<<(ofst+n)) - (1<<ofst);
25643  if( rc==SQLITE_OK ){
25644    if( lockType==F_UNLCK ){
25645      OSTRACE(("unlock %d ok", ofst));
25646      pShmNode->exclMask &= ~mask;
25647      pShmNode->sharedMask &= ~mask;
25648    }else if( lockType==F_RDLCK ){
25649      OSTRACE(("read-lock %d ok", ofst));
25650      pShmNode->exclMask &= ~mask;
25651      pShmNode->sharedMask |= mask;
25652    }else{
25653      assert( lockType==F_WRLCK );
25654      OSTRACE(("write-lock %d ok", ofst));
25655      pShmNode->exclMask |= mask;
25656      pShmNode->sharedMask &= ~mask;
25657    }
25658  }else{
25659    if( lockType==F_UNLCK ){
25660      OSTRACE(("unlock %d failed", ofst));
25661    }else if( lockType==F_RDLCK ){
25662      OSTRACE(("read-lock failed"));
25663    }else{
25664      assert( lockType==F_WRLCK );
25665      OSTRACE(("write-lock %d failed", ofst));
25666    }
25667  }
25668  OSTRACE((" - afterwards %03x,%03x\n",
25669           pShmNode->sharedMask, pShmNode->exclMask));
25670  }
25671#endif
25672
25673  return rc;
25674}
25675
25676
25677/*
25678** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
25679**
25680** This is not a VFS shared-memory method; it is a utility function called
25681** by VFS shared-memory methods.
25682*/
25683static void unixShmPurge(unixFile *pFd){
25684  unixShmNode *p = pFd->pInode->pShmNode;
25685  assert( unixMutexHeld() );
25686  if( p && p->nRef==0 ){
25687    int i;
25688    assert( p->pInode==pFd->pInode );
25689    if( p->mutex ) sqlite3_mutex_free(p->mutex);
25690    for(i=0; i<p->nRegion; i++){
25691      munmap(p->apRegion[i], p->szRegion);
25692    }
25693    sqlite3_free(p->apRegion);
25694    if( p->h>=0 ) close(p->h);
25695    p->pInode->pShmNode = 0;
25696    sqlite3_free(p);
25697  }
25698}
25699
25700/*
25701** Open a shared-memory area associated with open database file fd.
25702** This particular implementation uses mmapped files.
25703**
25704** The file used to implement shared-memory is in the same directory
25705** as the open database file and has the same name as the open database
25706** file with the "-shm" suffix added.  For example, if the database file
25707** is "/home/user1/config.db" then the file that is created and mmapped
25708** for shared memory will be called "/home/user1/config.db-shm".  We
25709** experimented with using files in /dev/tmp or an some other tmpfs mount.
25710** But if a file in a different directory from the database file is used,
25711** then differing access permissions or a chroot() might cause two different
25712** processes on the same database to end up using different files for
25713** shared memory - meaning that their memory would not really be shared -
25714** resulting in database corruption.
25715**
25716** When opening a new shared-memory file, if no other instances of that
25717** file are currently open, in this process or in other processes, then
25718** the file must be truncated to zero length or have its header cleared.
25719*/
25720static int unixShmOpen(
25721  sqlite3_file *fd      /* The file descriptor of the associated database */
25722){
25723  struct unixShm *p = 0;             /* The connection to be opened */
25724  struct unixShmNode *pShmNode = 0;  /* The underlying mmapped file */
25725  int rc;                            /* Result code */
25726  struct unixFile *pDbFd;            /* Underlying database file */
25727  unixInodeInfo *pInode;             /* The inode of fd */
25728  char *zShmFilename;                /* Name of the file used for SHM */
25729  int nShmFilename;                  /* Size of the SHM filename in bytes */
25730
25731  /* Allocate space for the new sqlite3_shm object.
25732  */
25733  p = sqlite3_malloc( sizeof(*p) );
25734  if( p==0 ) return SQLITE_NOMEM;
25735  memset(p, 0, sizeof(*p));
25736  pDbFd = (struct unixFile*)fd;
25737  assert( pDbFd->pShm==0 );
25738
25739  /* Check to see if a unixShmNode object already exists.  Reuse an existing
25740  ** one if present.  Create a new one if necessary.
25741  */
25742  unixEnterMutex();
25743  pInode = pDbFd->pInode;
25744  pShmNode = pInode->pShmNode;
25745  if( pShmNode==0 ){
25746    nShmFilename = 5 + (int)strlen(pDbFd->zPath);
25747    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
25748    if( pShmNode==0 ){
25749      rc = SQLITE_NOMEM;
25750      goto shm_open_err;
25751    }
25752    memset(pShmNode, 0, sizeof(*pShmNode));
25753    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
25754    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
25755    pShmNode->h = -1;
25756    pDbFd->pInode->pShmNode = pShmNode;
25757    pShmNode->pInode = pDbFd->pInode;
25758    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
25759    if( pShmNode->mutex==0 ){
25760      rc = SQLITE_NOMEM;
25761      goto shm_open_err;
25762    }
25763
25764    pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, 0664);
25765    if( pShmNode->h<0 ){
25766      rc = SQLITE_CANTOPEN_BKPT;
25767      goto shm_open_err;
25768    }
25769
25770    /* Check to see if another process is holding the dead-man switch.
25771    ** If not, truncate the file to zero length.
25772    */
25773    rc = SQLITE_OK;
25774    if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
25775      if( ftruncate(pShmNode->h, 0) ){
25776        rc = SQLITE_IOERR_SHMOPEN;
25777      }
25778    }
25779    if( rc==SQLITE_OK ){
25780      rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
25781    }
25782    if( rc ) goto shm_open_err;
25783  }
25784
25785  /* Make the new connection a child of the unixShmNode */
25786  p->pShmNode = pShmNode;
25787  p->pNext = pShmNode->pFirst;
25788#ifdef SQLITE_DEBUG
25789  p->id = pShmNode->nextShmId++;
25790#endif
25791  pShmNode->pFirst = p;
25792  pShmNode->nRef++;
25793  pDbFd->pShm = p;
25794  unixLeaveMutex();
25795  return SQLITE_OK;
25796
25797  /* Jump here on any error */
25798shm_open_err:
25799  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
25800  sqlite3_free(p);
25801  unixLeaveMutex();
25802  return rc;
25803}
25804
25805/*
25806** Close a connection to shared-memory.  Delete the underlying
25807** storage if deleteFlag is true.
25808*/
25809static int unixShmClose(
25810  sqlite3_file *fd,          /* The underlying database file */
25811  int deleteFlag             /* Delete shared-memory if true */
25812){
25813  unixShm *p;            /* The connection to be closed */
25814  unixShmNode *pShmNode; /* The underlying shared-memory file */
25815  unixShm **pp;          /* For looping over sibling connections */
25816  unixFile *pDbFd;       /* The underlying database file */
25817
25818  pDbFd = (unixFile*)fd;
25819  p = pDbFd->pShm;
25820  if( p==0 ) return SQLITE_OK;
25821  pShmNode = p->pShmNode;
25822
25823  assert( pShmNode==pDbFd->pInode->pShmNode );
25824  assert( pShmNode->pInode==pDbFd->pInode );
25825
25826  /* Remove connection p from the set of connections associated
25827  ** with pShmNode */
25828  sqlite3_mutex_enter(pShmNode->mutex);
25829  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
25830  *pp = p->pNext;
25831
25832  /* Free the connection p */
25833  sqlite3_free(p);
25834  pDbFd->pShm = 0;
25835  sqlite3_mutex_leave(pShmNode->mutex);
25836
25837  /* If pShmNode->nRef has reached 0, then close the underlying
25838  ** shared-memory file, too */
25839  unixEnterMutex();
25840  assert( pShmNode->nRef>0 );
25841  pShmNode->nRef--;
25842  if( pShmNode->nRef==0 ){
25843    if( deleteFlag ) unlink(pShmNode->zFilename);
25844    unixShmPurge(pDbFd);
25845  }
25846  unixLeaveMutex();
25847
25848  return SQLITE_OK;
25849}
25850
25851/*
25852** Change the lock state for a shared-memory segment.
25853**
25854** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
25855** different here than in posix.  In xShmLock(), one can go from unlocked
25856** to shared and back or from unlocked to exclusive and back.  But one may
25857** not go from shared to exclusive or from exclusive to shared.
25858*/
25859static int unixShmLock(
25860  sqlite3_file *fd,          /* Database file holding the shared memory */
25861  int ofst,                  /* First lock to acquire or release */
25862  int n,                     /* Number of locks to acquire or release */
25863  int flags                  /* What to do with the lock */
25864){
25865  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
25866  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
25867  unixShm *pX;                          /* For looping over all siblings */
25868  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
25869  int rc = SQLITE_OK;                   /* Result code */
25870  u16 mask;                             /* Mask of locks to take or release */
25871
25872  assert( pShmNode==pDbFd->pInode->pShmNode );
25873  assert( pShmNode->pInode==pDbFd->pInode );
25874  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
25875  assert( n>=1 );
25876  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
25877       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
25878       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
25879       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
25880  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
25881
25882  mask = (1<<(ofst+n)) - (1<<ofst);
25883  assert( n>1 || mask==(1<<ofst) );
25884  sqlite3_mutex_enter(pShmNode->mutex);
25885  if( flags & SQLITE_SHM_UNLOCK ){
25886    u16 allMask = 0; /* Mask of locks held by siblings */
25887
25888    /* See if any siblings hold this same lock */
25889    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25890      if( pX==p ) continue;
25891      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
25892      allMask |= pX->sharedMask;
25893    }
25894
25895    /* Unlock the system-level locks */
25896    if( (mask & allMask)==0 ){
25897      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
25898    }else{
25899      rc = SQLITE_OK;
25900    }
25901
25902    /* Undo the local locks */
25903    if( rc==SQLITE_OK ){
25904      p->exclMask &= ~mask;
25905      p->sharedMask &= ~mask;
25906    }
25907  }else if( flags & SQLITE_SHM_SHARED ){
25908    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
25909
25910    /* Find out which shared locks are already held by sibling connections.
25911    ** If any sibling already holds an exclusive lock, go ahead and return
25912    ** SQLITE_BUSY.
25913    */
25914    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25915      if( (pX->exclMask & mask)!=0 ){
25916        rc = SQLITE_BUSY;
25917        break;
25918      }
25919      allShared |= pX->sharedMask;
25920    }
25921
25922    /* Get shared locks at the system level, if necessary */
25923    if( rc==SQLITE_OK ){
25924      if( (allShared & mask)==0 ){
25925        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
25926      }else{
25927        rc = SQLITE_OK;
25928      }
25929    }
25930
25931    /* Get the local shared locks */
25932    if( rc==SQLITE_OK ){
25933      p->sharedMask |= mask;
25934    }
25935  }else{
25936    /* Make sure no sibling connections hold locks that will block this
25937    ** lock.  If any do, return SQLITE_BUSY right away.
25938    */
25939    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25940      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
25941        rc = SQLITE_BUSY;
25942        break;
25943      }
25944    }
25945
25946    /* Get the exclusive locks at the system level.  Then if successful
25947    ** also mark the local connection as being locked.
25948    */
25949    if( rc==SQLITE_OK ){
25950      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
25951      if( rc==SQLITE_OK ){
25952        assert( (p->sharedMask & mask)==0 );
25953        p->exclMask |= mask;
25954      }
25955    }
25956  }
25957  sqlite3_mutex_leave(pShmNode->mutex);
25958  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
25959           p->id, getpid(), p->sharedMask, p->exclMask));
25960  return rc;
25961}
25962
25963/*
25964** Implement a memory barrier or memory fence on shared memory.
25965**
25966** All loads and stores begun before the barrier must complete before
25967** any load or store begun after the barrier.
25968*/
25969static void unixShmBarrier(
25970  sqlite3_file *fd                /* Database file holding the shared memory */
25971){
25972  UNUSED_PARAMETER(fd);
25973  unixEnterMutex();
25974  unixLeaveMutex();
25975}
25976
25977/*
25978** This function is called to obtain a pointer to region iRegion of the
25979** shared-memory associated with the database file fd. Shared-memory regions
25980** are numbered starting from zero. Each shared-memory region is szRegion
25981** bytes in size.
25982**
25983** If an error occurs, an error code is returned and *pp is set to NULL.
25984**
25985** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
25986** region has not been allocated (by any client, including one running in a
25987** separate process), then *pp is set to NULL and SQLITE_OK returned. If
25988** isWrite is non-zero and the requested shared-memory region has not yet
25989** been allocated, it is allocated by this function.
25990**
25991** If the shared-memory region has already been allocated or is allocated by
25992** this call as described above, then it is mapped into this processes
25993** address space (if it is not already), *pp is set to point to the mapped
25994** memory and SQLITE_OK returned.
25995*/
25996static int unixShmMap(
25997  sqlite3_file *fd,               /* Handle open on database file */
25998  int iRegion,                    /* Region to retrieve */
25999  int szRegion,                   /* Size of regions */
26000  int isWrite,                    /* True to extend file if necessary */
26001  void volatile **pp              /* OUT: Mapped memory */
26002){
26003  unixFile *pDbFd = (unixFile*)fd;
26004  unixShm *p = pDbFd->pShm;
26005  unixShmNode *pShmNode = p->pShmNode;
26006  int rc = SQLITE_OK;
26007
26008  sqlite3_mutex_enter(pShmNode->mutex);
26009  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26010
26011  if( pShmNode->nRegion<=iRegion ){
26012    char **apNew;                      /* New apRegion[] array */
26013    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26014    struct stat sStat;                 /* Used by fstat() */
26015
26016    pShmNode->szRegion = szRegion;
26017
26018    /* The requested region is not mapped into this processes address space.
26019    ** Check to see if it has been allocated (i.e. if the wal-index file is
26020    ** large enough to contain the requested region).
26021    */
26022    if( fstat(pShmNode->h, &sStat) ){
26023      rc = SQLITE_IOERR_SHMSIZE;
26024      goto shmpage_out;
26025    }
26026
26027    if( sStat.st_size<nByte ){
26028      /* The requested memory region does not exist. If isWrite is set to
26029      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
26030      **
26031      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
26032      ** the requested memory region.
26033      */
26034      if( !isWrite ) goto shmpage_out;
26035      if( ftruncate(pShmNode->h, nByte) ){
26036        rc = SQLITE_IOERR_SHMSIZE;
26037        goto shmpage_out;
26038      }
26039    }
26040
26041    /* Map the requested memory region into this processes address space. */
26042    apNew = (char **)sqlite3_realloc(
26043        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26044    );
26045    if( !apNew ){
26046      rc = SQLITE_IOERR_NOMEM;
26047      goto shmpage_out;
26048    }
26049    pShmNode->apRegion = apNew;
26050    while(pShmNode->nRegion<=iRegion){
26051      void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
26052          MAP_SHARED, pShmNode->h, iRegion*szRegion
26053      );
26054      if( pMem==MAP_FAILED ){
26055        rc = SQLITE_IOERR;
26056        goto shmpage_out;
26057      }
26058      pShmNode->apRegion[pShmNode->nRegion] = pMem;
26059      pShmNode->nRegion++;
26060    }
26061  }
26062
26063shmpage_out:
26064  if( pShmNode->nRegion>iRegion ){
26065    *pp = pShmNode->apRegion[iRegion];
26066  }else{
26067    *pp = 0;
26068  }
26069  sqlite3_mutex_leave(pShmNode->mutex);
26070  return rc;
26071}
26072
26073#else
26074# define unixShmOpen    0
26075# define unixShmLock    0
26076# define unixShmMap     0
26077# define unixShmBarrier 0
26078# define unixShmClose   0
26079#endif /* #ifndef SQLITE_OMIT_WAL */
26080
26081/*
26082** Here ends the implementation of all sqlite3_file methods.
26083**
26084********************** End sqlite3_file Methods *******************************
26085******************************************************************************/
26086
26087/*
26088** This division contains definitions of sqlite3_io_methods objects that
26089** implement various file locking strategies.  It also contains definitions
26090** of "finder" functions.  A finder-function is used to locate the appropriate
26091** sqlite3_io_methods object for a particular database file.  The pAppData
26092** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26093** the correct finder-function for that VFS.
26094**
26095** Most finder functions return a pointer to a fixed sqlite3_io_methods
26096** object.  The only interesting finder-function is autolockIoFinder, which
26097** looks at the filesystem type and tries to guess the best locking
26098** strategy from that.
26099**
26100** For finder-funtion F, two objects are created:
26101**
26102**    (1) The real finder-function named "FImpt()".
26103**
26104**    (2) A constant pointer to this function named just "F".
26105**
26106**
26107** A pointer to the F pointer is used as the pAppData value for VFS
26108** objects.  We have to do this instead of letting pAppData point
26109** directly at the finder-function since C90 rules prevent a void*
26110** from be cast into a function pointer.
26111**
26112**
26113** Each instance of this macro generates two objects:
26114**
26115**   *  A constant sqlite3_io_methods object call METHOD that has locking
26116**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26117**
26118**   *  An I/O method finder function called FINDER that returns a pointer
26119**      to the METHOD object in the previous bullet.
26120*/
26121#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26122static const sqlite3_io_methods METHOD = {                                   \
26123   VERSION,                    /* iVersion */                                \
26124   CLOSE,                      /* xClose */                                  \
26125   unixRead,                   /* xRead */                                   \
26126   unixWrite,                  /* xWrite */                                  \
26127   unixTruncate,               /* xTruncate */                               \
26128   unixSync,                   /* xSync */                                   \
26129   unixFileSize,               /* xFileSize */                               \
26130   LOCK,                       /* xLock */                                   \
26131   UNLOCK,                     /* xUnlock */                                 \
26132   CKLOCK,                     /* xCheckReservedLock */                      \
26133   unixFileControl,            /* xFileControl */                            \
26134   unixSectorSize,             /* xSectorSize */                             \
26135   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26136   unixShmOpen,                /* xShmOpen */                                \
26137   unixShmLock,                /* xShmLock */                                \
26138   unixShmMap,                 /* xShmMap */                                 \
26139   unixShmBarrier,             /* xShmBarrier */                             \
26140   unixShmClose                /* xShmClose */                               \
26141};                                                                           \
26142static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26143  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26144  return &METHOD;                                                            \
26145}                                                                            \
26146static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26147    = FINDER##Impl;
26148
26149/*
26150** Here are all of the sqlite3_io_methods objects for each of the
26151** locking strategies.  Functions that return pointers to these methods
26152** are also created.
26153*/
26154IOMETHODS(
26155  posixIoFinder,            /* Finder function name */
26156  posixIoMethods,           /* sqlite3_io_methods object name */
26157  2,                        /* ShmOpen is enabled */
26158  unixClose,                /* xClose method */
26159  unixLock,                 /* xLock method */
26160  unixUnlock,               /* xUnlock method */
26161  unixCheckReservedLock     /* xCheckReservedLock method */
26162)
26163IOMETHODS(
26164  nolockIoFinder,           /* Finder function name */
26165  nolockIoMethods,          /* sqlite3_io_methods object name */
26166  1,                        /* ShmOpen is disabled */
26167  nolockClose,              /* xClose method */
26168  nolockLock,               /* xLock method */
26169  nolockUnlock,             /* xUnlock method */
26170  nolockCheckReservedLock   /* xCheckReservedLock method */
26171)
26172IOMETHODS(
26173  dotlockIoFinder,          /* Finder function name */
26174  dotlockIoMethods,         /* sqlite3_io_methods object name */
26175  1,                        /* ShmOpen is disabled */
26176  dotlockClose,             /* xClose method */
26177  dotlockLock,              /* xLock method */
26178  dotlockUnlock,            /* xUnlock method */
26179  dotlockCheckReservedLock  /* xCheckReservedLock method */
26180)
26181
26182#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26183IOMETHODS(
26184  flockIoFinder,            /* Finder function name */
26185  flockIoMethods,           /* sqlite3_io_methods object name */
26186  1,                        /* ShmOpen is disabled */
26187  flockClose,               /* xClose method */
26188  flockLock,                /* xLock method */
26189  flockUnlock,              /* xUnlock method */
26190  flockCheckReservedLock    /* xCheckReservedLock method */
26191)
26192#endif
26193
26194#if OS_VXWORKS
26195IOMETHODS(
26196  semIoFinder,              /* Finder function name */
26197  semIoMethods,             /* sqlite3_io_methods object name */
26198  1,                        /* ShmOpen is disabled */
26199  semClose,                 /* xClose method */
26200  semLock,                  /* xLock method */
26201  semUnlock,                /* xUnlock method */
26202  semCheckReservedLock      /* xCheckReservedLock method */
26203)
26204#endif
26205
26206#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26207IOMETHODS(
26208  afpIoFinder,              /* Finder function name */
26209  afpIoMethods,             /* sqlite3_io_methods object name */
26210  1,                        /* ShmOpen is disabled */
26211  afpClose,                 /* xClose method */
26212  afpLock,                  /* xLock method */
26213  afpUnlock,                /* xUnlock method */
26214  afpCheckReservedLock      /* xCheckReservedLock method */
26215)
26216#endif
26217
26218/*
26219** The proxy locking method is a "super-method" in the sense that it
26220** opens secondary file descriptors for the conch and lock files and
26221** it uses proxy, dot-file, AFP, and flock() locking methods on those
26222** secondary files.  For this reason, the division that implements
26223** proxy locking is located much further down in the file.  But we need
26224** to go ahead and define the sqlite3_io_methods and finder function
26225** for proxy locking here.  So we forward declare the I/O methods.
26226*/
26227#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26228static int proxyClose(sqlite3_file*);
26229static int proxyLock(sqlite3_file*, int);
26230static int proxyUnlock(sqlite3_file*, int);
26231static int proxyCheckReservedLock(sqlite3_file*, int*);
26232IOMETHODS(
26233  proxyIoFinder,            /* Finder function name */
26234  proxyIoMethods,           /* sqlite3_io_methods object name */
26235  1,                        /* ShmOpen is disabled */
26236  proxyClose,               /* xClose method */
26237  proxyLock,                /* xLock method */
26238  proxyUnlock,              /* xUnlock method */
26239  proxyCheckReservedLock    /* xCheckReservedLock method */
26240)
26241#endif
26242
26243/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26244#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26245IOMETHODS(
26246  nfsIoFinder,               /* Finder function name */
26247  nfsIoMethods,              /* sqlite3_io_methods object name */
26248  1,                         /* ShmOpen is disabled */
26249  unixClose,                 /* xClose method */
26250  unixLock,                  /* xLock method */
26251  nfsUnlock,                 /* xUnlock method */
26252  unixCheckReservedLock      /* xCheckReservedLock method */
26253)
26254#endif
26255
26256#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26257/*
26258** This "finder" function attempts to determine the best locking strategy
26259** for the database file "filePath".  It then returns the sqlite3_io_methods
26260** object that implements that strategy.
26261**
26262** This is for MacOSX only.
26263*/
26264static const sqlite3_io_methods *autolockIoFinderImpl(
26265  const char *filePath,    /* name of the database file */
26266  unixFile *pNew           /* open file object for the database file */
26267){
26268  static const struct Mapping {
26269    const char *zFilesystem;              /* Filesystem type name */
26270    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26271  } aMap[] = {
26272    { "hfs",    &posixIoMethods },
26273    { "ufs",    &posixIoMethods },
26274    { "afpfs",  &afpIoMethods },
26275    { "smbfs",  &afpIoMethods },
26276    { "webdav", &nolockIoMethods },
26277    { 0, 0 }
26278  };
26279  int i;
26280  struct statfs fsInfo;
26281  struct flock lockInfo;
26282
26283  if( !filePath ){
26284    /* If filePath==NULL that means we are dealing with a transient file
26285    ** that does not need to be locked. */
26286    return &nolockIoMethods;
26287  }
26288  if( statfs(filePath, &fsInfo) != -1 ){
26289    if( fsInfo.f_flags & MNT_RDONLY ){
26290      return &nolockIoMethods;
26291    }
26292    for(i=0; aMap[i].zFilesystem; i++){
26293      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26294        return aMap[i].pMethods;
26295      }
26296    }
26297  }
26298
26299  /* Default case. Handles, amongst others, "nfs".
26300  ** Test byte-range lock using fcntl(). If the call succeeds,
26301  ** assume that the file-system supports POSIX style locks.
26302  */
26303  lockInfo.l_len = 1;
26304  lockInfo.l_start = 0;
26305  lockInfo.l_whence = SEEK_SET;
26306  lockInfo.l_type = F_RDLCK;
26307  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26308    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26309      return &nfsIoMethods;
26310    } else {
26311      return &posixIoMethods;
26312    }
26313  }else{
26314    return &dotlockIoMethods;
26315  }
26316}
26317static const sqlite3_io_methods
26318  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26319
26320#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26321
26322#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26323/*
26324** This "finder" function attempts to determine the best locking strategy
26325** for the database file "filePath".  It then returns the sqlite3_io_methods
26326** object that implements that strategy.
26327**
26328** This is for VXWorks only.
26329*/
26330static const sqlite3_io_methods *autolockIoFinderImpl(
26331  const char *filePath,    /* name of the database file */
26332  unixFile *pNew           /* the open file object */
26333){
26334  struct flock lockInfo;
26335
26336  if( !filePath ){
26337    /* If filePath==NULL that means we are dealing with a transient file
26338    ** that does not need to be locked. */
26339    return &nolockIoMethods;
26340  }
26341
26342  /* Test if fcntl() is supported and use POSIX style locks.
26343  ** Otherwise fall back to the named semaphore method.
26344  */
26345  lockInfo.l_len = 1;
26346  lockInfo.l_start = 0;
26347  lockInfo.l_whence = SEEK_SET;
26348  lockInfo.l_type = F_RDLCK;
26349  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26350    return &posixIoMethods;
26351  }else{
26352    return &semIoMethods;
26353  }
26354}
26355static const sqlite3_io_methods
26356  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26357
26358#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
26359
26360/*
26361** An abstract type for a pointer to a IO method finder function:
26362*/
26363typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
26364
26365
26366/****************************************************************************
26367**************************** sqlite3_vfs methods ****************************
26368**
26369** This division contains the implementation of methods on the
26370** sqlite3_vfs object.
26371*/
26372
26373/*
26374** Initialize the contents of the unixFile structure pointed to by pId.
26375*/
26376static int fillInUnixFile(
26377  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
26378  int h,                  /* Open file descriptor of file being opened */
26379  int dirfd,              /* Directory file descriptor */
26380  sqlite3_file *pId,      /* Write to the unixFile structure here */
26381  const char *zFilename,  /* Name of the file being opened */
26382  int noLock,             /* Omit locking if true */
26383  int isDelete            /* Delete on close if true */
26384){
26385  const sqlite3_io_methods *pLockingStyle;
26386  unixFile *pNew = (unixFile *)pId;
26387  int rc = SQLITE_OK;
26388
26389  assert( pNew->pInode==NULL );
26390
26391  /* Parameter isDelete is only used on vxworks. Express this explicitly
26392  ** here to prevent compiler warnings about unused parameters.
26393  */
26394  UNUSED_PARAMETER(isDelete);
26395
26396  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
26397  pNew->h = h;
26398  pNew->dirfd = dirfd;
26399  pNew->fileFlags = 0;
26400  assert( zFilename==0 || zFilename[0]=='/' );  /* Never a relative pathname */
26401  pNew->zPath = zFilename;
26402
26403#if OS_VXWORKS
26404  pNew->pId = vxworksFindFileId(zFilename);
26405  if( pNew->pId==0 ){
26406    noLock = 1;
26407    rc = SQLITE_NOMEM;
26408  }
26409#endif
26410
26411  if( noLock ){
26412    pLockingStyle = &nolockIoMethods;
26413  }else{
26414    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
26415#if SQLITE_ENABLE_LOCKING_STYLE
26416    /* Cache zFilename in the locking context (AFP and dotlock override) for
26417    ** proxyLock activation is possible (remote proxy is based on db name)
26418    ** zFilename remains valid until file is closed, to support */
26419    pNew->lockingContext = (void*)zFilename;
26420#endif
26421  }
26422
26423  if( pLockingStyle == &posixIoMethods
26424#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26425    || pLockingStyle == &nfsIoMethods
26426#endif
26427  ){
26428    unixEnterMutex();
26429    rc = findInodeInfo(pNew, &pNew->pInode);
26430    if( rc!=SQLITE_OK ){
26431      /* If an error occured in findInodeInfo(), close the file descriptor
26432      ** immediately, before releasing the mutex. findInodeInfo() may fail
26433      ** in two scenarios:
26434      **
26435      **   (a) A call to fstat() failed.
26436      **   (b) A malloc failed.
26437      **
26438      ** Scenario (b) may only occur if the process is holding no other
26439      ** file descriptors open on the same file. If there were other file
26440      ** descriptors on this file, then no malloc would be required by
26441      ** findInodeInfo(). If this is the case, it is quite safe to close
26442      ** handle h - as it is guaranteed that no posix locks will be released
26443      ** by doing so.
26444      **
26445      ** If scenario (a) caused the error then things are not so safe. The
26446      ** implicit assumption here is that if fstat() fails, things are in
26447      ** such bad shape that dropping a lock or two doesn't matter much.
26448      */
26449      close(h);
26450      h = -1;
26451    }
26452    unixLeaveMutex();
26453  }
26454
26455#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26456  else if( pLockingStyle == &afpIoMethods ){
26457    /* AFP locking uses the file path so it needs to be included in
26458    ** the afpLockingContext.
26459    */
26460    afpLockingContext *pCtx;
26461    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
26462    if( pCtx==0 ){
26463      rc = SQLITE_NOMEM;
26464    }else{
26465      /* NB: zFilename exists and remains valid until the file is closed
26466      ** according to requirement F11141.  So we do not need to make a
26467      ** copy of the filename. */
26468      pCtx->dbPath = zFilename;
26469      pCtx->reserved = 0;
26470      srandomdev();
26471      unixEnterMutex();
26472      rc = findInodeInfo(pNew, &pNew->pInode);
26473      if( rc!=SQLITE_OK ){
26474        sqlite3_free(pNew->lockingContext);
26475        close(h);
26476        h = -1;
26477      }
26478      unixLeaveMutex();
26479    }
26480  }
26481#endif
26482
26483  else if( pLockingStyle == &dotlockIoMethods ){
26484    /* Dotfile locking uses the file path so it needs to be included in
26485    ** the dotlockLockingContext
26486    */
26487    char *zLockFile;
26488    int nFilename;
26489    nFilename = (int)strlen(zFilename) + 6;
26490    zLockFile = (char *)sqlite3_malloc(nFilename);
26491    if( zLockFile==0 ){
26492      rc = SQLITE_NOMEM;
26493    }else{
26494      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
26495    }
26496    pNew->lockingContext = zLockFile;
26497  }
26498
26499#if OS_VXWORKS
26500  else if( pLockingStyle == &semIoMethods ){
26501    /* Named semaphore locking uses the file path so it needs to be
26502    ** included in the semLockingContext
26503    */
26504    unixEnterMutex();
26505    rc = findInodeInfo(pNew, &pNew->pInode);
26506    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
26507      char *zSemName = pNew->pInode->aSemName;
26508      int n;
26509      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
26510                       pNew->pId->zCanonicalName);
26511      for( n=1; zSemName[n]; n++ )
26512        if( zSemName[n]=='/' ) zSemName[n] = '_';
26513      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
26514      if( pNew->pInode->pSem == SEM_FAILED ){
26515        rc = SQLITE_NOMEM;
26516        pNew->pInode->aSemName[0] = '\0';
26517      }
26518    }
26519    unixLeaveMutex();
26520  }
26521#endif
26522
26523  pNew->lastErrno = 0;
26524#if OS_VXWORKS
26525  if( rc!=SQLITE_OK ){
26526    if( h>=0 ) close(h);
26527    h = -1;
26528    unlink(zFilename);
26529    isDelete = 0;
26530  }
26531  pNew->isDelete = isDelete;
26532#endif
26533  if( rc!=SQLITE_OK ){
26534    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
26535    if( h>=0 ) close(h);
26536  }else{
26537    pNew->pMethod = pLockingStyle;
26538    OpenCounter(+1);
26539  }
26540  return rc;
26541}
26542
26543/*
26544** Open a file descriptor to the directory containing file zFilename.
26545** If successful, *pFd is set to the opened file descriptor and
26546** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26547** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26548** value.
26549**
26550** If SQLITE_OK is returned, the caller is responsible for closing
26551** the file descriptor *pFd using close().
26552*/
26553static int openDirectory(const char *zFilename, int *pFd){
26554  int ii;
26555  int fd = -1;
26556  char zDirname[MAX_PATHNAME+1];
26557
26558  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26559  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26560  if( ii>0 ){
26561    zDirname[ii] = '\0';
26562    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
26563    if( fd>=0 ){
26564#ifdef FD_CLOEXEC
26565      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26566#endif
26567      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26568    }
26569  }
26570  *pFd = fd;
26571  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
26572}
26573
26574/*
26575** Return the name of a directory in which to put temporary files.
26576** If no suitable temporary file directory can be found, return NULL.
26577*/
26578static const char *unixTempFileDir(void){
26579  static const char *azDirs[] = {
26580     0,
26581     0,
26582     "/var/tmp",
26583     "/usr/tmp",
26584     "/tmp",
26585     0        /* List terminator */
26586  };
26587  unsigned int i;
26588  struct stat buf;
26589  const char *zDir = 0;
26590
26591  azDirs[0] = sqlite3_temp_directory;
26592  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
26593  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
26594    if( zDir==0 ) continue;
26595    if( stat(zDir, &buf) ) continue;
26596    if( !S_ISDIR(buf.st_mode) ) continue;
26597    if( access(zDir, 07) ) continue;
26598    break;
26599  }
26600  return zDir;
26601}
26602
26603/*
26604** Create a temporary file name in zBuf.  zBuf must be allocated
26605** by the calling process and must be big enough to hold at least
26606** pVfs->mxPathname bytes.
26607*/
26608static int unixGetTempname(int nBuf, char *zBuf){
26609  static const unsigned char zChars[] =
26610    "abcdefghijklmnopqrstuvwxyz"
26611    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26612    "0123456789";
26613  unsigned int i, j;
26614  const char *zDir;
26615
26616  /* It's odd to simulate an io-error here, but really this is just
26617  ** using the io-error infrastructure to test that SQLite handles this
26618  ** function failing.
26619  */
26620  SimulateIOError( return SQLITE_IOERR );
26621
26622  zDir = unixTempFileDir();
26623  if( zDir==0 ) zDir = ".";
26624
26625  /* Check that the output buffer is large enough for the temporary file
26626  ** name. If it is not, return SQLITE_ERROR.
26627  */
26628  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
26629    return SQLITE_ERROR;
26630  }
26631
26632  do{
26633    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
26634    j = (int)strlen(zBuf);
26635    sqlite3_randomness(15, &zBuf[j]);
26636    for(i=0; i<15; i++, j++){
26637      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26638    }
26639    zBuf[j] = 0;
26640  }while( access(zBuf,0)==0 );
26641  return SQLITE_OK;
26642}
26643
26644#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26645/*
26646** Routine to transform a unixFile into a proxy-locking unixFile.
26647** Implementation in the proxy-lock division, but used by unixOpen()
26648** if SQLITE_PREFER_PROXY_LOCKING is defined.
26649*/
26650static int proxyTransformUnixFile(unixFile*, const char*);
26651#endif
26652
26653/*
26654** Search for an unused file descriptor that was opened on the database
26655** file (not a journal or master-journal file) identified by pathname
26656** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
26657** argument to this function.
26658**
26659** Such a file descriptor may exist if a database connection was closed
26660** but the associated file descriptor could not be closed because some
26661** other file descriptor open on the same file is holding a file-lock.
26662** Refer to comments in the unixClose() function and the lengthy comment
26663** describing "Posix Advisory Locking" at the start of this file for
26664** further details. Also, ticket #4018.
26665**
26666** If a suitable file descriptor is found, then it is returned. If no
26667** such file descriptor is located, -1 is returned.
26668*/
26669static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
26670  UnixUnusedFd *pUnused = 0;
26671
26672  /* Do not search for an unused file descriptor on vxworks. Not because
26673  ** vxworks would not benefit from the change (it might, we're not sure),
26674  ** but because no way to test it is currently available. It is better
26675  ** not to risk breaking vxworks support for the sake of such an obscure
26676  ** feature.  */
26677#if !OS_VXWORKS
26678  struct stat sStat;                   /* Results of stat() call */
26679
26680  /* A stat() call may fail for various reasons. If this happens, it is
26681  ** almost certain that an open() call on the same path will also fail.
26682  ** For this reason, if an error occurs in the stat() call here, it is
26683  ** ignored and -1 is returned. The caller will try to open a new file
26684  ** descriptor on the same path, fail, and return an error to SQLite.
26685  **
26686  ** Even if a subsequent open() call does succeed, the consequences of
26687  ** not searching for a resusable file descriptor are not dire.  */
26688  if( 0==stat(zPath, &sStat) ){
26689    unixInodeInfo *pInode;
26690
26691    unixEnterMutex();
26692    pInode = inodeList;
26693    while( pInode && (pInode->fileId.dev!=sStat.st_dev
26694                     || pInode->fileId.ino!=sStat.st_ino) ){
26695       pInode = pInode->pNext;
26696    }
26697    if( pInode ){
26698      UnixUnusedFd **pp;
26699      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
26700      pUnused = *pp;
26701      if( pUnused ){
26702        *pp = pUnused->pNext;
26703      }
26704    }
26705    unixLeaveMutex();
26706  }
26707#endif    /* if !OS_VXWORKS */
26708  return pUnused;
26709}
26710
26711/*
26712** Open the file zPath.
26713**
26714** Previously, the SQLite OS layer used three functions in place of this
26715** one:
26716**
26717**     sqlite3OsOpenReadWrite();
26718**     sqlite3OsOpenReadOnly();
26719**     sqlite3OsOpenExclusive();
26720**
26721** These calls correspond to the following combinations of flags:
26722**
26723**     ReadWrite() ->     (READWRITE | CREATE)
26724**     ReadOnly()  ->     (READONLY)
26725**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
26726**
26727** The old OpenExclusive() accepted a boolean argument - "delFlag". If
26728** true, the file was configured to be automatically deleted when the
26729** file handle closed. To achieve the same effect using this new
26730** interface, add the DELETEONCLOSE flag to those specified above for
26731** OpenExclusive().
26732*/
26733static int unixOpen(
26734  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
26735  const char *zPath,           /* Pathname of file to be opened */
26736  sqlite3_file *pFile,         /* The file descriptor to be filled in */
26737  int flags,                   /* Input flags to control the opening */
26738  int *pOutFlags               /* Output flags returned to SQLite core */
26739){
26740  unixFile *p = (unixFile *)pFile;
26741  int fd = -1;                   /* File descriptor returned by open() */
26742  int dirfd = -1;                /* Directory file descriptor */
26743  int openFlags = 0;             /* Flags to pass to open() */
26744  int eType = flags&0xFFFFFF00;  /* Type of file to open */
26745  int noLock;                    /* True to omit locking primitives */
26746  int rc = SQLITE_OK;            /* Function Return Code */
26747
26748  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
26749  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
26750  int isCreate     = (flags & SQLITE_OPEN_CREATE);
26751  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
26752  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
26753#if SQLITE_ENABLE_LOCKING_STYLE
26754  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
26755#endif
26756
26757  /* If creating a master or main-file journal, this function will open
26758  ** a file-descriptor on the directory too. The first time unixSync()
26759  ** is called the directory file descriptor will be fsync()ed and close()d.
26760  */
26761  int isOpenDirectory = (isCreate &&
26762      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
26763  );
26764
26765  /* If argument zPath is a NULL pointer, this function is required to open
26766  ** a temporary file. Use this buffer to store the file name in.
26767  */
26768  char zTmpname[MAX_PATHNAME+1];
26769  const char *zName = zPath;
26770
26771  /* Check the following statements are true:
26772  **
26773  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
26774  **   (b) if CREATE is set, then READWRITE must also be set, and
26775  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
26776  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
26777  */
26778  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
26779  assert(isCreate==0 || isReadWrite);
26780  assert(isExclusive==0 || isCreate);
26781  assert(isDelete==0 || isCreate);
26782
26783  /* The main DB, main journal, and master journal are never automatically
26784  ** deleted. Nor are they ever temporary files.  */
26785  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
26786  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
26787  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
26788
26789  /* Assert that the upper layer has set one of the "file-type" flags. */
26790  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
26791       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
26792       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
26793       || eType==SQLITE_OPEN_TRANSIENT_DB
26794  );
26795
26796  memset(p, 0, sizeof(unixFile));
26797
26798  if( eType==SQLITE_OPEN_MAIN_DB ){
26799    UnixUnusedFd *pUnused;
26800    pUnused = findReusableFd(zName, flags);
26801    if( pUnused ){
26802      fd = pUnused->fd;
26803    }else{
26804      pUnused = sqlite3_malloc(sizeof(*pUnused));
26805      if( !pUnused ){
26806        return SQLITE_NOMEM;
26807      }
26808    }
26809    p->pUnused = pUnused;
26810  }else if( !zName ){
26811    /* If zName is NULL, the upper layer is requesting a temp file. */
26812    assert(isDelete && !isOpenDirectory);
26813    rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
26814    if( rc!=SQLITE_OK ){
26815      return rc;
26816    }
26817    zName = zTmpname;
26818  }
26819
26820  /* Determine the value of the flags parameter passed to POSIX function
26821  ** open(). These must be calculated even if open() is not called, as
26822  ** they may be stored as part of the file handle and used by the
26823  ** 'conch file' locking functions later on.  */
26824  if( isReadonly )  openFlags |= O_RDONLY;
26825  if( isReadWrite ) openFlags |= O_RDWR;
26826  if( isCreate )    openFlags |= O_CREAT;
26827  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
26828  openFlags |= (O_LARGEFILE|O_BINARY);
26829
26830  if( fd<0 ){
26831    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
26832    fd = open(zName, openFlags, openMode);
26833    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
26834    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
26835      /* Failed to open the file for read/write access. Try read-only. */
26836      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
26837      openFlags &= ~(O_RDWR|O_CREAT);
26838      flags |= SQLITE_OPEN_READONLY;
26839      openFlags |= O_RDONLY;
26840      fd = open(zName, openFlags, openMode);
26841    }
26842    if( fd<0 ){
26843      rc = SQLITE_CANTOPEN_BKPT;
26844      goto open_finished;
26845    }
26846  }
26847  assert( fd>=0 );
26848  if( pOutFlags ){
26849    *pOutFlags = flags;
26850  }
26851
26852  if( p->pUnused ){
26853    p->pUnused->fd = fd;
26854    p->pUnused->flags = flags;
26855  }
26856
26857  if( isDelete ){
26858#if OS_VXWORKS
26859    zPath = zName;
26860#else
26861    unlink(zName);
26862#endif
26863  }
26864#if SQLITE_ENABLE_LOCKING_STYLE
26865  else{
26866    p->openFlags = openFlags;
26867  }
26868#endif
26869
26870  if( isOpenDirectory ){
26871    rc = openDirectory(zPath, &dirfd);
26872    if( rc!=SQLITE_OK ){
26873      /* It is safe to close fd at this point, because it is guaranteed not
26874      ** to be open on a database file. If it were open on a database file,
26875      ** it would not be safe to close as this would release any locks held
26876      ** on the file by this process.  */
26877      assert( eType!=SQLITE_OPEN_MAIN_DB );
26878      close(fd);             /* silently leak if fail, already in error */
26879      goto open_finished;
26880    }
26881  }
26882
26883#ifdef FD_CLOEXEC
26884  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26885#endif
26886
26887  noLock = eType!=SQLITE_OPEN_MAIN_DB;
26888
26889
26890#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
26891  struct statfs fsInfo;
26892  if( fstatfs(fd, &fsInfo) == -1 ){
26893    ((unixFile*)pFile)->lastErrno = errno;
26894    if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
26895    close(fd); /* silently leak if fail, in error */
26896    return SQLITE_IOERR_ACCESS;
26897  }
26898  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
26899    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
26900  }
26901#endif
26902
26903#if SQLITE_ENABLE_LOCKING_STYLE
26904#if SQLITE_PREFER_PROXY_LOCKING
26905  isAutoProxy = 1;
26906#endif
26907  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
26908    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
26909    int useProxy = 0;
26910
26911    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
26912    ** never use proxy, NULL means use proxy for non-local files only.  */
26913    if( envforce!=NULL ){
26914      useProxy = atoi(envforce)>0;
26915    }else{
26916      struct statfs fsInfo;
26917      if( statfs(zPath, &fsInfo) == -1 ){
26918        /* In theory, the close(fd) call is sub-optimal. If the file opened
26919        ** with fd is a database file, and there are other connections open
26920        ** on that file that are currently holding advisory locks on it,
26921        ** then the call to close() will cancel those locks. In practice,
26922        ** we're assuming that statfs() doesn't fail very often. At least
26923        ** not while other file descriptors opened by the same process on
26924        ** the same file are working.  */
26925        p->lastErrno = errno;
26926        if( dirfd>=0 ){
26927          close(dirfd); /* silently leak if fail, in error */
26928        }
26929        close(fd); /* silently leak if fail, in error */
26930        rc = SQLITE_IOERR_ACCESS;
26931        goto open_finished;
26932      }
26933      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
26934    }
26935    if( useProxy ){
26936      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
26937      if( rc==SQLITE_OK ){
26938        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
26939        if( rc!=SQLITE_OK ){
26940          /* Use unixClose to clean up the resources added in fillInUnixFile
26941          ** and clear all the structure's references.  Specifically,
26942          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
26943          */
26944          unixClose(pFile);
26945          return rc;
26946        }
26947      }
26948      goto open_finished;
26949    }
26950  }
26951#endif
26952
26953  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
26954open_finished:
26955  if( rc!=SQLITE_OK ){
26956    sqlite3_free(p->pUnused);
26957  }
26958  return rc;
26959}
26960
26961
26962/*
26963** Delete the file at zPath. If the dirSync argument is true, fsync()
26964** the directory after deleting the file.
26965*/
26966static int unixDelete(
26967  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
26968  const char *zPath,        /* Name of file to be deleted */
26969  int dirSync               /* If true, fsync() directory after deleting file */
26970){
26971  int rc = SQLITE_OK;
26972  UNUSED_PARAMETER(NotUsed);
26973  SimulateIOError(return SQLITE_IOERR_DELETE);
26974  unlink(zPath);
26975#ifndef SQLITE_DISABLE_DIRSYNC
26976  if( dirSync ){
26977    int fd;
26978    rc = openDirectory(zPath, &fd);
26979    if( rc==SQLITE_OK ){
26980#if OS_VXWORKS
26981      if( fsync(fd)==-1 )
26982#else
26983      if( fsync(fd) )
26984#endif
26985      {
26986        rc = SQLITE_IOERR_DIR_FSYNC;
26987      }
26988      if( close(fd)&&!rc ){
26989        rc = SQLITE_IOERR_DIR_CLOSE;
26990      }
26991    }
26992  }
26993#endif
26994  return rc;
26995}
26996
26997/*
26998** Test the existance of or access permissions of file zPath. The
26999** test performed depends on the value of flags:
27000**
27001**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27002**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27003**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27004**
27005** Otherwise return 0.
27006*/
27007static int unixAccess(
27008  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27009  const char *zPath,      /* Path of the file to examine */
27010  int flags,              /* What do we want to learn about the zPath file? */
27011  int *pResOut            /* Write result boolean here */
27012){
27013  int amode = 0;
27014  UNUSED_PARAMETER(NotUsed);
27015  SimulateIOError( return SQLITE_IOERR_ACCESS; );
27016  switch( flags ){
27017    case SQLITE_ACCESS_EXISTS:
27018      amode = F_OK;
27019      break;
27020    case SQLITE_ACCESS_READWRITE:
27021      amode = W_OK|R_OK;
27022      break;
27023    case SQLITE_ACCESS_READ:
27024      amode = R_OK;
27025      break;
27026
27027    default:
27028      assert(!"Invalid flags argument");
27029  }
27030  *pResOut = (access(zPath, amode)==0);
27031  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27032    struct stat buf;
27033    if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27034      *pResOut = 0;
27035    }
27036  }
27037  return SQLITE_OK;
27038}
27039
27040
27041/*
27042** Turn a relative pathname into a full pathname. The relative path
27043** is stored as a nul-terminated string in the buffer pointed to by
27044** zPath.
27045**
27046** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
27047** (in this case, MAX_PATHNAME bytes). The full-path is written to
27048** this buffer before returning.
27049*/
27050static int unixFullPathname(
27051  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27052  const char *zPath,            /* Possibly relative input path */
27053  int nOut,                     /* Size of output buffer in bytes */
27054  char *zOut                    /* Output buffer */
27055){
27056
27057  /* It's odd to simulate an io-error here, but really this is just
27058  ** using the io-error infrastructure to test that SQLite handles this
27059  ** function failing. This function could fail if, for example, the
27060  ** current working directory has been unlinked.
27061  */
27062  SimulateIOError( return SQLITE_ERROR );
27063
27064  assert( pVfs->mxPathname==MAX_PATHNAME );
27065  UNUSED_PARAMETER(pVfs);
27066
27067  zOut[nOut-1] = '\0';
27068  if( zPath[0]=='/' ){
27069    sqlite3_snprintf(nOut, zOut, "%s", zPath);
27070  }else{
27071    int nCwd;
27072    if( getcwd(zOut, nOut-1)==0 ){
27073      return SQLITE_CANTOPEN_BKPT;
27074    }
27075    nCwd = (int)strlen(zOut);
27076    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27077  }
27078  return SQLITE_OK;
27079}
27080
27081
27082#ifndef SQLITE_OMIT_LOAD_EXTENSION
27083/*
27084** Interfaces for opening a shared library, finding entry points
27085** within the shared library, and closing the shared library.
27086*/
27087#include <dlfcn.h>
27088static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27089  UNUSED_PARAMETER(NotUsed);
27090  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27091}
27092
27093/*
27094** SQLite calls this function immediately after a call to unixDlSym() or
27095** unixDlOpen() fails (returns a null pointer). If a more detailed error
27096** message is available, it is written to zBufOut. If no error message
27097** is available, zBufOut is left unmodified and SQLite uses a default
27098** error message.
27099*/
27100static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27101  char *zErr;
27102  UNUSED_PARAMETER(NotUsed);
27103  unixEnterMutex();
27104  zErr = dlerror();
27105  if( zErr ){
27106    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27107  }
27108  unixLeaveMutex();
27109}
27110static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27111  /*
27112  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27113  ** cast into a pointer to a function.  And yet the library dlsym() routine
27114  ** returns a void* which is really a pointer to a function.  So how do we
27115  ** use dlsym() with -pedantic-errors?
27116  **
27117  ** Variable x below is defined to be a pointer to a function taking
27118  ** parameters void* and const char* and returning a pointer to a function.
27119  ** We initialize x by assigning it a pointer to the dlsym() function.
27120  ** (That assignment requires a cast.)  Then we call the function that
27121  ** x points to.
27122  **
27123  ** This work-around is unlikely to work correctly on any system where
27124  ** you really cannot cast a function pointer into void*.  But then, on the
27125  ** other hand, dlsym() will not work on such a system either, so we have
27126  ** not really lost anything.
27127  */
27128  void (*(*x)(void*,const char*))(void);
27129  UNUSED_PARAMETER(NotUsed);
27130  x = (void(*(*)(void*,const char*))(void))dlsym;
27131  return (*x)(p, zSym);
27132}
27133static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27134  UNUSED_PARAMETER(NotUsed);
27135  dlclose(pHandle);
27136}
27137#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27138  #define unixDlOpen  0
27139  #define unixDlError 0
27140  #define unixDlSym   0
27141  #define unixDlClose 0
27142#endif
27143
27144/*
27145** Write nBuf bytes of random data to the supplied buffer zBuf.
27146*/
27147static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27148  UNUSED_PARAMETER(NotUsed);
27149  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27150
27151  /* We have to initialize zBuf to prevent valgrind from reporting
27152  ** errors.  The reports issued by valgrind are incorrect - we would
27153  ** prefer that the randomness be increased by making use of the
27154  ** uninitialized space in zBuf - but valgrind errors tend to worry
27155  ** some users.  Rather than argue, it seems easier just to initialize
27156  ** the whole array and silence valgrind, even if that means less randomness
27157  ** in the random seed.
27158  **
27159  ** When testing, initializing zBuf[] to zero is all we do.  That means
27160  ** that we always use the same random number sequence.  This makes the
27161  ** tests repeatable.
27162  */
27163  memset(zBuf, 0, nBuf);
27164#if !defined(SQLITE_TEST)
27165  {
27166    int pid, fd;
27167    fd = open("/dev/urandom", O_RDONLY);
27168    if( fd<0 ){
27169      time_t t;
27170      time(&t);
27171      memcpy(zBuf, &t, sizeof(t));
27172      pid = getpid();
27173      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27174      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27175      nBuf = sizeof(t) + sizeof(pid);
27176    }else{
27177      nBuf = read(fd, zBuf, nBuf);
27178      close(fd);
27179    }
27180  }
27181#endif
27182  return nBuf;
27183}
27184
27185
27186/*
27187** Sleep for a little while.  Return the amount of time slept.
27188** The argument is the number of microseconds we want to sleep.
27189** The return value is the number of microseconds of sleep actually
27190** requested from the underlying operating system, a number which
27191** might be greater than or equal to the argument, but not less
27192** than the argument.
27193*/
27194static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27195#if OS_VXWORKS
27196  struct timespec sp;
27197
27198  sp.tv_sec = microseconds / 1000000;
27199  sp.tv_nsec = (microseconds % 1000000) * 1000;
27200  nanosleep(&sp, NULL);
27201  UNUSED_PARAMETER(NotUsed);
27202  return microseconds;
27203#elif defined(HAVE_USLEEP) && HAVE_USLEEP
27204  usleep(microseconds);
27205  UNUSED_PARAMETER(NotUsed);
27206  return microseconds;
27207#else
27208  int seconds = (microseconds+999999)/1000000;
27209  sleep(seconds);
27210  UNUSED_PARAMETER(NotUsed);
27211  return seconds*1000000;
27212#endif
27213}
27214
27215/*
27216** The following variable, if set to a non-zero value, is interpreted as
27217** the number of seconds since 1970 and is used to set the result of
27218** sqlite3OsCurrentTime() during testing.
27219*/
27220#ifdef SQLITE_TEST
27221SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27222#endif
27223
27224/*
27225** Find the current time (in Universal Coordinated Time).  Write into *piNow
27226** the current time and date as a Julian Day number times 86_400_000.  In
27227** other words, write into *piNow the number of milliseconds since the Julian
27228** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27229** proleptic Gregorian calendar.
27230**
27231** On success, return 0.  Return 1 if the time and date cannot be found.
27232*/
27233static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27234  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27235#if defined(NO_GETTOD)
27236  time_t t;
27237  time(&t);
27238  *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27239#elif OS_VXWORKS
27240  struct timespec sNow;
27241  clock_gettime(CLOCK_REALTIME, &sNow);
27242  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27243#else
27244  struct timeval sNow;
27245  gettimeofday(&sNow, 0);
27246  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27247#endif
27248
27249#ifdef SQLITE_TEST
27250  if( sqlite3_current_time ){
27251    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27252  }
27253#endif
27254  UNUSED_PARAMETER(NotUsed);
27255  return 0;
27256}
27257
27258/*
27259** Find the current time (in Universal Coordinated Time).  Write the
27260** current time and date as a Julian Day number into *prNow and
27261** return 0.  Return 1 if the time and date cannot be found.
27262*/
27263static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27264  sqlite3_int64 i;
27265  UNUSED_PARAMETER(NotUsed);
27266  unixCurrentTimeInt64(0, &i);
27267  *prNow = i/86400000.0;
27268  return 0;
27269}
27270
27271/*
27272** We added the xGetLastError() method with the intention of providing
27273** better low-level error messages when operating-system problems come up
27274** during SQLite operation.  But so far, none of that has been implemented
27275** in the core.  So this routine is never called.  For now, it is merely
27276** a place-holder.
27277*/
27278static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
27279  UNUSED_PARAMETER(NotUsed);
27280  UNUSED_PARAMETER(NotUsed2);
27281  UNUSED_PARAMETER(NotUsed3);
27282  return 0;
27283}
27284
27285
27286/*
27287************************ End of sqlite3_vfs methods ***************************
27288******************************************************************************/
27289
27290/******************************************************************************
27291************************** Begin Proxy Locking ********************************
27292**
27293** Proxy locking is a "uber-locking-method" in this sense:  It uses the
27294** other locking methods on secondary lock files.  Proxy locking is a
27295** meta-layer over top of the primitive locking implemented above.  For
27296** this reason, the division that implements of proxy locking is deferred
27297** until late in the file (here) after all of the other I/O methods have
27298** been defined - so that the primitive locking methods are available
27299** as services to help with the implementation of proxy locking.
27300**
27301****
27302**
27303** The default locking schemes in SQLite use byte-range locks on the
27304** database file to coordinate safe, concurrent access by multiple readers
27305** and writers [http://sqlite.org/lockingv3.html].  The five file locking
27306** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
27307** as POSIX read & write locks over fixed set of locations (via fsctl),
27308** on AFP and SMB only exclusive byte-range locks are available via fsctl
27309** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
27310** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
27311** address in the shared range is taken for a SHARED lock, the entire
27312** shared range is taken for an EXCLUSIVE lock):
27313**
27314**      PENDING_BYTE        0x40000000
27315**      RESERVED_BYTE       0x40000001
27316**      SHARED_RANGE        0x40000002 -> 0x40000200
27317**
27318** This works well on the local file system, but shows a nearly 100x
27319** slowdown in read performance on AFP because the AFP client disables
27320** the read cache when byte-range locks are present.  Enabling the read
27321** cache exposes a cache coherency problem that is present on all OS X
27322** supported network file systems.  NFS and AFP both observe the
27323** close-to-open semantics for ensuring cache coherency
27324** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
27325** address the requirements for concurrent database access by multiple
27326** readers and writers
27327** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
27328**
27329** To address the performance and cache coherency issues, proxy file locking
27330** changes the way database access is controlled by limiting access to a
27331** single host at a time and moving file locks off of the database file
27332** and onto a proxy file on the local file system.
27333**
27334**
27335** Using proxy locks
27336** -----------------
27337**
27338** C APIs
27339**
27340**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
27341**                       <proxy_path> | ":auto:");
27342**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
27343**
27344**
27345** SQL pragmas
27346**
27347**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
27348**  PRAGMA [database.]lock_proxy_file
27349**
27350** Specifying ":auto:" means that if there is a conch file with a matching
27351** host ID in it, the proxy path in the conch file will be used, otherwise
27352** a proxy path based on the user's temp dir
27353** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
27354** actual proxy file name is generated from the name and path of the
27355** database file.  For example:
27356**
27357**       For database path "/Users/me/foo.db"
27358**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
27359**
27360** Once a lock proxy is configured for a database connection, it can not
27361** be removed, however it may be switched to a different proxy path via
27362** the above APIs (assuming the conch file is not being held by another
27363** connection or process).
27364**
27365**
27366** How proxy locking works
27367** -----------------------
27368**
27369** Proxy file locking relies primarily on two new supporting files:
27370**
27371**   *  conch file to limit access to the database file to a single host
27372**      at a time
27373**
27374**   *  proxy file to act as a proxy for the advisory locks normally
27375**      taken on the database
27376**
27377** The conch file - to use a proxy file, sqlite must first "hold the conch"
27378** by taking an sqlite-style shared lock on the conch file, reading the
27379** contents and comparing the host's unique host ID (see below) and lock
27380** proxy path against the values stored in the conch.  The conch file is
27381** stored in the same directory as the database file and the file name
27382** is patterned after the database file name as ".<databasename>-conch".
27383** If the conch file does not exist, or it's contents do not match the
27384** host ID and/or proxy path, then the lock is escalated to an exclusive
27385** lock and the conch file contents is updated with the host ID and proxy
27386** path and the lock is downgraded to a shared lock again.  If the conch
27387** is held by another process (with a shared lock), the exclusive lock
27388** will fail and SQLITE_BUSY is returned.
27389**
27390** The proxy file - a single-byte file used for all advisory file locks
27391** normally taken on the database file.   This allows for safe sharing
27392** of the database file for multiple readers and writers on the same
27393** host (the conch ensures that they all use the same local lock file).
27394**
27395** Requesting the lock proxy does not immediately take the conch, it is
27396** only taken when the first request to lock database file is made.
27397** This matches the semantics of the traditional locking behavior, where
27398** opening a connection to a database file does not take a lock on it.
27399** The shared lock and an open file descriptor are maintained until
27400** the connection to the database is closed.
27401**
27402** The proxy file and the lock file are never deleted so they only need
27403** to be created the first time they are used.
27404**
27405** Configuration options
27406** ---------------------
27407**
27408**  SQLITE_PREFER_PROXY_LOCKING
27409**
27410**       Database files accessed on non-local file systems are
27411**       automatically configured for proxy locking, lock files are
27412**       named automatically using the same logic as
27413**       PRAGMA lock_proxy_file=":auto:"
27414**
27415**  SQLITE_PROXY_DEBUG
27416**
27417**       Enables the logging of error messages during host id file
27418**       retrieval and creation
27419**
27420**  LOCKPROXYDIR
27421**
27422**       Overrides the default directory used for lock proxy files that
27423**       are named automatically via the ":auto:" setting
27424**
27425**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
27426**
27427**       Permissions to use when creating a directory for storing the
27428**       lock proxy files, only used when LOCKPROXYDIR is not set.
27429**
27430**
27431** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
27432** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
27433** force proxy locking to be used for every database file opened, and 0
27434** will force automatic proxy locking to be disabled for all database
27435** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
27436** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
27437*/
27438
27439/*
27440** Proxy locking is only available on MacOSX
27441*/
27442#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27443
27444/*
27445** The proxyLockingContext has the path and file structures for the remote
27446** and local proxy files in it
27447*/
27448typedef struct proxyLockingContext proxyLockingContext;
27449struct proxyLockingContext {
27450  unixFile *conchFile;         /* Open conch file */
27451  char *conchFilePath;         /* Name of the conch file */
27452  unixFile *lockProxy;         /* Open proxy lock file */
27453  char *lockProxyPath;         /* Name of the proxy lock file */
27454  char *dbPath;                /* Name of the open file */
27455  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
27456  void *oldLockingContext;     /* Original lockingcontext to restore on close */
27457  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
27458};
27459
27460/*
27461** The proxy lock file path for the database at dbPath is written into lPath,
27462** which must point to valid, writable memory large enough for a maxLen length
27463** file path.
27464*/
27465static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
27466  int len;
27467  int dbLen;
27468  int i;
27469
27470#ifdef LOCKPROXYDIR
27471  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
27472#else
27473# ifdef _CS_DARWIN_USER_TEMP_DIR
27474  {
27475    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
27476      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
27477               lPath, errno, getpid()));
27478      return SQLITE_IOERR_LOCK;
27479    }
27480    len = strlcat(lPath, "sqliteplocks", maxLen);
27481  }
27482# else
27483  len = strlcpy(lPath, "/tmp/", maxLen);
27484# endif
27485#endif
27486
27487  if( lPath[len-1]!='/' ){
27488    len = strlcat(lPath, "/", maxLen);
27489  }
27490
27491  /* transform the db path to a unique cache name */
27492  dbLen = (int)strlen(dbPath);
27493  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
27494    char c = dbPath[i];
27495    lPath[i+len] = (c=='/')?'_':c;
27496  }
27497  lPath[i+len]='\0';
27498  strlcat(lPath, ":auto:", maxLen);
27499  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
27500  return SQLITE_OK;
27501}
27502
27503/*
27504 ** Creates the lock file and any missing directories in lockPath
27505 */
27506static int proxyCreateLockPath(const char *lockPath){
27507  int i, len;
27508  char buf[MAXPATHLEN];
27509  int start = 0;
27510
27511  assert(lockPath!=NULL);
27512  /* try to create all the intermediate directories */
27513  len = (int)strlen(lockPath);
27514  buf[0] = lockPath[0];
27515  for( i=1; i<len; i++ ){
27516    if( lockPath[i] == '/' && (i - start > 0) ){
27517      /* only mkdir if leaf dir != "." or "/" or ".." */
27518      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
27519         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
27520        buf[i]='\0';
27521        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
27522          int err=errno;
27523          if( err!=EEXIST ) {
27524            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
27525                     "'%s' proxy lock path=%s pid=%d\n",
27526                     buf, strerror(err), lockPath, getpid()));
27527            return err;
27528          }
27529        }
27530      }
27531      start=i+1;
27532    }
27533    buf[i] = lockPath[i];
27534  }
27535  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
27536  return 0;
27537}
27538
27539/*
27540** Create a new VFS file descriptor (stored in memory obtained from
27541** sqlite3_malloc) and open the file named "path" in the file descriptor.
27542**
27543** The caller is responsible not only for closing the file descriptor
27544** but also for freeing the memory associated with the file descriptor.
27545*/
27546static int proxyCreateUnixFile(
27547    const char *path,        /* path for the new unixFile */
27548    unixFile **ppFile,       /* unixFile created and returned by ref */
27549    int islockfile           /* if non zero missing dirs will be created */
27550) {
27551  int fd = -1;
27552  int dirfd = -1;
27553  unixFile *pNew;
27554  int rc = SQLITE_OK;
27555  int openFlags = O_RDWR | O_CREAT;
27556  sqlite3_vfs dummyVfs;
27557  int terrno = 0;
27558  UnixUnusedFd *pUnused = NULL;
27559
27560  /* 1. first try to open/create the file
27561  ** 2. if that fails, and this is a lock file (not-conch), try creating
27562  ** the parent directories and then try again.
27563  ** 3. if that fails, try to open the file read-only
27564  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
27565  */
27566  pUnused = findReusableFd(path, openFlags);
27567  if( pUnused ){
27568    fd = pUnused->fd;
27569  }else{
27570    pUnused = sqlite3_malloc(sizeof(*pUnused));
27571    if( !pUnused ){
27572      return SQLITE_NOMEM;
27573    }
27574  }
27575  if( fd<0 ){
27576    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27577    terrno = errno;
27578    if( fd<0 && errno==ENOENT && islockfile ){
27579      if( proxyCreateLockPath(path) == SQLITE_OK ){
27580        fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27581      }
27582    }
27583  }
27584  if( fd<0 ){
27585    openFlags = O_RDONLY;
27586    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27587    terrno = errno;
27588  }
27589  if( fd<0 ){
27590    if( islockfile ){
27591      return SQLITE_BUSY;
27592    }
27593    switch (terrno) {
27594      case EACCES:
27595        return SQLITE_PERM;
27596      case EIO:
27597        return SQLITE_IOERR_LOCK; /* even though it is the conch */
27598      default:
27599        return SQLITE_CANTOPEN_BKPT;
27600    }
27601  }
27602
27603  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
27604  if( pNew==NULL ){
27605    rc = SQLITE_NOMEM;
27606    goto end_create_proxy;
27607  }
27608  memset(pNew, 0, sizeof(unixFile));
27609  pNew->openFlags = openFlags;
27610  dummyVfs.pAppData = (void*)&autolockIoFinder;
27611  pUnused->fd = fd;
27612  pUnused->flags = openFlags;
27613  pNew->pUnused = pUnused;
27614
27615  rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
27616  if( rc==SQLITE_OK ){
27617    *ppFile = pNew;
27618    return SQLITE_OK;
27619  }
27620end_create_proxy:
27621  close(fd); /* silently leak fd if error, we're already in error */
27622  sqlite3_free(pNew);
27623  sqlite3_free(pUnused);
27624  return rc;
27625}
27626
27627#ifdef SQLITE_TEST
27628/* simulate multiple hosts by creating unique hostid file paths */
27629SQLITE_API int sqlite3_hostid_num = 0;
27630#endif
27631
27632#define PROXY_HOSTIDLEN    16  /* conch file host id length */
27633
27634/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
27635** bytes of writable memory.
27636*/
27637static int proxyGetHostID(unsigned char *pHostID, int *pError){
27638  struct timespec timeout = {1, 0}; /* 1 sec timeout */
27639
27640  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
27641  memset(pHostID, 0, PROXY_HOSTIDLEN);
27642  if( gethostuuid(pHostID, &timeout) ){
27643    int err = errno;
27644    if( pError ){
27645      *pError = err;
27646    }
27647    return SQLITE_IOERR;
27648  }
27649#ifdef SQLITE_TEST
27650  /* simulate multiple hosts by creating unique hostid file paths */
27651  if( sqlite3_hostid_num != 0){
27652    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
27653  }
27654#endif
27655
27656  return SQLITE_OK;
27657}
27658
27659/* The conch file contains the header, host id and lock file path
27660 */
27661#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
27662#define PROXY_HEADERLEN    1   /* conch file header length */
27663#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
27664#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
27665
27666/*
27667** Takes an open conch file, copies the contents to a new path and then moves
27668** it back.  The newly created file's file descriptor is assigned to the
27669** conch file structure and finally the original conch file descriptor is
27670** closed.  Returns zero if successful.
27671*/
27672static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
27673  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27674  unixFile *conchFile = pCtx->conchFile;
27675  char tPath[MAXPATHLEN];
27676  char buf[PROXY_MAXCONCHLEN];
27677  char *cPath = pCtx->conchFilePath;
27678  size_t readLen = 0;
27679  size_t pathLen = 0;
27680  char errmsg[64] = "";
27681  int fd = -1;
27682  int rc = -1;
27683
27684  /* create a new path by replace the trailing '-conch' with '-break' */
27685  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
27686  if( pathLen>MAXPATHLEN || pathLen<6 ||
27687     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
27688    sprintf(errmsg, "path error (len %d)", (int)pathLen);
27689    goto end_breaklock;
27690  }
27691  /* read the conch content */
27692  readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
27693  if( readLen<PROXY_PATHINDEX ){
27694    sprintf(errmsg, "read error (len %d)", (int)readLen);
27695    goto end_breaklock;
27696  }
27697  /* write it out to the temporary break file */
27698  fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
27699  if( fd<0 ){
27700    sprintf(errmsg, "create failed (%d)", errno);
27701    goto end_breaklock;
27702  }
27703  if( pwrite(fd, buf, readLen, 0) != readLen ){
27704    sprintf(errmsg, "write failed (%d)", errno);
27705    goto end_breaklock;
27706  }
27707  if( rename(tPath, cPath) ){
27708    sprintf(errmsg, "rename failed (%d)", errno);
27709    goto end_breaklock;
27710  }
27711  rc = 0;
27712  fprintf(stderr, "broke stale lock on %s\n", cPath);
27713  close(conchFile->h);
27714  conchFile->h = fd;
27715  conchFile->openFlags = O_RDWR | O_CREAT;
27716
27717end_breaklock:
27718  if( rc ){
27719    if( fd>=0 ){
27720      unlink(tPath);
27721      close(fd);
27722    }
27723    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
27724  }
27725  return rc;
27726}
27727
27728/* Take the requested lock on the conch file and break a stale lock if the
27729** host id matches.
27730*/
27731static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
27732  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27733  unixFile *conchFile = pCtx->conchFile;
27734  int rc = SQLITE_OK;
27735  int nTries = 0;
27736  struct timespec conchModTime;
27737
27738  do {
27739    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27740    nTries ++;
27741    if( rc==SQLITE_BUSY ){
27742      /* If the lock failed (busy):
27743       * 1st try: get the mod time of the conch, wait 0.5s and try again.
27744       * 2nd try: fail if the mod time changed or host id is different, wait
27745       *           10 sec and try again
27746       * 3rd try: break the lock unless the mod time has changed.
27747       */
27748      struct stat buf;
27749      if( fstat(conchFile->h, &buf) ){
27750        pFile->lastErrno = errno;
27751        return SQLITE_IOERR_LOCK;
27752      }
27753
27754      if( nTries==1 ){
27755        conchModTime = buf.st_mtimespec;
27756        usleep(500000); /* wait 0.5 sec and try the lock again*/
27757        continue;
27758      }
27759
27760      assert( nTries>1 );
27761      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
27762         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
27763        return SQLITE_BUSY;
27764      }
27765
27766      if( nTries==2 ){
27767        char tBuf[PROXY_MAXCONCHLEN];
27768        int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
27769        if( len<0 ){
27770          pFile->lastErrno = errno;
27771          return SQLITE_IOERR_LOCK;
27772        }
27773        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
27774          /* don't break the lock if the host id doesn't match */
27775          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
27776            return SQLITE_BUSY;
27777          }
27778        }else{
27779          /* don't break the lock on short read or a version mismatch */
27780          return SQLITE_BUSY;
27781        }
27782        usleep(10000000); /* wait 10 sec and try the lock again */
27783        continue;
27784      }
27785
27786      assert( nTries==3 );
27787      if( 0==proxyBreakConchLock(pFile, myHostID) ){
27788        rc = SQLITE_OK;
27789        if( lockType==EXCLUSIVE_LOCK ){
27790          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
27791        }
27792        if( !rc ){
27793          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27794        }
27795      }
27796    }
27797  } while( rc==SQLITE_BUSY && nTries<3 );
27798
27799  return rc;
27800}
27801
27802/* Takes the conch by taking a shared lock and read the contents conch, if
27803** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
27804** lockPath means that the lockPath in the conch file will be used if the
27805** host IDs match, or a new lock path will be generated automatically
27806** and written to the conch file.
27807*/
27808static int proxyTakeConch(unixFile *pFile){
27809  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27810
27811  if( pCtx->conchHeld!=0 ){
27812    return SQLITE_OK;
27813  }else{
27814    unixFile *conchFile = pCtx->conchFile;
27815    uuid_t myHostID;
27816    int pError = 0;
27817    char readBuf[PROXY_MAXCONCHLEN];
27818    char lockPath[MAXPATHLEN];
27819    char *tempLockPath = NULL;
27820    int rc = SQLITE_OK;
27821    int createConch = 0;
27822    int hostIdMatch = 0;
27823    int readLen = 0;
27824    int tryOldLockPath = 0;
27825    int forceNewLockPath = 0;
27826
27827    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
27828             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
27829
27830    rc = proxyGetHostID(myHostID, &pError);
27831    if( (rc&0xff)==SQLITE_IOERR ){
27832      pFile->lastErrno = pError;
27833      goto end_takeconch;
27834    }
27835    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
27836    if( rc!=SQLITE_OK ){
27837      goto end_takeconch;
27838    }
27839    /* read the existing conch file */
27840    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
27841    if( readLen<0 ){
27842      /* I/O error: lastErrno set by seekAndRead */
27843      pFile->lastErrno = conchFile->lastErrno;
27844      rc = SQLITE_IOERR_READ;
27845      goto end_takeconch;
27846    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
27847             readBuf[0]!=(char)PROXY_CONCHVERSION ){
27848      /* a short read or version format mismatch means we need to create a new
27849      ** conch file.
27850      */
27851      createConch = 1;
27852    }
27853    /* if the host id matches and the lock path already exists in the conch
27854    ** we'll try to use the path there, if we can't open that path, we'll
27855    ** retry with a new auto-generated path
27856    */
27857    do { /* in case we need to try again for an :auto: named lock file */
27858
27859      if( !createConch && !forceNewLockPath ){
27860        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
27861                                  PROXY_HOSTIDLEN);
27862        /* if the conch has data compare the contents */
27863        if( !pCtx->lockProxyPath ){
27864          /* for auto-named local lock file, just check the host ID and we'll
27865           ** use the local lock file path that's already in there
27866           */
27867          if( hostIdMatch ){
27868            size_t pathLen = (readLen - PROXY_PATHINDEX);
27869
27870            if( pathLen>=MAXPATHLEN ){
27871              pathLen=MAXPATHLEN-1;
27872            }
27873            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
27874            lockPath[pathLen] = 0;
27875            tempLockPath = lockPath;
27876            tryOldLockPath = 1;
27877            /* create a copy of the lock path if the conch is taken */
27878            goto end_takeconch;
27879          }
27880        }else if( hostIdMatch
27881               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
27882                           readLen-PROXY_PATHINDEX)
27883        ){
27884          /* conch host and lock path match */
27885          goto end_takeconch;
27886        }
27887      }
27888
27889      /* if the conch isn't writable and doesn't match, we can't take it */
27890      if( (conchFile->openFlags&O_RDWR) == 0 ){
27891        rc = SQLITE_BUSY;
27892        goto end_takeconch;
27893      }
27894
27895      /* either the conch didn't match or we need to create a new one */
27896      if( !pCtx->lockProxyPath ){
27897        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
27898        tempLockPath = lockPath;
27899        /* create a copy of the lock path _only_ if the conch is taken */
27900      }
27901
27902      /* update conch with host and path (this will fail if other process
27903      ** has a shared lock already), if the host id matches, use the big
27904      ** stick.
27905      */
27906      futimes(conchFile->h, NULL);
27907      if( hostIdMatch && !createConch ){
27908        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
27909          /* We are trying for an exclusive lock but another thread in this
27910           ** same process is still holding a shared lock. */
27911          rc = SQLITE_BUSY;
27912        } else {
27913          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
27914        }
27915      }else{
27916        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
27917      }
27918      if( rc==SQLITE_OK ){
27919        char writeBuffer[PROXY_MAXCONCHLEN];
27920        int writeSize = 0;
27921
27922        writeBuffer[0] = (char)PROXY_CONCHVERSION;
27923        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
27924        if( pCtx->lockProxyPath!=NULL ){
27925          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
27926        }else{
27927          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
27928        }
27929        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
27930        ftruncate(conchFile->h, writeSize);
27931        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
27932        fsync(conchFile->h);
27933        /* If we created a new conch file (not just updated the contents of a
27934         ** valid conch file), try to match the permissions of the database
27935         */
27936        if( rc==SQLITE_OK && createConch ){
27937          struct stat buf;
27938          int err = fstat(pFile->h, &buf);
27939          if( err==0 ){
27940            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
27941                                        S_IROTH|S_IWOTH);
27942            /* try to match the database file R/W permissions, ignore failure */
27943#ifndef SQLITE_PROXY_DEBUG
27944            fchmod(conchFile->h, cmode);
27945#else
27946            if( fchmod(conchFile->h, cmode)!=0 ){
27947              int code = errno;
27948              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
27949                      cmode, code, strerror(code));
27950            } else {
27951              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
27952            }
27953          }else{
27954            int code = errno;
27955            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
27956                    err, code, strerror(code));
27957#endif
27958          }
27959        }
27960      }
27961      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
27962
27963    end_takeconch:
27964      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
27965      if( rc==SQLITE_OK && pFile->openFlags ){
27966        if( pFile->h>=0 ){
27967#ifdef STRICT_CLOSE_ERROR
27968          if( close(pFile->h) ){
27969            pFile->lastErrno = errno;
27970            return SQLITE_IOERR_CLOSE;
27971          }
27972#else
27973          close(pFile->h); /* silently leak fd if fail */
27974#endif
27975        }
27976        pFile->h = -1;
27977        int fd = open(pCtx->dbPath, pFile->openFlags,
27978                      SQLITE_DEFAULT_FILE_PERMISSIONS);
27979        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
27980        if( fd>=0 ){
27981          pFile->h = fd;
27982        }else{
27983          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
27984           during locking */
27985        }
27986      }
27987      if( rc==SQLITE_OK && !pCtx->lockProxy ){
27988        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
27989        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
27990        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
27991          /* we couldn't create the proxy lock file with the old lock file path
27992           ** so try again via auto-naming
27993           */
27994          forceNewLockPath = 1;
27995          tryOldLockPath = 0;
27996          continue; /* go back to the do {} while start point, try again */
27997        }
27998      }
27999      if( rc==SQLITE_OK ){
28000        /* Need to make a copy of path if we extracted the value
28001         ** from the conch file or the path was allocated on the stack
28002         */
28003        if( tempLockPath ){
28004          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28005          if( !pCtx->lockProxyPath ){
28006            rc = SQLITE_NOMEM;
28007          }
28008        }
28009      }
28010      if( rc==SQLITE_OK ){
28011        pCtx->conchHeld = 1;
28012
28013        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28014          afpLockingContext *afpCtx;
28015          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28016          afpCtx->dbPath = pCtx->lockProxyPath;
28017        }
28018      } else {
28019        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28020      }
28021      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28022               rc==SQLITE_OK?"ok":"failed"));
28023      return rc;
28024    } while (1); /* in case we need to retry the :auto: lock file -
28025                 ** we should never get here except via the 'continue' call. */
28026  }
28027}
28028
28029/*
28030** If pFile holds a lock on a conch file, then release that lock.
28031*/
28032static int proxyReleaseConch(unixFile *pFile){
28033  int rc = SQLITE_OK;         /* Subroutine return code */
28034  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28035  unixFile *conchFile;        /* Name of the conch file */
28036
28037  pCtx = (proxyLockingContext *)pFile->lockingContext;
28038  conchFile = pCtx->conchFile;
28039  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28040           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
28041           getpid()));
28042  if( pCtx->conchHeld>0 ){
28043    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28044  }
28045  pCtx->conchHeld = 0;
28046  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28047           (rc==SQLITE_OK ? "ok" : "failed")));
28048  return rc;
28049}
28050
28051/*
28052** Given the name of a database file, compute the name of its conch file.
28053** Store the conch filename in memory obtained from sqlite3_malloc().
28054** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28055** or SQLITE_NOMEM if unable to obtain memory.
28056**
28057** The caller is responsible for ensuring that the allocated memory
28058** space is eventually freed.
28059**
28060** *pConchPath is set to NULL if a memory allocation error occurs.
28061*/
28062static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28063  int i;                        /* Loop counter */
28064  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28065  char *conchPath;              /* buffer in which to construct conch name */
28066
28067  /* Allocate space for the conch filename and initialize the name to
28068  ** the name of the original database file. */
28069  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28070  if( conchPath==0 ){
28071    return SQLITE_NOMEM;
28072  }
28073  memcpy(conchPath, dbPath, len+1);
28074
28075  /* now insert a "." before the last / character */
28076  for( i=(len-1); i>=0; i-- ){
28077    if( conchPath[i]=='/' ){
28078      i++;
28079      break;
28080    }
28081  }
28082  conchPath[i]='.';
28083  while ( i<len ){
28084    conchPath[i+1]=dbPath[i];
28085    i++;
28086  }
28087
28088  /* append the "-conch" suffix to the file */
28089  memcpy(&conchPath[i+1], "-conch", 7);
28090  assert( (int)strlen(conchPath) == len+7 );
28091
28092  return SQLITE_OK;
28093}
28094
28095
28096/* Takes a fully configured proxy locking-style unix file and switches
28097** the local lock file path
28098*/
28099static int switchLockProxyPath(unixFile *pFile, const char *path) {
28100  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28101  char *oldPath = pCtx->lockProxyPath;
28102  int rc = SQLITE_OK;
28103
28104  if( pFile->eFileLock!=NO_LOCK ){
28105    return SQLITE_BUSY;
28106  }
28107
28108  /* nothing to do if the path is NULL, :auto: or matches the existing path */
28109  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28110    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28111    return SQLITE_OK;
28112  }else{
28113    unixFile *lockProxy = pCtx->lockProxy;
28114    pCtx->lockProxy=NULL;
28115    pCtx->conchHeld = 0;
28116    if( lockProxy!=NULL ){
28117      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28118      if( rc ) return rc;
28119      sqlite3_free(lockProxy);
28120    }
28121    sqlite3_free(oldPath);
28122    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28123  }
28124
28125  return rc;
28126}
28127
28128/*
28129** pFile is a file that has been opened by a prior xOpen call.  dbPath
28130** is a string buffer at least MAXPATHLEN+1 characters in size.
28131**
28132** This routine find the filename associated with pFile and writes it
28133** int dbPath.
28134*/
28135static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28136#if defined(__APPLE__)
28137  if( pFile->pMethod == &afpIoMethods ){
28138    /* afp style keeps a reference to the db path in the filePath field
28139    ** of the struct */
28140    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28141    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28142  } else
28143#endif
28144  if( pFile->pMethod == &dotlockIoMethods ){
28145    /* dot lock style uses the locking context to store the dot lock
28146    ** file path */
28147    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28148    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28149  }else{
28150    /* all other styles use the locking context to store the db file path */
28151    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28152    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28153  }
28154  return SQLITE_OK;
28155}
28156
28157/*
28158** Takes an already filled in unix file and alters it so all file locking
28159** will be performed on the local proxy lock file.  The following fields
28160** are preserved in the locking context so that they can be restored and
28161** the unix structure properly cleaned up at close time:
28162**  ->lockingContext
28163**  ->pMethod
28164*/
28165static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28166  proxyLockingContext *pCtx;
28167  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28168  char *lockPath=NULL;
28169  int rc = SQLITE_OK;
28170
28171  if( pFile->eFileLock!=NO_LOCK ){
28172    return SQLITE_BUSY;
28173  }
28174  proxyGetDbPathForUnixFile(pFile, dbPath);
28175  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28176    lockPath=NULL;
28177  }else{
28178    lockPath=(char *)path;
28179  }
28180
28181  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28182           (lockPath ? lockPath : ":auto:"), getpid()));
28183
28184  pCtx = sqlite3_malloc( sizeof(*pCtx) );
28185  if( pCtx==0 ){
28186    return SQLITE_NOMEM;
28187  }
28188  memset(pCtx, 0, sizeof(*pCtx));
28189
28190  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28191  if( rc==SQLITE_OK ){
28192    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28193    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28194      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28195      ** (c) the file system is read-only, then enable no-locking access.
28196      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28197      ** that openFlags will have only one of O_RDONLY or O_RDWR.
28198      */
28199      struct statfs fsInfo;
28200      struct stat conchInfo;
28201      int goLockless = 0;
28202
28203      if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28204        int err = errno;
28205        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28206          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28207        }
28208      }
28209      if( goLockless ){
28210        pCtx->conchHeld = -1; /* read only FS/ lockless */
28211        rc = SQLITE_OK;
28212      }
28213    }
28214  }
28215  if( rc==SQLITE_OK && lockPath ){
28216    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28217  }
28218
28219  if( rc==SQLITE_OK ){
28220    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28221    if( pCtx->dbPath==NULL ){
28222      rc = SQLITE_NOMEM;
28223    }
28224  }
28225  if( rc==SQLITE_OK ){
28226    /* all memory is allocated, proxys are created and assigned,
28227    ** switch the locking context and pMethod then return.
28228    */
28229    pCtx->oldLockingContext = pFile->lockingContext;
28230    pFile->lockingContext = pCtx;
28231    pCtx->pOldMethod = pFile->pMethod;
28232    pFile->pMethod = &proxyIoMethods;
28233  }else{
28234    if( pCtx->conchFile ){
28235      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28236      sqlite3_free(pCtx->conchFile);
28237    }
28238    sqlite3_free(pCtx->lockProxyPath);
28239    sqlite3_free(pCtx->conchFilePath);
28240    sqlite3_free(pCtx);
28241  }
28242  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
28243           (rc==SQLITE_OK ? "ok" : "failed")));
28244  return rc;
28245}
28246
28247
28248/*
28249** This routine handles sqlite3_file_control() calls that are specific
28250** to proxy locking.
28251*/
28252static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
28253  switch( op ){
28254    case SQLITE_GET_LOCKPROXYFILE: {
28255      unixFile *pFile = (unixFile*)id;
28256      if( pFile->pMethod == &proxyIoMethods ){
28257        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28258        proxyTakeConch(pFile);
28259        if( pCtx->lockProxyPath ){
28260          *(const char **)pArg = pCtx->lockProxyPath;
28261        }else{
28262          *(const char **)pArg = ":auto: (not held)";
28263        }
28264      } else {
28265        *(const char **)pArg = NULL;
28266      }
28267      return SQLITE_OK;
28268    }
28269    case SQLITE_SET_LOCKPROXYFILE: {
28270      unixFile *pFile = (unixFile*)id;
28271      int rc = SQLITE_OK;
28272      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
28273      if( pArg==NULL || (const char *)pArg==0 ){
28274        if( isProxyStyle ){
28275          /* turn off proxy locking - not supported */
28276          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
28277        }else{
28278          /* turn off proxy locking - already off - NOOP */
28279          rc = SQLITE_OK;
28280        }
28281      }else{
28282        const char *proxyPath = (const char *)pArg;
28283        if( isProxyStyle ){
28284          proxyLockingContext *pCtx =
28285            (proxyLockingContext*)pFile->lockingContext;
28286          if( !strcmp(pArg, ":auto:")
28287           || (pCtx->lockProxyPath &&
28288               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
28289          ){
28290            rc = SQLITE_OK;
28291          }else{
28292            rc = switchLockProxyPath(pFile, proxyPath);
28293          }
28294        }else{
28295          /* turn on proxy file locking */
28296          rc = proxyTransformUnixFile(pFile, proxyPath);
28297        }
28298      }
28299      return rc;
28300    }
28301    default: {
28302      assert( 0 );  /* The call assures that only valid opcodes are sent */
28303    }
28304  }
28305  /*NOTREACHED*/
28306  return SQLITE_ERROR;
28307}
28308
28309/*
28310** Within this division (the proxying locking implementation) the procedures
28311** above this point are all utilities.  The lock-related methods of the
28312** proxy-locking sqlite3_io_method object follow.
28313*/
28314
28315
28316/*
28317** This routine checks if there is a RESERVED lock held on the specified
28318** file by this or any other process. If such a lock is held, set *pResOut
28319** to a non-zero value otherwise *pResOut is set to zero.  The return value
28320** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28321*/
28322static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
28323  unixFile *pFile = (unixFile*)id;
28324  int rc = proxyTakeConch(pFile);
28325  if( rc==SQLITE_OK ){
28326    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28327    if( pCtx->conchHeld>0 ){
28328      unixFile *proxy = pCtx->lockProxy;
28329      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
28330    }else{ /* conchHeld < 0 is lockless */
28331      pResOut=0;
28332    }
28333  }
28334  return rc;
28335}
28336
28337/*
28338** Lock the file with the lock specified by parameter eFileLock - one
28339** of the following:
28340**
28341**     (1) SHARED_LOCK
28342**     (2) RESERVED_LOCK
28343**     (3) PENDING_LOCK
28344**     (4) EXCLUSIVE_LOCK
28345**
28346** Sometimes when requesting one lock state, additional lock states
28347** are inserted in between.  The locking might fail on one of the later
28348** transitions leaving the lock state different from what it started but
28349** still short of its goal.  The following chart shows the allowed
28350** transitions and the inserted intermediate states:
28351**
28352**    UNLOCKED -> SHARED
28353**    SHARED -> RESERVED
28354**    SHARED -> (PENDING) -> EXCLUSIVE
28355**    RESERVED -> (PENDING) -> EXCLUSIVE
28356**    PENDING -> EXCLUSIVE
28357**
28358** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28359** routine to lower a locking level.
28360*/
28361static int proxyLock(sqlite3_file *id, int eFileLock) {
28362  unixFile *pFile = (unixFile*)id;
28363  int rc = proxyTakeConch(pFile);
28364  if( rc==SQLITE_OK ){
28365    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28366    if( pCtx->conchHeld>0 ){
28367      unixFile *proxy = pCtx->lockProxy;
28368      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
28369      pFile->eFileLock = proxy->eFileLock;
28370    }else{
28371      /* conchHeld < 0 is lockless */
28372    }
28373  }
28374  return rc;
28375}
28376
28377
28378/*
28379** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28380** must be either NO_LOCK or SHARED_LOCK.
28381**
28382** If the locking level of the file descriptor is already at or below
28383** the requested locking level, this routine is a no-op.
28384*/
28385static int proxyUnlock(sqlite3_file *id, int eFileLock) {
28386  unixFile *pFile = (unixFile*)id;
28387  int rc = proxyTakeConch(pFile);
28388  if( rc==SQLITE_OK ){
28389    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28390    if( pCtx->conchHeld>0 ){
28391      unixFile *proxy = pCtx->lockProxy;
28392      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
28393      pFile->eFileLock = proxy->eFileLock;
28394    }else{
28395      /* conchHeld < 0 is lockless */
28396    }
28397  }
28398  return rc;
28399}
28400
28401/*
28402** Close a file that uses proxy locks.
28403*/
28404static int proxyClose(sqlite3_file *id) {
28405  if( id ){
28406    unixFile *pFile = (unixFile*)id;
28407    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28408    unixFile *lockProxy = pCtx->lockProxy;
28409    unixFile *conchFile = pCtx->conchFile;
28410    int rc = SQLITE_OK;
28411
28412    if( lockProxy ){
28413      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
28414      if( rc ) return rc;
28415      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
28416      if( rc ) return rc;
28417      sqlite3_free(lockProxy);
28418      pCtx->lockProxy = 0;
28419    }
28420    if( conchFile ){
28421      if( pCtx->conchHeld ){
28422        rc = proxyReleaseConch(pFile);
28423        if( rc ) return rc;
28424      }
28425      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
28426      if( rc ) return rc;
28427      sqlite3_free(conchFile);
28428    }
28429    sqlite3_free(pCtx->lockProxyPath);
28430    sqlite3_free(pCtx->conchFilePath);
28431    sqlite3_free(pCtx->dbPath);
28432    /* restore the original locking context and pMethod then close it */
28433    pFile->lockingContext = pCtx->oldLockingContext;
28434    pFile->pMethod = pCtx->pOldMethod;
28435    sqlite3_free(pCtx);
28436    return pFile->pMethod->xClose(id);
28437  }
28438  return SQLITE_OK;
28439}
28440
28441
28442
28443#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28444/*
28445** The proxy locking style is intended for use with AFP filesystems.
28446** And since AFP is only supported on MacOSX, the proxy locking is also
28447** restricted to MacOSX.
28448**
28449**
28450******************* End of the proxy lock implementation **********************
28451******************************************************************************/
28452
28453/*
28454** Initialize the operating system interface.
28455**
28456** This routine registers all VFS implementations for unix-like operating
28457** systems.  This routine, and the sqlite3_os_end() routine that follows,
28458** should be the only routines in this file that are visible from other
28459** files.
28460**
28461** This routine is called once during SQLite initialization and by a
28462** single thread.  The memory allocation and mutex subsystems have not
28463** necessarily been initialized when this routine is called, and so they
28464** should not be used.
28465*/
28466SQLITE_API int sqlite3_os_init(void){
28467  /*
28468  ** The following macro defines an initializer for an sqlite3_vfs object.
28469  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
28470  ** to the "finder" function.  (pAppData is a pointer to a pointer because
28471  ** silly C90 rules prohibit a void* from being cast to a function pointer
28472  ** and so we have to go through the intermediate pointer to avoid problems
28473  ** when compiling with -pedantic-errors on GCC.)
28474  **
28475  ** The FINDER parameter to this macro is the name of the pointer to the
28476  ** finder-function.  The finder-function returns a pointer to the
28477  ** sqlite_io_methods object that implements the desired locking
28478  ** behaviors.  See the division above that contains the IOMETHODS
28479  ** macro for addition information on finder-functions.
28480  **
28481  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
28482  ** object.  But the "autolockIoFinder" available on MacOSX does a little
28483  ** more than that; it looks at the filesystem type that hosts the
28484  ** database file and tries to choose an locking method appropriate for
28485  ** that filesystem time.
28486  */
28487  #define UNIXVFS(VFSNAME, FINDER) {                        \
28488    2,                    /* iVersion */                    \
28489    sizeof(unixFile),     /* szOsFile */                    \
28490    MAX_PATHNAME,         /* mxPathname */                  \
28491    0,                    /* pNext */                       \
28492    VFSNAME,              /* zName */                       \
28493    (void*)&FINDER,       /* pAppData */                    \
28494    unixOpen,             /* xOpen */                       \
28495    unixDelete,           /* xDelete */                     \
28496    unixAccess,           /* xAccess */                     \
28497    unixFullPathname,     /* xFullPathname */               \
28498    unixDlOpen,           /* xDlOpen */                     \
28499    unixDlError,          /* xDlError */                    \
28500    unixDlSym,            /* xDlSym */                      \
28501    unixDlClose,          /* xDlClose */                    \
28502    unixRandomness,       /* xRandomness */                 \
28503    unixSleep,            /* xSleep */                      \
28504    unixCurrentTime,      /* xCurrentTime */                \
28505    unixGetLastError,     /* xGetLastError */               \
28506    0,                    /* xRename */                     \
28507    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
28508  }
28509
28510  /*
28511  ** All default VFSes for unix are contained in the following array.
28512  **
28513  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
28514  ** by the SQLite core when the VFS is registered.  So the following
28515  ** array cannot be const.
28516  */
28517  static sqlite3_vfs aVfs[] = {
28518#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
28519    UNIXVFS("unix",          autolockIoFinder ),
28520#else
28521    UNIXVFS("unix",          posixIoFinder ),
28522#endif
28523    UNIXVFS("unix-none",     nolockIoFinder ),
28524    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
28525#if OS_VXWORKS
28526    UNIXVFS("unix-namedsem", semIoFinder ),
28527#endif
28528#if SQLITE_ENABLE_LOCKING_STYLE
28529    UNIXVFS("unix-posix",    posixIoFinder ),
28530#if !OS_VXWORKS
28531    UNIXVFS("unix-flock",    flockIoFinder ),
28532#endif
28533#endif
28534#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28535    UNIXVFS("unix-afp",      afpIoFinder ),
28536    UNIXVFS("unix-nfs",      nfsIoFinder ),
28537    UNIXVFS("unix-proxy",    proxyIoFinder ),
28538#endif
28539  };
28540  unsigned int i;          /* Loop counter */
28541
28542  /* Register all VFSes defined in the aVfs[] array */
28543  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
28544    sqlite3_vfs_register(&aVfs[i], i==0);
28545  }
28546  return SQLITE_OK;
28547}
28548
28549/*
28550** Shutdown the operating system interface.
28551**
28552** Some operating systems might need to do some cleanup in this routine,
28553** to release dynamically allocated objects.  But not on unix.
28554** This routine is a no-op for unix.
28555*/
28556SQLITE_API int sqlite3_os_end(void){
28557  return SQLITE_OK;
28558}
28559
28560#endif /* SQLITE_OS_UNIX */
28561
28562/************** End of os_unix.c *********************************************/
28563/************** Begin file os_win.c ******************************************/
28564/*
28565** 2004 May 22
28566**
28567** The author disclaims copyright to this source code.  In place of
28568** a legal notice, here is a blessing:
28569**
28570**    May you do good and not evil.
28571**    May you find forgiveness for yourself and forgive others.
28572**    May you share freely, never taking more than you give.
28573**
28574******************************************************************************
28575**
28576** This file contains code that is specific to windows.
28577*/
28578#if SQLITE_OS_WIN               /* This file is used for windows only */
28579
28580
28581/*
28582** A Note About Memory Allocation:
28583**
28584** This driver uses malloc()/free() directly rather than going through
28585** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
28586** are designed for use on embedded systems where memory is scarce and
28587** malloc failures happen frequently.  Win32 does not typically run on
28588** embedded systems, and when it does the developers normally have bigger
28589** problems to worry about than running out of memory.  So there is not
28590** a compelling need to use the wrappers.
28591**
28592** But there is a good reason to not use the wrappers.  If we use the
28593** wrappers then we will get simulated malloc() failures within this
28594** driver.  And that causes all kinds of problems for our tests.  We
28595** could enhance SQLite to deal with simulated malloc failures within
28596** the OS driver, but the code to deal with those failure would not
28597** be exercised on Linux (which does not need to malloc() in the driver)
28598** and so we would have difficulty writing coverage tests for that
28599** code.  Better to leave the code out, we think.
28600**
28601** The point of this discussion is as follows:  When creating a new
28602** OS layer for an embedded system, if you use this file as an example,
28603** avoid the use of malloc()/free().  Those routines work ok on windows
28604** desktops but not so well in embedded systems.
28605*/
28606
28607#include <winbase.h>
28608
28609#ifdef __CYGWIN__
28610# include <sys/cygwin.h>
28611#endif
28612
28613/*
28614** Macros used to determine whether or not to use threads.
28615*/
28616#if defined(THREADSAFE) && THREADSAFE
28617# define SQLITE_W32_THREADS 1
28618#endif
28619
28620/*
28621** Include code that is common to all os_*.c files
28622*/
28623/************** Include os_common.h in the middle of os_win.c ****************/
28624/************** Begin file os_common.h ***************************************/
28625/*
28626** 2004 May 22
28627**
28628** The author disclaims copyright to this source code.  In place of
28629** a legal notice, here is a blessing:
28630**
28631**    May you do good and not evil.
28632**    May you find forgiveness for yourself and forgive others.
28633**    May you share freely, never taking more than you give.
28634**
28635******************************************************************************
28636**
28637** This file contains macros and a little bit of code that is common to
28638** all of the platform-specific files (os_*.c) and is #included into those
28639** files.
28640**
28641** This file should be #included by the os_*.c files only.  It is not a
28642** general purpose header file.
28643*/
28644#ifndef _OS_COMMON_H_
28645#define _OS_COMMON_H_
28646
28647/*
28648** At least two bugs have slipped in because we changed the MEMORY_DEBUG
28649** macro to SQLITE_DEBUG and some older makefiles have not yet made the
28650** switch.  The following code should catch this problem at compile-time.
28651*/
28652#ifdef MEMORY_DEBUG
28653# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
28654#endif
28655
28656#ifdef SQLITE_DEBUG
28657SQLITE_PRIVATE int sqlite3OSTrace = 0;
28658#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
28659#else
28660#define OSTRACE(X)
28661#endif
28662
28663/*
28664** Macros for performance tracing.  Normally turned off.  Only works
28665** on i486 hardware.
28666*/
28667#ifdef SQLITE_PERFORMANCE_TRACE
28668
28669/*
28670** hwtime.h contains inline assembler code for implementing
28671** high-performance timing routines.
28672*/
28673/************** Include hwtime.h in the middle of os_common.h ****************/
28674/************** Begin file hwtime.h ******************************************/
28675/*
28676** 2008 May 27
28677**
28678** The author disclaims copyright to this source code.  In place of
28679** a legal notice, here is a blessing:
28680**
28681**    May you do good and not evil.
28682**    May you find forgiveness for yourself and forgive others.
28683**    May you share freely, never taking more than you give.
28684**
28685******************************************************************************
28686**
28687** This file contains inline asm code for retrieving "high-performance"
28688** counters for x86 class CPUs.
28689*/
28690#ifndef _HWTIME_H_
28691#define _HWTIME_H_
28692
28693/*
28694** The following routine only works on pentium-class (or newer) processors.
28695** It uses the RDTSC opcode to read the cycle count value out of the
28696** processor and returns that value.  This can be used for high-res
28697** profiling.
28698*/
28699#if (defined(__GNUC__) || defined(_MSC_VER)) && \
28700      (defined(i386) || defined(__i386__) || defined(_M_IX86))
28701
28702  #if defined(__GNUC__)
28703
28704  __inline__ sqlite_uint64 sqlite3Hwtime(void){
28705     unsigned int lo, hi;
28706     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
28707     return (sqlite_uint64)hi << 32 | lo;
28708  }
28709
28710  #elif defined(_MSC_VER)
28711
28712  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
28713     __asm {
28714        rdtsc
28715        ret       ; return value at EDX:EAX
28716     }
28717  }
28718
28719  #endif
28720
28721#elif (defined(__GNUC__) && defined(__x86_64__))
28722
28723  __inline__ sqlite_uint64 sqlite3Hwtime(void){
28724      unsigned long val;
28725      __asm__ __volatile__ ("rdtsc" : "=A" (val));
28726      return val;
28727  }
28728
28729#elif (defined(__GNUC__) && defined(__ppc__))
28730
28731  __inline__ sqlite_uint64 sqlite3Hwtime(void){
28732      unsigned long long retval;
28733      unsigned long junk;
28734      __asm__ __volatile__ ("\n\
28735          1:      mftbu   %1\n\
28736                  mftb    %L0\n\
28737                  mftbu   %0\n\
28738                  cmpw    %0,%1\n\
28739                  bne     1b"
28740                  : "=r" (retval), "=r" (junk));
28741      return retval;
28742  }
28743
28744#else
28745
28746  #error Need implementation of sqlite3Hwtime() for your platform.
28747
28748  /*
28749  ** To compile without implementing sqlite3Hwtime() for your platform,
28750  ** you can remove the above #error and use the following
28751  ** stub function.  You will lose timing support for many
28752  ** of the debugging and testing utilities, but it should at
28753  ** least compile and run.
28754  */
28755SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
28756
28757#endif
28758
28759#endif /* !defined(_HWTIME_H_) */
28760
28761/************** End of hwtime.h **********************************************/
28762/************** Continuing where we left off in os_common.h ******************/
28763
28764static sqlite_uint64 g_start;
28765static sqlite_uint64 g_elapsed;
28766#define TIMER_START       g_start=sqlite3Hwtime()
28767#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
28768#define TIMER_ELAPSED     g_elapsed
28769#else
28770#define TIMER_START
28771#define TIMER_END
28772#define TIMER_ELAPSED     ((sqlite_uint64)0)
28773#endif
28774
28775/*
28776** If we compile with the SQLITE_TEST macro set, then the following block
28777** of code will give us the ability to simulate a disk I/O error.  This
28778** is used for testing the I/O recovery logic.
28779*/
28780#ifdef SQLITE_TEST
28781SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
28782SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
28783SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
28784SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
28785SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
28786SQLITE_API int sqlite3_diskfull_pending = 0;
28787SQLITE_API int sqlite3_diskfull = 0;
28788#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
28789#define SimulateIOError(CODE)  \
28790  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
28791       || sqlite3_io_error_pending-- == 1 )  \
28792              { local_ioerr(); CODE; }
28793static void local_ioerr(){
28794  IOTRACE(("IOERR\n"));
28795  sqlite3_io_error_hit++;
28796  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
28797}
28798#define SimulateDiskfullError(CODE) \
28799   if( sqlite3_diskfull_pending ){ \
28800     if( sqlite3_diskfull_pending == 1 ){ \
28801       local_ioerr(); \
28802       sqlite3_diskfull = 1; \
28803       sqlite3_io_error_hit = 1; \
28804       CODE; \
28805     }else{ \
28806       sqlite3_diskfull_pending--; \
28807     } \
28808   }
28809#else
28810#define SimulateIOErrorBenign(X)
28811#define SimulateIOError(A)
28812#define SimulateDiskfullError(A)
28813#endif
28814
28815/*
28816** When testing, keep a count of the number of open files.
28817*/
28818#ifdef SQLITE_TEST
28819SQLITE_API int sqlite3_open_file_count = 0;
28820#define OpenCounter(X)  sqlite3_open_file_count+=(X)
28821#else
28822#define OpenCounter(X)
28823#endif
28824
28825#endif /* !defined(_OS_COMMON_H_) */
28826
28827/************** End of os_common.h *******************************************/
28828/************** Continuing where we left off in os_win.c *********************/
28829
28830/*
28831** Some microsoft compilers lack this definition.
28832*/
28833#ifndef INVALID_FILE_ATTRIBUTES
28834# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
28835#endif
28836
28837/*
28838** Determine if we are dealing with WindowsCE - which has a much
28839** reduced API.
28840*/
28841#if SQLITE_OS_WINCE
28842# define AreFileApisANSI() 1
28843# define FormatMessageW(a,b,c,d,e,f,g) 0
28844#endif
28845
28846/* Forward references */
28847typedef struct winShm winShm;           /* A connection to shared-memory */
28848typedef struct winShmNode winShmNode;   /* A region of shared-memory */
28849
28850/*
28851** WinCE lacks native support for file locking so we have to fake it
28852** with some code of our own.
28853*/
28854#if SQLITE_OS_WINCE
28855typedef struct winceLock {
28856  int nReaders;       /* Number of reader locks obtained */
28857  BOOL bPending;      /* Indicates a pending lock has been obtained */
28858  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
28859  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
28860} winceLock;
28861#endif
28862
28863/*
28864** The winFile structure is a subclass of sqlite3_file* specific to the win32
28865** portability layer.
28866*/
28867typedef struct winFile winFile;
28868struct winFile {
28869  const sqlite3_io_methods *pMethod; /*** Must be first ***/
28870  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
28871  HANDLE h;               /* Handle for accessing the file */
28872  unsigned char locktype; /* Type of lock currently held on this file */
28873  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
28874  DWORD lastErrno;        /* The Windows errno from the last I/O error */
28875  DWORD sectorSize;       /* Sector size of the device file is on */
28876  winShm *pShm;           /* Instance of shared memory on this file */
28877  const char *zPath;      /* Full pathname of this file */
28878#if SQLITE_OS_WINCE
28879  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
28880  HANDLE hMutex;          /* Mutex used to control access to shared lock */
28881  HANDLE hShared;         /* Shared memory segment used for locking */
28882  winceLock local;        /* Locks obtained by this instance of winFile */
28883  winceLock *shared;      /* Global shared lock memory for the file  */
28884#endif
28885};
28886
28887/*
28888** Forward prototypes.
28889*/
28890static int getSectorSize(
28891    sqlite3_vfs *pVfs,
28892    const char *zRelative     /* UTF-8 file name */
28893);
28894
28895/*
28896** The following variable is (normally) set once and never changes
28897** thereafter.  It records whether the operating system is Win95
28898** or WinNT.
28899**
28900** 0:   Operating system unknown.
28901** 1:   Operating system is Win95.
28902** 2:   Operating system is WinNT.
28903**
28904** In order to facilitate testing on a WinNT system, the test fixture
28905** can manually set this value to 1 to emulate Win98 behavior.
28906*/
28907#ifdef SQLITE_TEST
28908SQLITE_API int sqlite3_os_type = 0;
28909#else
28910static int sqlite3_os_type = 0;
28911#endif
28912
28913/*
28914** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
28915** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
28916**
28917** Here is an interesting observation:  Win95, Win98, and WinME lack
28918** the LockFileEx() API.  But we can still statically link against that
28919** API as long as we don't call it when running Win95/98/ME.  A call to
28920** this routine is used to determine if the host is Win95/98/ME or
28921** WinNT/2K/XP so that we will know whether or not we can safely call
28922** the LockFileEx() API.
28923*/
28924#if SQLITE_OS_WINCE
28925# define isNT()  (1)
28926#else
28927  static int isNT(void){
28928    if( sqlite3_os_type==0 ){
28929      OSVERSIONINFO sInfo;
28930      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
28931      GetVersionEx(&sInfo);
28932      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
28933    }
28934    return sqlite3_os_type==2;
28935  }
28936#endif /* SQLITE_OS_WINCE */
28937
28938/*
28939** Convert a UTF-8 string to microsoft unicode (UTF-16?).
28940**
28941** Space to hold the returned string is obtained from malloc.
28942*/
28943static WCHAR *utf8ToUnicode(const char *zFilename){
28944  int nChar;
28945  WCHAR *zWideFilename;
28946
28947  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
28948  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
28949  if( zWideFilename==0 ){
28950    return 0;
28951  }
28952  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
28953  if( nChar==0 ){
28954    free(zWideFilename);
28955    zWideFilename = 0;
28956  }
28957  return zWideFilename;
28958}
28959
28960/*
28961** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
28962** obtained from malloc().
28963*/
28964static char *unicodeToUtf8(const WCHAR *zWideFilename){
28965  int nByte;
28966  char *zFilename;
28967
28968  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
28969  zFilename = malloc( nByte );
28970  if( zFilename==0 ){
28971    return 0;
28972  }
28973  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
28974                              0, 0);
28975  if( nByte == 0 ){
28976    free(zFilename);
28977    zFilename = 0;
28978  }
28979  return zFilename;
28980}
28981
28982/*
28983** Convert an ansi string to microsoft unicode, based on the
28984** current codepage settings for file apis.
28985**
28986** Space to hold the returned string is obtained
28987** from malloc.
28988*/
28989static WCHAR *mbcsToUnicode(const char *zFilename){
28990  int nByte;
28991  WCHAR *zMbcsFilename;
28992  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
28993
28994  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
28995  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
28996  if( zMbcsFilename==0 ){
28997    return 0;
28998  }
28999  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29000  if( nByte==0 ){
29001    free(zMbcsFilename);
29002    zMbcsFilename = 0;
29003  }
29004  return zMbcsFilename;
29005}
29006
29007/*
29008** Convert microsoft unicode to multibyte character string, based on the
29009** user's Ansi codepage.
29010**
29011** Space to hold the returned string is obtained from
29012** malloc().
29013*/
29014static char *unicodeToMbcs(const WCHAR *zWideFilename){
29015  int nByte;
29016  char *zFilename;
29017  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29018
29019  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29020  zFilename = malloc( nByte );
29021  if( zFilename==0 ){
29022    return 0;
29023  }
29024  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29025                              0, 0);
29026  if( nByte == 0 ){
29027    free(zFilename);
29028    zFilename = 0;
29029  }
29030  return zFilename;
29031}
29032
29033/*
29034** Convert multibyte character string to UTF-8.  Space to hold the
29035** returned string is obtained from malloc().
29036*/
29037SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29038  char *zFilenameUtf8;
29039  WCHAR *zTmpWide;
29040
29041  zTmpWide = mbcsToUnicode(zFilename);
29042  if( zTmpWide==0 ){
29043    return 0;
29044  }
29045  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29046  free(zTmpWide);
29047  return zFilenameUtf8;
29048}
29049
29050/*
29051** Convert UTF-8 to multibyte character string.  Space to hold the
29052** returned string is obtained from malloc().
29053*/
29054static char *utf8ToMbcs(const char *zFilename){
29055  char *zFilenameMbcs;
29056  WCHAR *zTmpWide;
29057
29058  zTmpWide = utf8ToUnicode(zFilename);
29059  if( zTmpWide==0 ){
29060    return 0;
29061  }
29062  zFilenameMbcs = unicodeToMbcs(zTmpWide);
29063  free(zTmpWide);
29064  return zFilenameMbcs;
29065}
29066
29067#if SQLITE_OS_WINCE
29068/*************************************************************************
29069** This section contains code for WinCE only.
29070*/
29071/*
29072** WindowsCE does not have a localtime() function.  So create a
29073** substitute.
29074*/
29075struct tm *__cdecl localtime(const time_t *t)
29076{
29077  static struct tm y;
29078  FILETIME uTm, lTm;
29079  SYSTEMTIME pTm;
29080  sqlite3_int64 t64;
29081  t64 = *t;
29082  t64 = (t64 + 11644473600)*10000000;
29083  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29084  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29085  FileTimeToLocalFileTime(&uTm,&lTm);
29086  FileTimeToSystemTime(&lTm,&pTm);
29087  y.tm_year = pTm.wYear - 1900;
29088  y.tm_mon = pTm.wMonth - 1;
29089  y.tm_wday = pTm.wDayOfWeek;
29090  y.tm_mday = pTm.wDay;
29091  y.tm_hour = pTm.wHour;
29092  y.tm_min = pTm.wMinute;
29093  y.tm_sec = pTm.wSecond;
29094  return &y;
29095}
29096
29097/* This will never be called, but defined to make the code compile */
29098#define GetTempPathA(a,b)
29099
29100#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29101#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29102#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29103
29104#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29105
29106/*
29107** Acquire a lock on the handle h
29108*/
29109static void winceMutexAcquire(HANDLE h){
29110   DWORD dwErr;
29111   do {
29112     dwErr = WaitForSingleObject(h, INFINITE);
29113   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29114}
29115/*
29116** Release a lock acquired by winceMutexAcquire()
29117*/
29118#define winceMutexRelease(h) ReleaseMutex(h)
29119
29120/*
29121** Create the mutex and shared memory used for locking in the file
29122** descriptor pFile
29123*/
29124static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29125  WCHAR *zTok;
29126  WCHAR *zName = utf8ToUnicode(zFilename);
29127  BOOL bInit = TRUE;
29128
29129  /* Initialize the local lockdata */
29130  ZeroMemory(&pFile->local, sizeof(pFile->local));
29131
29132  /* Replace the backslashes from the filename and lowercase it
29133  ** to derive a mutex name. */
29134  zTok = CharLowerW(zName);
29135  for (;*zTok;zTok++){
29136    if (*zTok == '\\') *zTok = '_';
29137  }
29138
29139  /* Create/open the named mutex */
29140  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29141  if (!pFile->hMutex){
29142    pFile->lastErrno = GetLastError();
29143    free(zName);
29144    return FALSE;
29145  }
29146
29147  /* Acquire the mutex before continuing */
29148  winceMutexAcquire(pFile->hMutex);
29149
29150  /* Since the names of named mutexes, semaphores, file mappings etc are
29151  ** case-sensitive, take advantage of that by uppercasing the mutex name
29152  ** and using that as the shared filemapping name.
29153  */
29154  CharUpperW(zName);
29155  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29156                                       PAGE_READWRITE, 0, sizeof(winceLock),
29157                                       zName);
29158
29159  /* Set a flag that indicates we're the first to create the memory so it
29160  ** must be zero-initialized */
29161  if (GetLastError() == ERROR_ALREADY_EXISTS){
29162    bInit = FALSE;
29163  }
29164
29165  free(zName);
29166
29167  /* If we succeeded in making the shared memory handle, map it. */
29168  if (pFile->hShared){
29169    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
29170             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29171    /* If mapping failed, close the shared memory handle and erase it */
29172    if (!pFile->shared){
29173      pFile->lastErrno = GetLastError();
29174      CloseHandle(pFile->hShared);
29175      pFile->hShared = NULL;
29176    }
29177  }
29178
29179  /* If shared memory could not be created, then close the mutex and fail */
29180  if (pFile->hShared == NULL){
29181    winceMutexRelease(pFile->hMutex);
29182    CloseHandle(pFile->hMutex);
29183    pFile->hMutex = NULL;
29184    return FALSE;
29185  }
29186
29187  /* Initialize the shared memory if we're supposed to */
29188  if (bInit) {
29189    ZeroMemory(pFile->shared, sizeof(winceLock));
29190  }
29191
29192  winceMutexRelease(pFile->hMutex);
29193  return TRUE;
29194}
29195
29196/*
29197** Destroy the part of winFile that deals with wince locks
29198*/
29199static void winceDestroyLock(winFile *pFile){
29200  if (pFile->hMutex){
29201    /* Acquire the mutex */
29202    winceMutexAcquire(pFile->hMutex);
29203
29204    /* The following blocks should probably assert in debug mode, but they
29205       are to cleanup in case any locks remained open */
29206    if (pFile->local.nReaders){
29207      pFile->shared->nReaders --;
29208    }
29209    if (pFile->local.bReserved){
29210      pFile->shared->bReserved = FALSE;
29211    }
29212    if (pFile->local.bPending){
29213      pFile->shared->bPending = FALSE;
29214    }
29215    if (pFile->local.bExclusive){
29216      pFile->shared->bExclusive = FALSE;
29217    }
29218
29219    /* De-reference and close our copy of the shared memory handle */
29220    UnmapViewOfFile(pFile->shared);
29221    CloseHandle(pFile->hShared);
29222
29223    /* Done with the mutex */
29224    winceMutexRelease(pFile->hMutex);
29225    CloseHandle(pFile->hMutex);
29226    pFile->hMutex = NULL;
29227  }
29228}
29229
29230/*
29231** An implementation of the LockFile() API of windows for wince
29232*/
29233static BOOL winceLockFile(
29234  HANDLE *phFile,
29235  DWORD dwFileOffsetLow,
29236  DWORD dwFileOffsetHigh,
29237  DWORD nNumberOfBytesToLockLow,
29238  DWORD nNumberOfBytesToLockHigh
29239){
29240  winFile *pFile = HANDLE_TO_WINFILE(phFile);
29241  BOOL bReturn = FALSE;
29242
29243  UNUSED_PARAMETER(dwFileOffsetHigh);
29244  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29245
29246  if (!pFile->hMutex) return TRUE;
29247  winceMutexAcquire(pFile->hMutex);
29248
29249  /* Wanting an exclusive lock? */
29250  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
29251       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29252    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
29253       pFile->shared->bExclusive = TRUE;
29254       pFile->local.bExclusive = TRUE;
29255       bReturn = TRUE;
29256    }
29257  }
29258
29259  /* Want a read-only lock? */
29260  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
29261           nNumberOfBytesToLockLow == 1){
29262    if (pFile->shared->bExclusive == 0){
29263      pFile->local.nReaders ++;
29264      if (pFile->local.nReaders == 1){
29265        pFile->shared->nReaders ++;
29266      }
29267      bReturn = TRUE;
29268    }
29269  }
29270
29271  /* Want a pending lock? */
29272  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
29273    /* If no pending lock has been acquired, then acquire it */
29274    if (pFile->shared->bPending == 0) {
29275      pFile->shared->bPending = TRUE;
29276      pFile->local.bPending = TRUE;
29277      bReturn = TRUE;
29278    }
29279  }
29280
29281  /* Want a reserved lock? */
29282  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
29283    if (pFile->shared->bReserved == 0) {
29284      pFile->shared->bReserved = TRUE;
29285      pFile->local.bReserved = TRUE;
29286      bReturn = TRUE;
29287    }
29288  }
29289
29290  winceMutexRelease(pFile->hMutex);
29291  return bReturn;
29292}
29293
29294/*
29295** An implementation of the UnlockFile API of windows for wince
29296*/
29297static BOOL winceUnlockFile(
29298  HANDLE *phFile,
29299  DWORD dwFileOffsetLow,
29300  DWORD dwFileOffsetHigh,
29301  DWORD nNumberOfBytesToUnlockLow,
29302  DWORD nNumberOfBytesToUnlockHigh
29303){
29304  winFile *pFile = HANDLE_TO_WINFILE(phFile);
29305  BOOL bReturn = FALSE;
29306
29307  UNUSED_PARAMETER(dwFileOffsetHigh);
29308  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
29309
29310  if (!pFile->hMutex) return TRUE;
29311  winceMutexAcquire(pFile->hMutex);
29312
29313  /* Releasing a reader lock or an exclusive lock */
29314  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
29315    /* Did we have an exclusive lock? */
29316    if (pFile->local.bExclusive){
29317      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
29318      pFile->local.bExclusive = FALSE;
29319      pFile->shared->bExclusive = FALSE;
29320      bReturn = TRUE;
29321    }
29322
29323    /* Did we just have a reader lock? */
29324    else if (pFile->local.nReaders){
29325      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
29326      pFile->local.nReaders --;
29327      if (pFile->local.nReaders == 0)
29328      {
29329        pFile->shared->nReaders --;
29330      }
29331      bReturn = TRUE;
29332    }
29333  }
29334
29335  /* Releasing a pending lock */
29336  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
29337    if (pFile->local.bPending){
29338      pFile->local.bPending = FALSE;
29339      pFile->shared->bPending = FALSE;
29340      bReturn = TRUE;
29341    }
29342  }
29343  /* Releasing a reserved lock */
29344  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
29345    if (pFile->local.bReserved) {
29346      pFile->local.bReserved = FALSE;
29347      pFile->shared->bReserved = FALSE;
29348      bReturn = TRUE;
29349    }
29350  }
29351
29352  winceMutexRelease(pFile->hMutex);
29353  return bReturn;
29354}
29355
29356/*
29357** An implementation of the LockFileEx() API of windows for wince
29358*/
29359static BOOL winceLockFileEx(
29360  HANDLE *phFile,
29361  DWORD dwFlags,
29362  DWORD dwReserved,
29363  DWORD nNumberOfBytesToLockLow,
29364  DWORD nNumberOfBytesToLockHigh,
29365  LPOVERLAPPED lpOverlapped
29366){
29367  UNUSED_PARAMETER(dwReserved);
29368  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29369
29370  /* If the caller wants a shared read lock, forward this call
29371  ** to winceLockFile */
29372  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
29373      dwFlags == 1 &&
29374      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29375    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
29376  }
29377  return FALSE;
29378}
29379/*
29380** End of the special code for wince
29381*****************************************************************************/
29382#endif /* SQLITE_OS_WINCE */
29383
29384/*****************************************************************************
29385** The next group of routines implement the I/O methods specified
29386** by the sqlite3_io_methods object.
29387******************************************************************************/
29388
29389/*
29390** Close a file.
29391**
29392** It is reported that an attempt to close a handle might sometimes
29393** fail.  This is a very unreasonable result, but windows is notorious
29394** for being unreasonable so I do not doubt that it might happen.  If
29395** the close fails, we pause for 100 milliseconds and try again.  As
29396** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
29397** giving up and returning an error.
29398*/
29399#define MX_CLOSE_ATTEMPT 3
29400static int winClose(sqlite3_file *id){
29401  int rc, cnt = 0;
29402  winFile *pFile = (winFile*)id;
29403
29404  assert( id!=0 );
29405  assert( pFile->pShm==0 );
29406  OSTRACE(("CLOSE %d\n", pFile->h));
29407  do{
29408    rc = CloseHandle(pFile->h);
29409  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
29410#if SQLITE_OS_WINCE
29411#define WINCE_DELETION_ATTEMPTS 3
29412  winceDestroyLock(pFile);
29413  if( pFile->zDeleteOnClose ){
29414    int cnt = 0;
29415    while(
29416           DeleteFileW(pFile->zDeleteOnClose)==0
29417        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
29418        && cnt++ < WINCE_DELETION_ATTEMPTS
29419    ){
29420       Sleep(100);  /* Wait a little before trying again */
29421    }
29422    free(pFile->zDeleteOnClose);
29423  }
29424#endif
29425  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
29426  OpenCounter(-1);
29427  return rc ? SQLITE_OK : SQLITE_IOERR;
29428}
29429
29430/*
29431** Some microsoft compilers lack this definition.
29432*/
29433#ifndef INVALID_SET_FILE_POINTER
29434# define INVALID_SET_FILE_POINTER ((DWORD)-1)
29435#endif
29436
29437/*
29438** Read data from a file into a buffer.  Return SQLITE_OK if all
29439** bytes were read successfully and SQLITE_IOERR if anything goes
29440** wrong.
29441*/
29442static int winRead(
29443  sqlite3_file *id,          /* File to read from */
29444  void *pBuf,                /* Write content into this buffer */
29445  int amt,                   /* Number of bytes to read */
29446  sqlite3_int64 offset       /* Begin reading at this offset */
29447){
29448  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29449  LONG lowerBits = (LONG)(offset & 0xffffffff);
29450  DWORD rc;
29451  winFile *pFile = (winFile*)id;
29452  DWORD error;
29453  DWORD got;
29454
29455  assert( id!=0 );
29456  SimulateIOError(return SQLITE_IOERR_READ);
29457  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
29458  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29459  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29460    pFile->lastErrno = error;
29461    return SQLITE_FULL;
29462  }
29463  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
29464    pFile->lastErrno = GetLastError();
29465    return SQLITE_IOERR_READ;
29466  }
29467  if( got==(DWORD)amt ){
29468    return SQLITE_OK;
29469  }else{
29470    /* Unread parts of the buffer must be zero-filled */
29471    memset(&((char*)pBuf)[got], 0, amt-got);
29472    return SQLITE_IOERR_SHORT_READ;
29473  }
29474}
29475
29476/*
29477** Write data from a buffer into a file.  Return SQLITE_OK on success
29478** or some other error code on failure.
29479*/
29480static int winWrite(
29481  sqlite3_file *id,         /* File to write into */
29482  const void *pBuf,         /* The bytes to be written */
29483  int amt,                  /* Number of bytes to write */
29484  sqlite3_int64 offset      /* Offset into the file to begin writing at */
29485){
29486  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29487  LONG lowerBits = (LONG)(offset & 0xffffffff);
29488  DWORD rc;
29489  winFile *pFile = (winFile*)id;
29490  DWORD error;
29491  DWORD wrote = 0;
29492
29493  assert( id!=0 );
29494  SimulateIOError(return SQLITE_IOERR_WRITE);
29495  SimulateDiskfullError(return SQLITE_FULL);
29496  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
29497  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29498  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29499    pFile->lastErrno = error;
29500    return SQLITE_FULL;
29501  }
29502  assert( amt>0 );
29503  while(
29504     amt>0
29505     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
29506     && wrote>0
29507  ){
29508    amt -= wrote;
29509    pBuf = &((char*)pBuf)[wrote];
29510  }
29511  if( !rc || amt>(int)wrote ){
29512    pFile->lastErrno = GetLastError();
29513    return SQLITE_FULL;
29514  }
29515  return SQLITE_OK;
29516}
29517
29518/*
29519** Truncate an open file to a specified size
29520*/
29521static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
29522  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
29523  LONG lowerBits = (LONG)(nByte & 0xffffffff);
29524  DWORD dwRet;
29525  winFile *pFile = (winFile*)id;
29526  DWORD error;
29527  int rc = SQLITE_OK;
29528
29529  assert( id!=0 );
29530  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
29531  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
29532  dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29533  if( dwRet==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29534    pFile->lastErrno = error;
29535    rc = SQLITE_IOERR_TRUNCATE;
29536  /* SetEndOfFile will fail if nByte is negative */
29537  }else if( !SetEndOfFile(pFile->h) ){
29538    pFile->lastErrno = GetLastError();
29539    rc = SQLITE_IOERR_TRUNCATE;
29540  }
29541  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc==SQLITE_OK ? "ok" : "failed"));
29542  return rc;
29543}
29544
29545#ifdef SQLITE_TEST
29546/*
29547** Count the number of fullsyncs and normal syncs.  This is used to test
29548** that syncs and fullsyncs are occuring at the right times.
29549*/
29550SQLITE_API int sqlite3_sync_count = 0;
29551SQLITE_API int sqlite3_fullsync_count = 0;
29552#endif
29553
29554/*
29555** Make sure all writes to a particular file are committed to disk.
29556*/
29557static int winSync(sqlite3_file *id, int flags){
29558#ifndef SQLITE_NO_SYNC
29559  winFile *pFile = (winFile*)id;
29560
29561  assert( id!=0 );
29562  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
29563#else
29564  UNUSED_PARAMETER(id);
29565#endif
29566#ifndef SQLITE_TEST
29567  UNUSED_PARAMETER(flags);
29568#else
29569  if( flags & SQLITE_SYNC_FULL ){
29570    sqlite3_fullsync_count++;
29571  }
29572  sqlite3_sync_count++;
29573#endif
29574  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
29575  ** no-op
29576  */
29577#ifdef SQLITE_NO_SYNC
29578    return SQLITE_OK;
29579#else
29580  if( FlushFileBuffers(pFile->h) ){
29581    return SQLITE_OK;
29582  }else{
29583    pFile->lastErrno = GetLastError();
29584    return SQLITE_IOERR;
29585  }
29586#endif
29587}
29588
29589/*
29590** Determine the current size of a file in bytes
29591*/
29592static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
29593  DWORD upperBits;
29594  DWORD lowerBits;
29595  winFile *pFile = (winFile*)id;
29596  DWORD error;
29597
29598  assert( id!=0 );
29599  SimulateIOError(return SQLITE_IOERR_FSTAT);
29600  lowerBits = GetFileSize(pFile->h, &upperBits);
29601  if(   (lowerBits == INVALID_FILE_SIZE)
29602     && ((error = GetLastError()) != NO_ERROR) )
29603  {
29604    pFile->lastErrno = error;
29605    return SQLITE_IOERR_FSTAT;
29606  }
29607  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
29608  return SQLITE_OK;
29609}
29610
29611/*
29612** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
29613*/
29614#ifndef LOCKFILE_FAIL_IMMEDIATELY
29615# define LOCKFILE_FAIL_IMMEDIATELY 1
29616#endif
29617
29618/*
29619** Acquire a reader lock.
29620** Different API routines are called depending on whether or not this
29621** is Win95 or WinNT.
29622*/
29623static int getReadLock(winFile *pFile){
29624  int res;
29625  if( isNT() ){
29626    OVERLAPPED ovlp;
29627    ovlp.Offset = SHARED_FIRST;
29628    ovlp.OffsetHigh = 0;
29629    ovlp.hEvent = 0;
29630    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
29631                     0, SHARED_SIZE, 0, &ovlp);
29632/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
29633*/
29634#if SQLITE_OS_WINCE==0
29635  }else{
29636    int lk;
29637    sqlite3_randomness(sizeof(lk), &lk);
29638    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
29639    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
29640#endif
29641  }
29642  if( res == 0 ){
29643    pFile->lastErrno = GetLastError();
29644  }
29645  return res;
29646}
29647
29648/*
29649** Undo a readlock
29650*/
29651static int unlockReadLock(winFile *pFile){
29652  int res;
29653  if( isNT() ){
29654    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29655/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
29656*/
29657#if SQLITE_OS_WINCE==0
29658  }else{
29659    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
29660#endif
29661  }
29662  if( res == 0 ){
29663    pFile->lastErrno = GetLastError();
29664  }
29665  return res;
29666}
29667
29668/*
29669** Lock the file with the lock specified by parameter locktype - one
29670** of the following:
29671**
29672**     (1) SHARED_LOCK
29673**     (2) RESERVED_LOCK
29674**     (3) PENDING_LOCK
29675**     (4) EXCLUSIVE_LOCK
29676**
29677** Sometimes when requesting one lock state, additional lock states
29678** are inserted in between.  The locking might fail on one of the later
29679** transitions leaving the lock state different from what it started but
29680** still short of its goal.  The following chart shows the allowed
29681** transitions and the inserted intermediate states:
29682**
29683**    UNLOCKED -> SHARED
29684**    SHARED -> RESERVED
29685**    SHARED -> (PENDING) -> EXCLUSIVE
29686**    RESERVED -> (PENDING) -> EXCLUSIVE
29687**    PENDING -> EXCLUSIVE
29688**
29689** This routine will only increase a lock.  The winUnlock() routine
29690** erases all locks at once and returns us immediately to locking level 0.
29691** It is not possible to lower the locking level one step at a time.  You
29692** must go straight to locking level 0.
29693*/
29694static int winLock(sqlite3_file *id, int locktype){
29695  int rc = SQLITE_OK;    /* Return code from subroutines */
29696  int res = 1;           /* Result of a windows lock call */
29697  int newLocktype;       /* Set pFile->locktype to this value before exiting */
29698  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
29699  winFile *pFile = (winFile*)id;
29700  DWORD error = NO_ERROR;
29701
29702  assert( id!=0 );
29703  OSTRACE(("LOCK %d %d was %d(%d)\n",
29704           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
29705
29706  /* If there is already a lock of this type or more restrictive on the
29707  ** OsFile, do nothing. Don't use the end_lock: exit path, as
29708  ** sqlite3OsEnterMutex() hasn't been called yet.
29709  */
29710  if( pFile->locktype>=locktype ){
29711    return SQLITE_OK;
29712  }
29713
29714  /* Make sure the locking sequence is correct
29715  */
29716  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
29717  assert( locktype!=PENDING_LOCK );
29718  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
29719
29720  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
29721  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
29722  ** the PENDING_LOCK byte is temporary.
29723  */
29724  newLocktype = pFile->locktype;
29725  if(   (pFile->locktype==NO_LOCK)
29726     || (   (locktype==EXCLUSIVE_LOCK)
29727         && (pFile->locktype==RESERVED_LOCK))
29728  ){
29729    int cnt = 3;
29730    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
29731      /* Try 3 times to get the pending lock.  The pending lock might be
29732      ** held by another reader process who will release it momentarily.
29733      */
29734      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
29735      Sleep(1);
29736    }
29737    gotPendingLock = res;
29738    if( !res ){
29739      error = GetLastError();
29740    }
29741  }
29742
29743  /* Acquire a shared lock
29744  */
29745  if( locktype==SHARED_LOCK && res ){
29746    assert( pFile->locktype==NO_LOCK );
29747    res = getReadLock(pFile);
29748    if( res ){
29749      newLocktype = SHARED_LOCK;
29750    }else{
29751      error = GetLastError();
29752    }
29753  }
29754
29755  /* Acquire a RESERVED lock
29756  */
29757  if( locktype==RESERVED_LOCK && res ){
29758    assert( pFile->locktype==SHARED_LOCK );
29759    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29760    if( res ){
29761      newLocktype = RESERVED_LOCK;
29762    }else{
29763      error = GetLastError();
29764    }
29765  }
29766
29767  /* Acquire a PENDING lock
29768  */
29769  if( locktype==EXCLUSIVE_LOCK && res ){
29770    newLocktype = PENDING_LOCK;
29771    gotPendingLock = 0;
29772  }
29773
29774  /* Acquire an EXCLUSIVE lock
29775  */
29776  if( locktype==EXCLUSIVE_LOCK && res ){
29777    assert( pFile->locktype>=SHARED_LOCK );
29778    res = unlockReadLock(pFile);
29779    OSTRACE(("unreadlock = %d\n", res));
29780    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29781    if( res ){
29782      newLocktype = EXCLUSIVE_LOCK;
29783    }else{
29784      error = GetLastError();
29785      OSTRACE(("error-code = %d\n", error));
29786      getReadLock(pFile);
29787    }
29788  }
29789
29790  /* If we are holding a PENDING lock that ought to be released, then
29791  ** release it now.
29792  */
29793  if( gotPendingLock && locktype==SHARED_LOCK ){
29794    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29795  }
29796
29797  /* Update the state of the lock has held in the file descriptor then
29798  ** return the appropriate result code.
29799  */
29800  if( res ){
29801    rc = SQLITE_OK;
29802  }else{
29803    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
29804           locktype, newLocktype));
29805    pFile->lastErrno = error;
29806    rc = SQLITE_BUSY;
29807  }
29808  pFile->locktype = (u8)newLocktype;
29809  return rc;
29810}
29811
29812/*
29813** This routine checks if there is a RESERVED lock held on the specified
29814** file by this or any other process. If such a lock is held, return
29815** non-zero, otherwise zero.
29816*/
29817static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
29818  int rc;
29819  winFile *pFile = (winFile*)id;
29820
29821  assert( id!=0 );
29822  if( pFile->locktype>=RESERVED_LOCK ){
29823    rc = 1;
29824    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
29825  }else{
29826    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29827    if( rc ){
29828      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29829    }
29830    rc = !rc;
29831    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
29832  }
29833  *pResOut = rc;
29834  return SQLITE_OK;
29835}
29836
29837/*
29838** Lower the locking level on file descriptor id to locktype.  locktype
29839** must be either NO_LOCK or SHARED_LOCK.
29840**
29841** If the locking level of the file descriptor is already at or below
29842** the requested locking level, this routine is a no-op.
29843**
29844** It is not possible for this routine to fail if the second argument
29845** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
29846** might return SQLITE_IOERR;
29847*/
29848static int winUnlock(sqlite3_file *id, int locktype){
29849  int type;
29850  winFile *pFile = (winFile*)id;
29851  int rc = SQLITE_OK;
29852  assert( pFile!=0 );
29853  assert( locktype<=SHARED_LOCK );
29854  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
29855          pFile->locktype, pFile->sharedLockByte));
29856  type = pFile->locktype;
29857  if( type>=EXCLUSIVE_LOCK ){
29858    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29859    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
29860      /* This should never happen.  We should always be able to
29861      ** reacquire the read lock */
29862      rc = SQLITE_IOERR_UNLOCK;
29863    }
29864  }
29865  if( type>=RESERVED_LOCK ){
29866    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29867  }
29868  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
29869    unlockReadLock(pFile);
29870  }
29871  if( type>=PENDING_LOCK ){
29872    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29873  }
29874  pFile->locktype = (u8)locktype;
29875  return rc;
29876}
29877
29878/*
29879** Control and query of the open file handle.
29880*/
29881static int winFileControl(sqlite3_file *id, int op, void *pArg){
29882  switch( op ){
29883    case SQLITE_FCNTL_LOCKSTATE: {
29884      *(int*)pArg = ((winFile*)id)->locktype;
29885      return SQLITE_OK;
29886    }
29887    case SQLITE_LAST_ERRNO: {
29888      *(int*)pArg = (int)((winFile*)id)->lastErrno;
29889      return SQLITE_OK;
29890    }
29891    case SQLITE_FCNTL_SIZE_HINT: {
29892      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
29893      winTruncate(id, sz);
29894      return SQLITE_OK;
29895    }
29896  }
29897  return SQLITE_ERROR;
29898}
29899
29900/*
29901** Return the sector size in bytes of the underlying block device for
29902** the specified file. This is almost always 512 bytes, but may be
29903** larger for some devices.
29904**
29905** SQLite code assumes this function cannot fail. It also assumes that
29906** if two files are created in the same file-system directory (i.e.
29907** a database and its journal file) that the sector size will be the
29908** same for both.
29909*/
29910static int winSectorSize(sqlite3_file *id){
29911  assert( id!=0 );
29912  return (int)(((winFile*)id)->sectorSize);
29913}
29914
29915/*
29916** Return a vector of device characteristics.
29917*/
29918static int winDeviceCharacteristics(sqlite3_file *id){
29919  UNUSED_PARAMETER(id);
29920  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
29921}
29922
29923/****************************************************************************
29924********************************* Shared Memory *****************************
29925**
29926** The next subdivision of code manages the shared-memory primitives.
29927*/
29928#ifndef SQLITE_OMIT_WAL
29929
29930/*
29931** Helper functions to obtain and relinquish the global mutex. The
29932** global mutex is used to protect the winLockInfo objects used by
29933** this file, all of which may be shared by multiple threads.
29934**
29935** Function winShmMutexHeld() is used to assert() that the global mutex
29936** is held when required. This function is only used as part of assert()
29937** statements. e.g.
29938**
29939**   winShmEnterMutex()
29940**     assert( winShmMutexHeld() );
29941**   winEnterLeave()
29942*/
29943static void winShmEnterMutex(void){
29944  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
29945}
29946static void winShmLeaveMutex(void){
29947  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
29948}
29949#ifdef SQLITE_DEBUG
29950static int winShmMutexHeld(void) {
29951  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
29952}
29953#endif
29954
29955/*
29956** Object used to represent a single file opened and mmapped to provide
29957** shared memory.  When multiple threads all reference the same
29958** log-summary, each thread has its own winFile object, but they all
29959** point to a single instance of this object.  In other words, each
29960** log-summary is opened only once per process.
29961**
29962** winShmMutexHeld() must be true when creating or destroying
29963** this object or while reading or writing the following fields:
29964**
29965**      nRef
29966**      pNext
29967**
29968** The following fields are read-only after the object is created:
29969**
29970**      fid
29971**      zFilename
29972**
29973** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
29974** winShmMutexHeld() is true when reading or writing any other field
29975** in this structure.
29976**
29977** To avoid deadlocks, mutex and mutexBuf are always released in the
29978** reverse order that they are acquired.  mutexBuf is always acquired
29979** first and released last.  This invariant is check by asserting
29980** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
29981** released.
29982*/
29983struct winShmNode {
29984  sqlite3_mutex *mutex;      /* Mutex to access this object */
29985  char *zFilename;           /* Name of the file */
29986  winFile hFile;             /* File handle from winOpen */
29987
29988  int szRegion;              /* Size of shared-memory regions */
29989  int nRegion;               /* Size of array apRegion */
29990  struct ShmRegion {
29991    HANDLE hMap;             /* File handle from CreateFileMapping */
29992    void *pMap;
29993  } *aRegion;
29994  DWORD lastErrno;           /* The Windows errno from the last I/O error */
29995
29996  int nRef;                  /* Number of winShm objects pointing to this */
29997  winShm *pFirst;            /* All winShm objects pointing to this */
29998  winShmNode *pNext;         /* Next in list of all winShmNode objects */
29999#ifdef SQLITE_DEBUG
30000  u8 nextShmId;              /* Next available winShm.id value */
30001#endif
30002};
30003
30004/*
30005** A global array of all winShmNode objects.
30006**
30007** The winShmMutexHeld() must be true while reading or writing this list.
30008*/
30009static winShmNode *winShmNodeList = 0;
30010
30011/*
30012** Structure used internally by this VFS to record the state of an
30013** open shared memory connection.
30014**
30015** winShm.pFile->mutex must be held while reading or writing the
30016** winShm.pNext and winShm.locks[] elements.
30017**
30018** The winShm.pFile element is initialized when the object is created
30019** and is read-only thereafter.
30020*/
30021struct winShm {
30022  winShmNode *pShmNode;      /* The underlying winShmNode object */
30023  winShm *pNext;             /* Next winShm with the same winShmNode */
30024  u8 hasMutex;               /* True if holding the winShmNode mutex */
30025  u8 hasMutexBuf;            /* True if holding pFile->mutexBuf */
30026#ifdef SQLITE_DEBUG
30027  u8 id;                     /* Id of this connection with its winShmNode */
30028#endif
30029};
30030
30031/*
30032** Constants used for locking
30033*/
30034#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30035#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30036
30037/*
30038** Apply advisory locks for all n bytes beginning at ofst.
30039*/
30040#define _SHM_UNLCK  1
30041#define _SHM_RDLCK  2
30042#define _SHM_WRLCK  3
30043static int winShmSystemLock(
30044  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30045  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30046  int ofst,             /* Offset to first byte to be locked/unlocked */
30047  int nByte             /* Number of bytes to lock or unlock */
30048){
30049  OVERLAPPED ovlp;
30050  DWORD dwFlags;
30051  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30052
30053  /* Access to the winShmNode object is serialized by the caller */
30054  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30055
30056  /* Initialize the locking parameters */
30057  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30058  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30059
30060  /* Find the first bit in lockMask that is set */
30061  memset(&ovlp, 0, sizeof(OVERLAPPED));
30062  ovlp.Offset = ofst;
30063
30064  /* Release/Acquire the system-level lock */
30065  if( lockType==_SHM_UNLCK ){
30066    rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30067  }else{
30068    rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30069  }
30070  if( !rc ){
30071    OSTRACE(("SHM-LOCK %d %s ERROR 0x%08lx\n",
30072             pFile->hFile.h,
30073             lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30074             GetLastError()));
30075  }
30076  rc = (rc!=0) ? SQLITE_OK : SQLITE_BUSY;
30077
30078  return rc;
30079}
30080
30081/* Forward references to VFS methods */
30082static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30083static int winDelete(sqlite3_vfs *,const char*,int);
30084
30085/*
30086** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30087**
30088** This is not a VFS shared-memory method; it is a utility function called
30089** by VFS shared-memory methods.
30090*/
30091static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30092  winShmNode **pp;
30093  winShmNode *p;
30094  assert( winShmMutexHeld() );
30095  pp = &winShmNodeList;
30096  while( (p = *pp)!=0 ){
30097    if( p->nRef==0 ){
30098      int i;
30099      if( p->mutex ) sqlite3_mutex_free(p->mutex);
30100      for(i=0; i<p->nRegion; i++){
30101        UnmapViewOfFile(p->aRegion[i].pMap);
30102        CloseHandle(p->aRegion[i].hMap);
30103      }
30104      if( p->hFile.h != INVALID_HANDLE_VALUE ) {
30105        winClose((sqlite3_file *)&p->hFile);
30106      }
30107      if( deleteFlag ) winDelete(pVfs, p->zFilename, 0);
30108      *pp = p->pNext;
30109      sqlite3_free(p->aRegion);
30110      sqlite3_free(p);
30111    }else{
30112      pp = &p->pNext;
30113    }
30114  }
30115}
30116
30117/*
30118** Open a shared-memory area.  This particular implementation uses
30119** mmapped files.
30120**
30121** zName is a filename used to identify the shared-memory area.  The
30122** implementation does not (and perhaps should not) use this name
30123** directly, but rather use it as a template for finding an appropriate
30124** name for the shared-memory storage.  In this implementation, the
30125** string "-index" is appended to zName and used as the name of the
30126** mmapped file.
30127**
30128** When opening a new shared-memory file, if no other instances of that
30129** file are currently open, in this process or in other processes, then
30130** the file must be truncated to zero length or have its header cleared.
30131*/
30132static int winShmOpen(
30133  sqlite3_file *fd      /* The file to which to attach shared memory */
30134){
30135  struct winFile *pDbFd;             /* Database to which to attach SHM */
30136  struct winShm *p;                  /* The connection to be opened */
30137  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30138  int rc;                            /* Result code */
30139  struct winShmNode *pNew;           /* Newly allocated winShmNode */
30140  int nName;                         /* Size of zName in bytes */
30141
30142  pDbFd = (winFile*)fd;
30143  assert( pDbFd->pShm==0 );    /* Not previously opened */
30144
30145  /* Allocate space for the new sqlite3_shm object.  Also speculatively
30146  ** allocate space for a new winShmNode and filename.
30147  */
30148  p = sqlite3_malloc( sizeof(*p) );
30149  if( p==0 ) return SQLITE_NOMEM;
30150  memset(p, 0, sizeof(*p));
30151  nName = sqlite3Strlen30(pDbFd->zPath);
30152  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30153  if( pNew==0 ){
30154    sqlite3_free(p);
30155    return SQLITE_NOMEM;
30156  }
30157  memset(pNew, 0, sizeof(*pNew));
30158  pNew->zFilename = (char*)&pNew[1];
30159  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30160
30161  /* Look to see if there is an existing winShmNode that can be used.
30162  ** If no matching winShmNode currently exists, create a new one.
30163  */
30164  winShmEnterMutex();
30165  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30166    /* TBD need to come up with better match here.  Perhaps
30167    ** use FILE_ID_BOTH_DIR_INFO Structure.
30168    */
30169    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30170  }
30171  if( pShmNode ){
30172    sqlite3_free(pNew);
30173  }else{
30174    pShmNode = pNew;
30175    pNew = 0;
30176    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30177    pShmNode->pNext = winShmNodeList;
30178    winShmNodeList = pShmNode;
30179
30180    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30181    if( pShmNode->mutex==0 ){
30182      rc = SQLITE_NOMEM;
30183      goto shm_open_err;
30184    }
30185    rc = winOpen(pDbFd->pVfs,
30186                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
30187                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30188                 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30189                 0);
30190    if( SQLITE_OK!=rc ){
30191      rc = SQLITE_CANTOPEN_BKPT;
30192      goto shm_open_err;
30193    }
30194
30195    /* Check to see if another process is holding the dead-man switch.
30196    ** If not, truncate the file to zero length.
30197    */
30198    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30199      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30200    }
30201    if( rc==SQLITE_OK ){
30202      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30203      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30204    }
30205    if( rc ) goto shm_open_err;
30206  }
30207
30208  /* Make the new connection a child of the winShmNode */
30209  p->pShmNode = pShmNode;
30210  p->pNext = pShmNode->pFirst;
30211#ifdef SQLITE_DEBUG
30212  p->id = pShmNode->nextShmId++;
30213#endif
30214  pShmNode->pFirst = p;
30215  pShmNode->nRef++;
30216  pDbFd->pShm = p;
30217  winShmLeaveMutex();
30218  return SQLITE_OK;
30219
30220  /* Jump here on any error */
30221shm_open_err:
30222  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30223  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30224  sqlite3_free(p);
30225  sqlite3_free(pNew);
30226  winShmLeaveMutex();
30227  return rc;
30228}
30229
30230/*
30231** Close a connection to shared-memory.  Delete the underlying
30232** storage if deleteFlag is true.
30233*/
30234static int winShmClose(
30235  sqlite3_file *fd,          /* Database holding shared memory */
30236  int deleteFlag             /* Delete after closing if true */
30237){
30238  winFile *pDbFd;       /* Database holding shared-memory */
30239  winShm *p;            /* The connection to be closed */
30240  winShmNode *pShmNode; /* The underlying shared-memory file */
30241  winShm **pp;          /* For looping over sibling connections */
30242
30243  pDbFd = (winFile*)fd;
30244  p = pDbFd->pShm;
30245  pShmNode = p->pShmNode;
30246
30247  /* Remove connection p from the set of connections associated
30248  ** with pShmNode */
30249  sqlite3_mutex_enter(pShmNode->mutex);
30250  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30251  *pp = p->pNext;
30252
30253  /* Free the connection p */
30254  sqlite3_free(p);
30255  pDbFd->pShm = 0;
30256  sqlite3_mutex_leave(pShmNode->mutex);
30257
30258  /* If pShmNode->nRef has reached 0, then close the underlying
30259  ** shared-memory file, too */
30260  winShmEnterMutex();
30261  assert( pShmNode->nRef>0 );
30262  pShmNode->nRef--;
30263  if( pShmNode->nRef==0 ){
30264    winShmPurge(pDbFd->pVfs, deleteFlag);
30265  }
30266  winShmLeaveMutex();
30267
30268  return SQLITE_OK;
30269}
30270
30271/*
30272** This function is called to obtain a pointer to region iRegion of the
30273** shared-memory associated with the database file fd. Shared-memory regions
30274** are numbered starting from zero. Each shared-memory region is szRegion
30275** bytes in size.
30276**
30277** If an error occurs, an error code is returned and *pp is set to NULL.
30278**
30279** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
30280** region has not been allocated (by any client, including one running in a
30281** separate process), then *pp is set to NULL and SQLITE_OK returned. If
30282** isWrite is non-zero and the requested shared-memory region has not yet
30283** been allocated, it is allocated by this function.
30284**
30285** If the shared-memory region has already been allocated or is allocated by
30286** this call as described above, then it is mapped into this processes
30287** address space (if it is not already), *pp is set to point to the mapped
30288** memory and SQLITE_OK returned.
30289*/
30290static int winShmMap(
30291  sqlite3_file *fd,               /* Handle open on database file */
30292  int iRegion,                    /* Region to retrieve */
30293  int szRegion,                   /* Size of regions */
30294  int isWrite,                    /* True to extend file if necessary */
30295  void volatile **pp              /* OUT: Mapped memory */
30296){
30297  winFile *pDbFd = (winFile*)fd;
30298  winShm *p = pDbFd->pShm;
30299  winShmNode *pShmNode = p->pShmNode;
30300  int rc = SQLITE_OK;
30301
30302  sqlite3_mutex_enter(pShmNode->mutex);
30303  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30304
30305  if( pShmNode->nRegion<=iRegion ){
30306    struct ShmRegion *apNew;           /* New aRegion[] array */
30307    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30308    sqlite3_int64 sz;                  /* Current size of wal-index file */
30309
30310    pShmNode->szRegion = szRegion;
30311
30312    /* The requested region is not mapped into this processes address space.
30313    ** Check to see if it has been allocated (i.e. if the wal-index file is
30314    ** large enough to contain the requested region).
30315    */
30316    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
30317    if( rc!=SQLITE_OK ){
30318      goto shmpage_out;
30319    }
30320
30321    if( sz<nByte ){
30322      /* The requested memory region does not exist. If isWrite is set to
30323      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
30324      **
30325      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
30326      ** the requested memory region.
30327      */
30328      if( !isWrite ) goto shmpage_out;
30329      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
30330      if( rc!=SQLITE_OK ){
30331        goto shmpage_out;
30332      }
30333    }
30334
30335    /* Map the requested memory region into this processes address space. */
30336    apNew = (struct ShmRegion *)sqlite3_realloc(
30337        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
30338    );
30339    if( !apNew ){
30340      rc = SQLITE_IOERR_NOMEM;
30341      goto shmpage_out;
30342    }
30343    pShmNode->aRegion = apNew;
30344
30345    while( pShmNode->nRegion<=iRegion ){
30346      HANDLE hMap;                /* file-mapping handle */
30347      void *pMap = 0;             /* Mapped memory region */
30348
30349      hMap = CreateFileMapping(pShmNode->hFile.h,
30350          NULL, PAGE_READWRITE, 0, nByte, NULL
30351      );
30352      if( hMap ){
30353        pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30354            0, 0, nByte
30355        );
30356      }
30357      if( !pMap ){
30358        pShmNode->lastErrno = GetLastError();
30359        rc = SQLITE_IOERR;
30360        if( hMap ) CloseHandle(hMap);
30361        goto shmpage_out;
30362      }
30363
30364      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
30365      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
30366      pShmNode->nRegion++;
30367    }
30368  }
30369
30370shmpage_out:
30371  if( pShmNode->nRegion>iRegion ){
30372    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30373    *pp = (void *)&p[iRegion*szRegion];
30374  }else{
30375    *pp = 0;
30376  }
30377  sqlite3_mutex_leave(pShmNode->mutex);
30378  return rc;
30379}
30380
30381/*
30382** Change the lock state for a shared-memory segment.
30383*/
30384static int winShmLock(
30385  sqlite3_file *fd,          /* Database file holding the shared memory */
30386  int ofst,                  /* First lock to acquire or release */
30387  int n,                     /* Number of locks to acquire or release */
30388  int flags                  /* What to do with the lock */
30389){
30390  winFile *pDbFd = (winFile*)fd;
30391  winShm *p = pDbFd->pShm;
30392  winShmNode *pShmNode = p->pShmNode;
30393  int rc = SQLITE_PROTOCOL;
30394
30395  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30396  assert( n>=1 );
30397  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30398       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30399       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30400       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30401  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30402
30403  sqlite3_mutex_enter(pShmNode->mutex);
30404  if( flags & SQLITE_SHM_UNLOCK ){
30405    rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
30406  }else if( flags & SQLITE_SHM_SHARED ){
30407    rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
30408  }else{
30409    rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
30410  }
30411  sqlite3_mutex_leave(pShmNode->mutex);
30412  OSTRACE(("SHM-LOCK shmid-%d, pid-%d %s\n",
30413           p->id, (int)GetCurrentProcessId(), rc ? "failed" : "ok"));
30414  return rc;
30415}
30416
30417/*
30418** Implement a memory barrier or memory fence on shared memory.
30419**
30420** All loads and stores begun before the barrier must complete before
30421** any load or store begun after the barrier.
30422*/
30423static void winShmBarrier(
30424  sqlite3_file *fd          /* Database holding the shared memory */
30425){
30426  /* MemoryBarrier(); // does not work -- do not know why not */
30427  winShmEnterMutex();
30428  winShmLeaveMutex();
30429}
30430
30431#else
30432# define winShmOpen    0
30433# define winShmMap     0
30434# define winShmLock    0
30435# define winShmBarrier 0
30436# define winShmClose   0
30437#endif /* #ifndef SQLITE_OMIT_WAL */
30438/*
30439***************************** End Shared Memory *****************************
30440****************************************************************************/
30441
30442/*
30443** This vector defines all the methods that can operate on an
30444** sqlite3_file for win32.
30445*/
30446static const sqlite3_io_methods winIoMethod = {
30447  2,                        /* iVersion */
30448  winClose,
30449  winRead,
30450  winWrite,
30451  winTruncate,
30452  winSync,
30453  winFileSize,
30454  winLock,
30455  winUnlock,
30456  winCheckReservedLock,
30457  winFileControl,
30458  winSectorSize,
30459  winDeviceCharacteristics,
30460  winShmOpen,              /* xShmOpen */
30461  winShmLock,              /* xShmLock */
30462  winShmMap,               /* xShmMap */
30463  winShmBarrier,           /* xShmBarrier */
30464  winShmClose              /* xShmClose */
30465};
30466
30467/***************************************************************************
30468** Here ends the I/O methods that form the sqlite3_io_methods object.
30469**
30470** The next block of code implements the VFS methods.
30471****************************************************************************/
30472
30473/*
30474** Convert a UTF-8 filename into whatever form the underlying
30475** operating system wants filenames in.  Space to hold the result
30476** is obtained from malloc and must be freed by the calling
30477** function.
30478*/
30479static void *convertUtf8Filename(const char *zFilename){
30480  void *zConverted = 0;
30481  if( isNT() ){
30482    zConverted = utf8ToUnicode(zFilename);
30483/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30484*/
30485#if SQLITE_OS_WINCE==0
30486  }else{
30487    zConverted = utf8ToMbcs(zFilename);
30488#endif
30489  }
30490  /* caller will handle out of memory */
30491  return zConverted;
30492}
30493
30494/*
30495** Create a temporary file name in zBuf.  zBuf must be big enough to
30496** hold at pVfs->mxPathname characters.
30497*/
30498static int getTempname(int nBuf, char *zBuf){
30499  static char zChars[] =
30500    "abcdefghijklmnopqrstuvwxyz"
30501    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30502    "0123456789";
30503  size_t i, j;
30504  char zTempPath[MAX_PATH+1];
30505  if( sqlite3_temp_directory ){
30506    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
30507  }else if( isNT() ){
30508    char *zMulti;
30509    WCHAR zWidePath[MAX_PATH];
30510    GetTempPathW(MAX_PATH-30, zWidePath);
30511    zMulti = unicodeToUtf8(zWidePath);
30512    if( zMulti ){
30513      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
30514      free(zMulti);
30515    }else{
30516      return SQLITE_NOMEM;
30517    }
30518/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30519** Since the ASCII version of these Windows API do not exist for WINCE,
30520** it's important to not reference them for WINCE builds.
30521*/
30522#if SQLITE_OS_WINCE==0
30523  }else{
30524    char *zUtf8;
30525    char zMbcsPath[MAX_PATH];
30526    GetTempPathA(MAX_PATH-30, zMbcsPath);
30527    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
30528    if( zUtf8 ){
30529      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
30530      free(zUtf8);
30531    }else{
30532      return SQLITE_NOMEM;
30533    }
30534#endif
30535  }
30536  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
30537  zTempPath[i] = 0;
30538  sqlite3_snprintf(nBuf-30, zBuf,
30539                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
30540  j = sqlite3Strlen30(zBuf);
30541  sqlite3_randomness(20, &zBuf[j]);
30542  for(i=0; i<20; i++, j++){
30543    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30544  }
30545  zBuf[j] = 0;
30546  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
30547  return SQLITE_OK;
30548}
30549
30550/*
30551** The return value of getLastErrorMsg
30552** is zero if the error message fits in the buffer, or non-zero
30553** otherwise (if the message was truncated).
30554*/
30555static int getLastErrorMsg(int nBuf, char *zBuf){
30556  /* FormatMessage returns 0 on failure.  Otherwise it
30557  ** returns the number of TCHARs written to the output
30558  ** buffer, excluding the terminating null char.
30559  */
30560  DWORD error = GetLastError();
30561  DWORD dwLen = 0;
30562  char *zOut = 0;
30563
30564  if( isNT() ){
30565    WCHAR *zTempWide = NULL;
30566    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30567                           NULL,
30568                           error,
30569                           0,
30570                           (LPWSTR) &zTempWide,
30571                           0,
30572                           0);
30573    if( dwLen > 0 ){
30574      /* allocate a buffer and convert to UTF8 */
30575      zOut = unicodeToUtf8(zTempWide);
30576      /* free the system buffer allocated by FormatMessage */
30577      LocalFree(zTempWide);
30578    }
30579/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30580** Since the ASCII version of these Windows API do not exist for WINCE,
30581** it's important to not reference them for WINCE builds.
30582*/
30583#if SQLITE_OS_WINCE==0
30584  }else{
30585    char *zTemp = NULL;
30586    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30587                           NULL,
30588                           error,
30589                           0,
30590                           (LPSTR) &zTemp,
30591                           0,
30592                           0);
30593    if( dwLen > 0 ){
30594      /* allocate a buffer and convert to UTF8 */
30595      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
30596      /* free the system buffer allocated by FormatMessage */
30597      LocalFree(zTemp);
30598    }
30599#endif
30600  }
30601  if( 0 == dwLen ){
30602    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
30603  }else{
30604    /* copy a maximum of nBuf chars to output buffer */
30605    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
30606    /* free the UTF8 buffer */
30607    free(zOut);
30608  }
30609  return 0;
30610}
30611
30612/*
30613** Open a file.
30614*/
30615static int winOpen(
30616  sqlite3_vfs *pVfs,        /* Not used */
30617  const char *zName,        /* Name of the file (UTF-8) */
30618  sqlite3_file *id,         /* Write the SQLite file handle here */
30619  int flags,                /* Open mode flags */
30620  int *pOutFlags            /* Status return flags */
30621){
30622  HANDLE h;
30623  DWORD dwDesiredAccess;
30624  DWORD dwShareMode;
30625  DWORD dwCreationDisposition;
30626  DWORD dwFlagsAndAttributes = 0;
30627#if SQLITE_OS_WINCE
30628  int isTemp = 0;
30629#endif
30630  winFile *pFile = (winFile*)id;
30631  void *zConverted;                 /* Filename in OS encoding */
30632  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
30633  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
30634
30635  assert( id!=0 );
30636  UNUSED_PARAMETER(pVfs);
30637
30638  pFile->h = INVALID_HANDLE_VALUE;
30639
30640  /* If the second argument to this function is NULL, generate a
30641  ** temporary file name to use
30642  */
30643  if( !zUtf8Name ){
30644    int rc = getTempname(MAX_PATH+1, zTmpname);
30645    if( rc!=SQLITE_OK ){
30646      return rc;
30647    }
30648    zUtf8Name = zTmpname;
30649  }
30650
30651  /* Convert the filename to the system encoding. */
30652  zConverted = convertUtf8Filename(zUtf8Name);
30653  if( zConverted==0 ){
30654    return SQLITE_NOMEM;
30655  }
30656
30657  if( flags & SQLITE_OPEN_READWRITE ){
30658    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
30659  }else{
30660    dwDesiredAccess = GENERIC_READ;
30661  }
30662  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
30663  ** created. SQLite doesn't use it to indicate "exclusive access"
30664  ** as it is usually understood.
30665  */
30666  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
30667  if( flags & SQLITE_OPEN_EXCLUSIVE ){
30668    /* Creates a new file, only if it does not already exist. */
30669    /* If the file exists, it fails. */
30670    dwCreationDisposition = CREATE_NEW;
30671  }else if( flags & SQLITE_OPEN_CREATE ){
30672    /* Open existing file, or create if it doesn't exist */
30673    dwCreationDisposition = OPEN_ALWAYS;
30674  }else{
30675    /* Opens a file, only if it exists. */
30676    dwCreationDisposition = OPEN_EXISTING;
30677  }
30678  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
30679  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30680#if SQLITE_OS_WINCE
30681    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
30682    isTemp = 1;
30683#else
30684    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
30685                               | FILE_ATTRIBUTE_HIDDEN
30686                               | FILE_FLAG_DELETE_ON_CLOSE;
30687#endif
30688  }else{
30689    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
30690  }
30691  /* Reports from the internet are that performance is always
30692  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
30693#if SQLITE_OS_WINCE
30694  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
30695#endif
30696  if( isNT() ){
30697    h = CreateFileW((WCHAR*)zConverted,
30698       dwDesiredAccess,
30699       dwShareMode,
30700       NULL,
30701       dwCreationDisposition,
30702       dwFlagsAndAttributes,
30703       NULL
30704    );
30705/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30706** Since the ASCII version of these Windows API do not exist for WINCE,
30707** it's important to not reference them for WINCE builds.
30708*/
30709#if SQLITE_OS_WINCE==0
30710  }else{
30711    h = CreateFileA((char*)zConverted,
30712       dwDesiredAccess,
30713       dwShareMode,
30714       NULL,
30715       dwCreationDisposition,
30716       dwFlagsAndAttributes,
30717       NULL
30718    );
30719#endif
30720  }
30721  OSTRACE(("OPEN %d %s 0x%lx %s\n",
30722           h, zName, dwDesiredAccess,
30723           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
30724  if( h==INVALID_HANDLE_VALUE ){
30725    free(zConverted);
30726    if( flags & SQLITE_OPEN_READWRITE ){
30727      return winOpen(pVfs, zName, id,
30728             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
30729    }else{
30730      return SQLITE_CANTOPEN_BKPT;
30731    }
30732  }
30733  if( pOutFlags ){
30734    if( flags & SQLITE_OPEN_READWRITE ){
30735      *pOutFlags = SQLITE_OPEN_READWRITE;
30736    }else{
30737      *pOutFlags = SQLITE_OPEN_READONLY;
30738    }
30739  }
30740  memset(pFile, 0, sizeof(*pFile));
30741  pFile->pMethod = &winIoMethod;
30742  pFile->h = h;
30743  pFile->lastErrno = NO_ERROR;
30744  pFile->pVfs = pVfs;
30745  pFile->pShm = 0;
30746  pFile->zPath = zName;
30747  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
30748#if SQLITE_OS_WINCE
30749  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
30750               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
30751       && !winceCreateLock(zName, pFile)
30752  ){
30753    CloseHandle(h);
30754    free(zConverted);
30755    return SQLITE_CANTOPEN_BKPT;
30756  }
30757  if( isTemp ){
30758    pFile->zDeleteOnClose = zConverted;
30759  }else
30760#endif
30761  {
30762    free(zConverted);
30763  }
30764  OpenCounter(+1);
30765  return SQLITE_OK;
30766}
30767
30768/*
30769** Delete the named file.
30770**
30771** Note that windows does not allow a file to be deleted if some other
30772** process has it open.  Sometimes a virus scanner or indexing program
30773** will open a journal file shortly after it is created in order to do
30774** whatever it does.  While this other process is holding the
30775** file open, we will be unable to delete it.  To work around this
30776** problem, we delay 100 milliseconds and try to delete again.  Up
30777** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
30778** up and returning an error.
30779*/
30780#define MX_DELETION_ATTEMPTS 5
30781static int winDelete(
30782  sqlite3_vfs *pVfs,          /* Not used on win32 */
30783  const char *zFilename,      /* Name of file to delete */
30784  int syncDir                 /* Not used on win32 */
30785){
30786  int cnt = 0;
30787  DWORD rc;
30788  DWORD error = 0;
30789  void *zConverted = convertUtf8Filename(zFilename);
30790  UNUSED_PARAMETER(pVfs);
30791  UNUSED_PARAMETER(syncDir);
30792  if( zConverted==0 ){
30793    return SQLITE_NOMEM;
30794  }
30795  SimulateIOError(return SQLITE_IOERR_DELETE);
30796  if( isNT() ){
30797    do{
30798      DeleteFileW(zConverted);
30799    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
30800               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
30801           && (++cnt < MX_DELETION_ATTEMPTS)
30802           && (Sleep(100), 1) );
30803/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30804** Since the ASCII version of these Windows API do not exist for WINCE,
30805** it's important to not reference them for WINCE builds.
30806*/
30807#if SQLITE_OS_WINCE==0
30808  }else{
30809    do{
30810      DeleteFileA(zConverted);
30811    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
30812               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
30813           && (++cnt < MX_DELETION_ATTEMPTS)
30814           && (Sleep(100), 1) );
30815#endif
30816  }
30817  free(zConverted);
30818  OSTRACE(("DELETE \"%s\" %s\n", zFilename,
30819       ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
30820         "ok" : "failed" ));
30821
30822  return (   (rc == INVALID_FILE_ATTRIBUTES)
30823          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
30824}
30825
30826/*
30827** Check the existance and status of a file.
30828*/
30829static int winAccess(
30830  sqlite3_vfs *pVfs,         /* Not used on win32 */
30831  const char *zFilename,     /* Name of file to check */
30832  int flags,                 /* Type of test to make on this file */
30833  int *pResOut               /* OUT: Result */
30834){
30835  DWORD attr;
30836  int rc = 0;
30837  void *zConverted = convertUtf8Filename(zFilename);
30838  UNUSED_PARAMETER(pVfs);
30839  if( zConverted==0 ){
30840    return SQLITE_NOMEM;
30841  }
30842  if( isNT() ){
30843    attr = GetFileAttributesW((WCHAR*)zConverted);
30844/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30845** Since the ASCII version of these Windows API do not exist for WINCE,
30846** it's important to not reference them for WINCE builds.
30847*/
30848#if SQLITE_OS_WINCE==0
30849  }else{
30850    attr = GetFileAttributesA((char*)zConverted);
30851#endif
30852  }
30853  free(zConverted);
30854  switch( flags ){
30855    case SQLITE_ACCESS_READ:
30856    case SQLITE_ACCESS_EXISTS:
30857      rc = attr!=INVALID_FILE_ATTRIBUTES;
30858      break;
30859    case SQLITE_ACCESS_READWRITE:
30860      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
30861      break;
30862    default:
30863      assert(!"Invalid flags argument");
30864  }
30865  *pResOut = rc;
30866  return SQLITE_OK;
30867}
30868
30869
30870/*
30871** Turn a relative pathname into a full pathname.  Write the full
30872** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
30873** bytes in size.
30874*/
30875static int winFullPathname(
30876  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30877  const char *zRelative,        /* Possibly relative input path */
30878  int nFull,                    /* Size of output buffer in bytes */
30879  char *zFull                   /* Output buffer */
30880){
30881
30882#if defined(__CYGWIN__)
30883  UNUSED_PARAMETER(nFull);
30884  cygwin_conv_to_full_win32_path(zRelative, zFull);
30885  return SQLITE_OK;
30886#endif
30887
30888#if SQLITE_OS_WINCE
30889  UNUSED_PARAMETER(nFull);
30890  /* WinCE has no concept of a relative pathname, or so I am told. */
30891  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
30892  return SQLITE_OK;
30893#endif
30894
30895#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
30896  int nByte;
30897  void *zConverted;
30898  char *zOut;
30899  UNUSED_PARAMETER(nFull);
30900  zConverted = convertUtf8Filename(zRelative);
30901  if( isNT() ){
30902    WCHAR *zTemp;
30903    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
30904    zTemp = malloc( nByte*sizeof(zTemp[0]) );
30905    if( zTemp==0 ){
30906      free(zConverted);
30907      return SQLITE_NOMEM;
30908    }
30909    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
30910    free(zConverted);
30911    zOut = unicodeToUtf8(zTemp);
30912    free(zTemp);
30913/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30914** Since the ASCII version of these Windows API do not exist for WINCE,
30915** it's important to not reference them for WINCE builds.
30916*/
30917#if SQLITE_OS_WINCE==0
30918  }else{
30919    char *zTemp;
30920    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
30921    zTemp = malloc( nByte*sizeof(zTemp[0]) );
30922    if( zTemp==0 ){
30923      free(zConverted);
30924      return SQLITE_NOMEM;
30925    }
30926    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
30927    free(zConverted);
30928    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
30929    free(zTemp);
30930#endif
30931  }
30932  if( zOut ){
30933    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
30934    free(zOut);
30935    return SQLITE_OK;
30936  }else{
30937    return SQLITE_NOMEM;
30938  }
30939#endif
30940}
30941
30942/*
30943** Get the sector size of the device used to store
30944** file.
30945*/
30946static int getSectorSize(
30947    sqlite3_vfs *pVfs,
30948    const char *zRelative     /* UTF-8 file name */
30949){
30950  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
30951  /* GetDiskFreeSpace is not supported under WINCE */
30952#if SQLITE_OS_WINCE
30953  UNUSED_PARAMETER(pVfs);
30954  UNUSED_PARAMETER(zRelative);
30955#else
30956  char zFullpath[MAX_PATH+1];
30957  int rc;
30958  DWORD dwRet = 0;
30959  DWORD dwDummy;
30960
30961  /*
30962  ** We need to get the full path name of the file
30963  ** to get the drive letter to look up the sector
30964  ** size.
30965  */
30966  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
30967  if( rc == SQLITE_OK )
30968  {
30969    void *zConverted = convertUtf8Filename(zFullpath);
30970    if( zConverted ){
30971      if( isNT() ){
30972        /* trim path to just drive reference */
30973        WCHAR *p = zConverted;
30974        for(;*p;p++){
30975          if( *p == '\\' ){
30976            *p = '\0';
30977            break;
30978          }
30979        }
30980        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
30981                                  &dwDummy,
30982                                  &bytesPerSector,
30983                                  &dwDummy,
30984                                  &dwDummy);
30985      }else{
30986        /* trim path to just drive reference */
30987        char *p = (char *)zConverted;
30988        for(;*p;p++){
30989          if( *p == '\\' ){
30990            *p = '\0';
30991            break;
30992          }
30993        }
30994        dwRet = GetDiskFreeSpaceA((char*)zConverted,
30995                                  &dwDummy,
30996                                  &bytesPerSector,
30997                                  &dwDummy,
30998                                  &dwDummy);
30999      }
31000      free(zConverted);
31001    }
31002    if( !dwRet ){
31003      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31004    }
31005  }
31006#endif
31007  return (int) bytesPerSector;
31008}
31009
31010#ifndef SQLITE_OMIT_LOAD_EXTENSION
31011/*
31012** Interfaces for opening a shared library, finding entry points
31013** within the shared library, and closing the shared library.
31014*/
31015/*
31016** Interfaces for opening a shared library, finding entry points
31017** within the shared library, and closing the shared library.
31018*/
31019static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
31020  HANDLE h;
31021  void *zConverted = convertUtf8Filename(zFilename);
31022  UNUSED_PARAMETER(pVfs);
31023  if( zConverted==0 ){
31024    return 0;
31025  }
31026  if( isNT() ){
31027    h = LoadLibraryW((WCHAR*)zConverted);
31028/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31029** Since the ASCII version of these Windows API do not exist for WINCE,
31030** it's important to not reference them for WINCE builds.
31031*/
31032#if SQLITE_OS_WINCE==0
31033  }else{
31034    h = LoadLibraryA((char*)zConverted);
31035#endif
31036  }
31037  free(zConverted);
31038  return (void*)h;
31039}
31040static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
31041  UNUSED_PARAMETER(pVfs);
31042  getLastErrorMsg(nBuf, zBufOut);
31043}
31044void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
31045  UNUSED_PARAMETER(pVfs);
31046#if SQLITE_OS_WINCE
31047  /* The GetProcAddressA() routine is only available on wince. */
31048  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
31049#else
31050  /* All other windows platforms expect GetProcAddress() to take
31051  ** an Ansi string regardless of the _UNICODE setting */
31052  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
31053#endif
31054}
31055void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
31056  UNUSED_PARAMETER(pVfs);
31057  FreeLibrary((HANDLE)pHandle);
31058}
31059#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31060  #define winDlOpen  0
31061  #define winDlError 0
31062  #define winDlSym   0
31063  #define winDlClose 0
31064#endif
31065
31066
31067/*
31068** Write up to nBuf bytes of randomness into zBuf.
31069*/
31070static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31071  int n = 0;
31072  UNUSED_PARAMETER(pVfs);
31073#if defined(SQLITE_TEST)
31074  n = nBuf;
31075  memset(zBuf, 0, nBuf);
31076#else
31077  if( sizeof(SYSTEMTIME)<=nBuf-n ){
31078    SYSTEMTIME x;
31079    GetSystemTime(&x);
31080    memcpy(&zBuf[n], &x, sizeof(x));
31081    n += sizeof(x);
31082  }
31083  if( sizeof(DWORD)<=nBuf-n ){
31084    DWORD pid = GetCurrentProcessId();
31085    memcpy(&zBuf[n], &pid, sizeof(pid));
31086    n += sizeof(pid);
31087  }
31088  if( sizeof(DWORD)<=nBuf-n ){
31089    DWORD cnt = GetTickCount();
31090    memcpy(&zBuf[n], &cnt, sizeof(cnt));
31091    n += sizeof(cnt);
31092  }
31093  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
31094    LARGE_INTEGER i;
31095    QueryPerformanceCounter(&i);
31096    memcpy(&zBuf[n], &i, sizeof(i));
31097    n += sizeof(i);
31098  }
31099#endif
31100  return n;
31101}
31102
31103
31104/*
31105** Sleep for a little while.  Return the amount of time slept.
31106*/
31107static int winSleep(sqlite3_vfs *pVfs, int microsec){
31108  Sleep((microsec+999)/1000);
31109  UNUSED_PARAMETER(pVfs);
31110  return ((microsec+999)/1000)*1000;
31111}
31112
31113/*
31114** The following variable, if set to a non-zero value, is interpreted as
31115** the number of seconds since 1970 and is used to set the result of
31116** sqlite3OsCurrentTime() during testing.
31117*/
31118#ifdef SQLITE_TEST
31119SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31120#endif
31121
31122/*
31123** Find the current time (in Universal Coordinated Time).  Write into *piNow
31124** the current time and date as a Julian Day number times 86_400_000.  In
31125** other words, write into *piNow the number of milliseconds since the Julian
31126** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31127** proleptic Gregorian calendar.
31128**
31129** On success, return 0.  Return 1 if the time and date cannot be found.
31130*/
31131static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
31132  /* FILETIME structure is a 64-bit value representing the number of
31133     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
31134  */
31135  FILETIME ft;
31136  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
31137#ifdef SQLITE_TEST
31138  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31139#endif
31140  /* 2^32 - to avoid use of LL and warnings in gcc */
31141  static const sqlite3_int64 max32BitValue =
31142      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
31143
31144#if SQLITE_OS_WINCE
31145  SYSTEMTIME time;
31146  GetSystemTime(&time);
31147  /* if SystemTimeToFileTime() fails, it returns zero. */
31148  if (!SystemTimeToFileTime(&time,&ft)){
31149    return 1;
31150  }
31151#else
31152  GetSystemTimeAsFileTime( &ft );
31153#endif
31154
31155  *piNow = winFiletimeEpoch +
31156            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
31157               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
31158
31159#ifdef SQLITE_TEST
31160  if( sqlite3_current_time ){
31161    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31162  }
31163#endif
31164  UNUSED_PARAMETER(pVfs);
31165  return 0;
31166}
31167
31168/*
31169** Find the current time (in Universal Coordinated Time).  Write the
31170** current time and date as a Julian Day number into *prNow and
31171** return 0.  Return 1 if the time and date cannot be found.
31172*/
31173int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31174  int rc;
31175  sqlite3_int64 i;
31176  rc = winCurrentTimeInt64(pVfs, &i);
31177  if( !rc ){
31178    *prNow = i/86400000.0;
31179  }
31180  return rc;
31181}
31182
31183/*
31184** The idea is that this function works like a combination of
31185** GetLastError() and FormatMessage() on windows (or errno and
31186** strerror_r() on unix). After an error is returned by an OS
31187** function, SQLite calls this function with zBuf pointing to
31188** a buffer of nBuf bytes. The OS layer should populate the
31189** buffer with a nul-terminated UTF-8 encoded error message
31190** describing the last IO error to have occurred within the calling
31191** thread.
31192**
31193** If the error message is too large for the supplied buffer,
31194** it should be truncated. The return value of xGetLastError
31195** is zero if the error message fits in the buffer, or non-zero
31196** otherwise (if the message was truncated). If non-zero is returned,
31197** then it is not necessary to include the nul-terminator character
31198** in the output buffer.
31199**
31200** Not supplying an error message will have no adverse effect
31201** on SQLite. It is fine to have an implementation that never
31202** returns an error message:
31203**
31204**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31205**     assert(zBuf[0]=='\0');
31206**     return 0;
31207**   }
31208**
31209** However if an error message is supplied, it will be incorporated
31210** by sqlite into the error message available to the user using
31211** sqlite3_errmsg(), possibly making IO errors easier to debug.
31212*/
31213static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31214  UNUSED_PARAMETER(pVfs);
31215  return getLastErrorMsg(nBuf, zBuf);
31216}
31217
31218
31219
31220/*
31221** Initialize and deinitialize the operating system interface.
31222*/
31223SQLITE_API int sqlite3_os_init(void){
31224  static sqlite3_vfs winVfs = {
31225    2,                   /* iVersion */
31226    sizeof(winFile),     /* szOsFile */
31227    MAX_PATH,            /* mxPathname */
31228    0,                   /* pNext */
31229    "win32",             /* zName */
31230    0,                   /* pAppData */
31231    winOpen,             /* xOpen */
31232    winDelete,           /* xDelete */
31233    winAccess,           /* xAccess */
31234    winFullPathname,     /* xFullPathname */
31235    winDlOpen,           /* xDlOpen */
31236    winDlError,          /* xDlError */
31237    winDlSym,            /* xDlSym */
31238    winDlClose,          /* xDlClose */
31239    winRandomness,       /* xRandomness */
31240    winSleep,            /* xSleep */
31241    winCurrentTime,      /* xCurrentTime */
31242    winGetLastError,     /* xGetLastError */
31243    0,                   /* xRename */
31244    winCurrentTimeInt64, /* xCurrentTimeInt64 */
31245  };
31246
31247  sqlite3_vfs_register(&winVfs, 1);
31248  return SQLITE_OK;
31249}
31250SQLITE_API int sqlite3_os_end(void){
31251  return SQLITE_OK;
31252}
31253
31254#endif /* SQLITE_OS_WIN */
31255
31256/************** End of os_win.c **********************************************/
31257/************** Begin file bitvec.c ******************************************/
31258/*
31259** 2008 February 16
31260**
31261** The author disclaims copyright to this source code.  In place of
31262** a legal notice, here is a blessing:
31263**
31264**    May you do good and not evil.
31265**    May you find forgiveness for yourself and forgive others.
31266**    May you share freely, never taking more than you give.
31267**
31268*************************************************************************
31269** This file implements an object that represents a fixed-length
31270** bitmap.  Bits are numbered starting with 1.
31271**
31272** A bitmap is used to record which pages of a database file have been
31273** journalled during a transaction, or which pages have the "dont-write"
31274** property.  Usually only a few pages are meet either condition.
31275** So the bitmap is usually sparse and has low cardinality.
31276** But sometimes (for example when during a DROP of a large table) most
31277** or all of the pages in a database can get journalled.  In those cases,
31278** the bitmap becomes dense with high cardinality.  The algorithm needs
31279** to handle both cases well.
31280**
31281** The size of the bitmap is fixed when the object is created.
31282**
31283** All bits are clear when the bitmap is created.  Individual bits
31284** may be set or cleared one at a time.
31285**
31286** Test operations are about 100 times more common that set operations.
31287** Clear operations are exceedingly rare.  There are usually between
31288** 5 and 500 set operations per Bitvec object, though the number of sets can
31289** sometimes grow into tens of thousands or larger.  The size of the
31290** Bitvec object is the number of pages in the database file at the
31291** start of a transaction, and is thus usually less than a few thousand,
31292** but can be as large as 2 billion for a really big database.
31293*/
31294
31295/* Size of the Bitvec structure in bytes. */
31296#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
31297
31298/* Round the union size down to the nearest pointer boundary, since that's how
31299** it will be aligned within the Bitvec struct. */
31300#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
31301
31302/* Type of the array "element" for the bitmap representation.
31303** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
31304** Setting this to the "natural word" size of your CPU may improve
31305** performance. */
31306#define BITVEC_TELEM     u8
31307/* Size, in bits, of the bitmap element. */
31308#define BITVEC_SZELEM    8
31309/* Number of elements in a bitmap array. */
31310#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
31311/* Number of bits in the bitmap array. */
31312#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
31313
31314/* Number of u32 values in hash table. */
31315#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
31316/* Maximum number of entries in hash table before
31317** sub-dividing and re-hashing. */
31318#define BITVEC_MXHASH    (BITVEC_NINT/2)
31319/* Hashing function for the aHash representation.
31320** Empirical testing showed that the *37 multiplier
31321** (an arbitrary prime)in the hash function provided
31322** no fewer collisions than the no-op *1. */
31323#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
31324
31325#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
31326
31327
31328/*
31329** A bitmap is an instance of the following structure.
31330**
31331** This bitmap records the existance of zero or more bits
31332** with values between 1 and iSize, inclusive.
31333**
31334** There are three possible representations of the bitmap.
31335** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
31336** bitmap.  The least significant bit is bit 1.
31337**
31338** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
31339** a hash table that will hold up to BITVEC_MXHASH distinct values.
31340**
31341** Otherwise, the value i is redirected into one of BITVEC_NPTR
31342** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
31343** handles up to iDivisor separate values of i.  apSub[0] holds
31344** values between 1 and iDivisor.  apSub[1] holds values between
31345** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
31346** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
31347** to hold deal with values between 1 and iDivisor.
31348*/
31349struct Bitvec {
31350  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
31351  u32 nSet;       /* Number of bits that are set - only valid for aHash
31352                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
31353                  ** this would be 125. */
31354  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
31355                  /* Should >=0 for apSub element. */
31356                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
31357                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
31358  union {
31359    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
31360    u32 aHash[BITVEC_NINT];      /* Hash table representation */
31361    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
31362  } u;
31363};
31364
31365/*
31366** Create a new bitmap object able to handle bits between 0 and iSize,
31367** inclusive.  Return a pointer to the new object.  Return NULL if
31368** malloc fails.
31369*/
31370SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
31371  Bitvec *p;
31372  assert( sizeof(*p)==BITVEC_SZ );
31373  p = sqlite3MallocZero( sizeof(*p) );
31374  if( p ){
31375    p->iSize = iSize;
31376  }
31377  return p;
31378}
31379
31380/*
31381** Check to see if the i-th bit is set.  Return true or false.
31382** If p is NULL (if the bitmap has not been created) or if
31383** i is out of range, then return false.
31384*/
31385SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
31386  if( p==0 ) return 0;
31387  if( i>p->iSize || i==0 ) return 0;
31388  i--;
31389  while( p->iDivisor ){
31390    u32 bin = i/p->iDivisor;
31391    i = i%p->iDivisor;
31392    p = p->u.apSub[bin];
31393    if (!p) {
31394      return 0;
31395    }
31396  }
31397  if( p->iSize<=BITVEC_NBIT ){
31398    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
31399  } else{
31400    u32 h = BITVEC_HASH(i++);
31401    while( p->u.aHash[h] ){
31402      if( p->u.aHash[h]==i ) return 1;
31403      h = (h+1) % BITVEC_NINT;
31404    }
31405    return 0;
31406  }
31407}
31408
31409/*
31410** Set the i-th bit.  Return 0 on success and an error code if
31411** anything goes wrong.
31412**
31413** This routine might cause sub-bitmaps to be allocated.  Failing
31414** to get the memory needed to hold the sub-bitmap is the only
31415** that can go wrong with an insert, assuming p and i are valid.
31416**
31417** The calling function must ensure that p is a valid Bitvec object
31418** and that the value for "i" is within range of the Bitvec object.
31419** Otherwise the behavior is undefined.
31420*/
31421SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
31422  u32 h;
31423  if( p==0 ) return SQLITE_OK;
31424  assert( i>0 );
31425  assert( i<=p->iSize );
31426  i--;
31427  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
31428    u32 bin = i/p->iDivisor;
31429    i = i%p->iDivisor;
31430    if( p->u.apSub[bin]==0 ){
31431      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
31432      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
31433    }
31434    p = p->u.apSub[bin];
31435  }
31436  if( p->iSize<=BITVEC_NBIT ){
31437    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
31438    return SQLITE_OK;
31439  }
31440  h = BITVEC_HASH(i++);
31441  /* if there wasn't a hash collision, and this doesn't */
31442  /* completely fill the hash, then just add it without */
31443  /* worring about sub-dividing and re-hashing. */
31444  if( !p->u.aHash[h] ){
31445    if (p->nSet<(BITVEC_NINT-1)) {
31446      goto bitvec_set_end;
31447    } else {
31448      goto bitvec_set_rehash;
31449    }
31450  }
31451  /* there was a collision, check to see if it's already */
31452  /* in hash, if not, try to find a spot for it */
31453  do {
31454    if( p->u.aHash[h]==i ) return SQLITE_OK;
31455    h++;
31456    if( h>=BITVEC_NINT ) h = 0;
31457  } while( p->u.aHash[h] );
31458  /* we didn't find it in the hash.  h points to the first */
31459  /* available free spot. check to see if this is going to */
31460  /* make our hash too "full".  */
31461bitvec_set_rehash:
31462  if( p->nSet>=BITVEC_MXHASH ){
31463    unsigned int j;
31464    int rc;
31465    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
31466    if( aiValues==0 ){
31467      return SQLITE_NOMEM;
31468    }else{
31469      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31470      memset(p->u.apSub, 0, sizeof(p->u.apSub));
31471      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
31472      rc = sqlite3BitvecSet(p, i);
31473      for(j=0; j<BITVEC_NINT; j++){
31474        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
31475      }
31476      sqlite3StackFree(0, aiValues);
31477      return rc;
31478    }
31479  }
31480bitvec_set_end:
31481  p->nSet++;
31482  p->u.aHash[h] = i;
31483  return SQLITE_OK;
31484}
31485
31486/*
31487** Clear the i-th bit.
31488**
31489** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
31490** that BitvecClear can use to rebuilt its hash table.
31491*/
31492SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
31493  if( p==0 ) return;
31494  assert( i>0 );
31495  i--;
31496  while( p->iDivisor ){
31497    u32 bin = i/p->iDivisor;
31498    i = i%p->iDivisor;
31499    p = p->u.apSub[bin];
31500    if (!p) {
31501      return;
31502    }
31503  }
31504  if( p->iSize<=BITVEC_NBIT ){
31505    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
31506  }else{
31507    unsigned int j;
31508    u32 *aiValues = pBuf;
31509    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31510    memset(p->u.aHash, 0, sizeof(p->u.aHash));
31511    p->nSet = 0;
31512    for(j=0; j<BITVEC_NINT; j++){
31513      if( aiValues[j] && aiValues[j]!=(i+1) ){
31514        u32 h = BITVEC_HASH(aiValues[j]-1);
31515        p->nSet++;
31516        while( p->u.aHash[h] ){
31517          h++;
31518          if( h>=BITVEC_NINT ) h = 0;
31519        }
31520        p->u.aHash[h] = aiValues[j];
31521      }
31522    }
31523  }
31524}
31525
31526/*
31527** Destroy a bitmap object.  Reclaim all memory used.
31528*/
31529SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
31530  if( p==0 ) return;
31531  if( p->iDivisor ){
31532    unsigned int i;
31533    for(i=0; i<BITVEC_NPTR; i++){
31534      sqlite3BitvecDestroy(p->u.apSub[i]);
31535    }
31536  }
31537  sqlite3_free(p);
31538}
31539
31540/*
31541** Return the value of the iSize parameter specified when Bitvec *p
31542** was created.
31543*/
31544SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
31545  return p->iSize;
31546}
31547
31548#ifndef SQLITE_OMIT_BUILTIN_TEST
31549/*
31550** Let V[] be an array of unsigned characters sufficient to hold
31551** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
31552** Then the following macros can be used to set, clear, or test
31553** individual bits within V.
31554*/
31555#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
31556#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
31557#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
31558
31559/*
31560** This routine runs an extensive test of the Bitvec code.
31561**
31562** The input is an array of integers that acts as a program
31563** to test the Bitvec.  The integers are opcodes followed
31564** by 0, 1, or 3 operands, depending on the opcode.  Another
31565** opcode follows immediately after the last operand.
31566**
31567** There are 6 opcodes numbered from 0 through 5.  0 is the
31568** "halt" opcode and causes the test to end.
31569**
31570**    0          Halt and return the number of errors
31571**    1 N S X    Set N bits beginning with S and incrementing by X
31572**    2 N S X    Clear N bits beginning with S and incrementing by X
31573**    3 N        Set N randomly chosen bits
31574**    4 N        Clear N randomly chosen bits
31575**    5 N S X    Set N bits from S increment X in array only, not in bitvec
31576**
31577** The opcodes 1 through 4 perform set and clear operations are performed
31578** on both a Bitvec object and on a linear array of bits obtained from malloc.
31579** Opcode 5 works on the linear array only, not on the Bitvec.
31580** Opcode 5 is used to deliberately induce a fault in order to
31581** confirm that error detection works.
31582**
31583** At the conclusion of the test the linear array is compared
31584** against the Bitvec object.  If there are any differences,
31585** an error is returned.  If they are the same, zero is returned.
31586**
31587** If a memory allocation error occurs, return -1.
31588*/
31589SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
31590  Bitvec *pBitvec = 0;
31591  unsigned char *pV = 0;
31592  int rc = -1;
31593  int i, nx, pc, op;
31594  void *pTmpSpace;
31595
31596  /* Allocate the Bitvec to be tested and a linear array of
31597  ** bits to act as the reference */
31598  pBitvec = sqlite3BitvecCreate( sz );
31599  pV = sqlite3_malloc( (sz+7)/8 + 1 );
31600  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
31601  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
31602  memset(pV, 0, (sz+7)/8 + 1);
31603
31604  /* NULL pBitvec tests */
31605  sqlite3BitvecSet(0, 1);
31606  sqlite3BitvecClear(0, 1, pTmpSpace);
31607
31608  /* Run the program */
31609  pc = 0;
31610  while( (op = aOp[pc])!=0 ){
31611    switch( op ){
31612      case 1:
31613      case 2:
31614      case 5: {
31615        nx = 4;
31616        i = aOp[pc+2] - 1;
31617        aOp[pc+2] += aOp[pc+3];
31618        break;
31619      }
31620      case 3:
31621      case 4:
31622      default: {
31623        nx = 2;
31624        sqlite3_randomness(sizeof(i), &i);
31625        break;
31626      }
31627    }
31628    if( (--aOp[pc+1]) > 0 ) nx = 0;
31629    pc += nx;
31630    i = (i & 0x7fffffff)%sz;
31631    if( (op & 1)!=0 ){
31632      SETBIT(pV, (i+1));
31633      if( op!=5 ){
31634        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
31635      }
31636    }else{
31637      CLEARBIT(pV, (i+1));
31638      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
31639    }
31640  }
31641
31642  /* Test to make sure the linear array exactly matches the
31643  ** Bitvec object.  Start with the assumption that they do
31644  ** match (rc==0).  Change rc to non-zero if a discrepancy
31645  ** is found.
31646  */
31647  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
31648          + sqlite3BitvecTest(pBitvec, 0)
31649          + (sqlite3BitvecSize(pBitvec) - sz);
31650  for(i=1; i<=sz; i++){
31651    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
31652      rc = i;
31653      break;
31654    }
31655  }
31656
31657  /* Free allocated structure */
31658bitvec_end:
31659  sqlite3_free(pTmpSpace);
31660  sqlite3_free(pV);
31661  sqlite3BitvecDestroy(pBitvec);
31662  return rc;
31663}
31664#endif /* SQLITE_OMIT_BUILTIN_TEST */
31665
31666/************** End of bitvec.c **********************************************/
31667/************** Begin file pcache.c ******************************************/
31668/*
31669** 2008 August 05
31670**
31671** The author disclaims copyright to this source code.  In place of
31672** a legal notice, here is a blessing:
31673**
31674**    May you do good and not evil.
31675**    May you find forgiveness for yourself and forgive others.
31676**    May you share freely, never taking more than you give.
31677**
31678*************************************************************************
31679** This file implements that page cache.
31680*/
31681
31682/*
31683** A complete page cache is an instance of this structure.
31684*/
31685struct PCache {
31686  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
31687  PgHdr *pSynced;                     /* Last synced page in dirty page list */
31688  int nRef;                           /* Number of referenced pages */
31689  int nMax;                           /* Configured cache size */
31690  int szPage;                         /* Size of every page in this cache */
31691  int szExtra;                        /* Size of extra space for each page */
31692  int bPurgeable;                     /* True if pages are on backing store */
31693  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
31694  void *pStress;                      /* Argument to xStress */
31695  sqlite3_pcache *pCache;             /* Pluggable cache module */
31696  PgHdr *pPage1;                      /* Reference to page 1 */
31697};
31698
31699/*
31700** Some of the assert() macros in this code are too expensive to run
31701** even during normal debugging.  Use them only rarely on long-running
31702** tests.  Enable the expensive asserts using the
31703** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
31704*/
31705#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
31706# define expensive_assert(X)  assert(X)
31707#else
31708# define expensive_assert(X)
31709#endif
31710
31711/********************************** Linked List Management ********************/
31712
31713#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
31714/*
31715** Check that the pCache->pSynced variable is set correctly. If it
31716** is not, either fail an assert or return zero. Otherwise, return
31717** non-zero. This is only used in debugging builds, as follows:
31718**
31719**   expensive_assert( pcacheCheckSynced(pCache) );
31720*/
31721static int pcacheCheckSynced(PCache *pCache){
31722  PgHdr *p;
31723  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
31724    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
31725  }
31726  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
31727}
31728#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
31729
31730/*
31731** Remove page pPage from the list of dirty pages.
31732*/
31733static void pcacheRemoveFromDirtyList(PgHdr *pPage){
31734  PCache *p = pPage->pCache;
31735
31736  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
31737  assert( pPage->pDirtyPrev || pPage==p->pDirty );
31738
31739  /* Update the PCache1.pSynced variable if necessary. */
31740  if( p->pSynced==pPage ){
31741    PgHdr *pSynced = pPage->pDirtyPrev;
31742    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
31743      pSynced = pSynced->pDirtyPrev;
31744    }
31745    p->pSynced = pSynced;
31746  }
31747
31748  if( pPage->pDirtyNext ){
31749    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
31750  }else{
31751    assert( pPage==p->pDirtyTail );
31752    p->pDirtyTail = pPage->pDirtyPrev;
31753  }
31754  if( pPage->pDirtyPrev ){
31755    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
31756  }else{
31757    assert( pPage==p->pDirty );
31758    p->pDirty = pPage->pDirtyNext;
31759  }
31760  pPage->pDirtyNext = 0;
31761  pPage->pDirtyPrev = 0;
31762
31763  expensive_assert( pcacheCheckSynced(p) );
31764}
31765
31766/*
31767** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
31768** pPage).
31769*/
31770static void pcacheAddToDirtyList(PgHdr *pPage){
31771  PCache *p = pPage->pCache;
31772
31773  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
31774
31775  pPage->pDirtyNext = p->pDirty;
31776  if( pPage->pDirtyNext ){
31777    assert( pPage->pDirtyNext->pDirtyPrev==0 );
31778    pPage->pDirtyNext->pDirtyPrev = pPage;
31779  }
31780  p->pDirty = pPage;
31781  if( !p->pDirtyTail ){
31782    p->pDirtyTail = pPage;
31783  }
31784  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
31785    p->pSynced = pPage;
31786  }
31787  expensive_assert( pcacheCheckSynced(p) );
31788}
31789
31790/*
31791** Wrapper around the pluggable caches xUnpin method. If the cache is
31792** being used for an in-memory database, this function is a no-op.
31793*/
31794static void pcacheUnpin(PgHdr *p){
31795  PCache *pCache = p->pCache;
31796  if( pCache->bPurgeable ){
31797    if( p->pgno==1 ){
31798      pCache->pPage1 = 0;
31799    }
31800    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
31801  }
31802}
31803
31804/*************************************************** General Interfaces ******
31805**
31806** Initialize and shutdown the page cache subsystem. Neither of these
31807** functions are threadsafe.
31808*/
31809SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
31810  if( sqlite3GlobalConfig.pcache.xInit==0 ){
31811    sqlite3PCacheSetDefault();
31812  }
31813  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
31814}
31815SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
31816  if( sqlite3GlobalConfig.pcache.xShutdown ){
31817    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
31818  }
31819}
31820
31821/*
31822** Return the size in bytes of a PCache object.
31823*/
31824SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
31825
31826/*
31827** Create a new PCache object. Storage space to hold the object
31828** has already been allocated and is passed in as the p pointer.
31829** The caller discovers how much space needs to be allocated by
31830** calling sqlite3PcacheSize().
31831*/
31832SQLITE_PRIVATE void sqlite3PcacheOpen(
31833  int szPage,                  /* Size of every page */
31834  int szExtra,                 /* Extra space associated with each page */
31835  int bPurgeable,              /* True if pages are on backing store */
31836  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
31837  void *pStress,               /* Argument to xStress */
31838  PCache *p                    /* Preallocated space for the PCache */
31839){
31840  memset(p, 0, sizeof(PCache));
31841  p->szPage = szPage;
31842  p->szExtra = szExtra;
31843  p->bPurgeable = bPurgeable;
31844  p->xStress = xStress;
31845  p->pStress = pStress;
31846  p->nMax = 100;
31847}
31848
31849/*
31850** Change the page size for PCache object. The caller must ensure that there
31851** are no outstanding page references when this function is called.
31852*/
31853SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
31854  assert( pCache->nRef==0 && pCache->pDirty==0 );
31855  if( pCache->pCache ){
31856    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
31857    pCache->pCache = 0;
31858    pCache->pPage1 = 0;
31859  }
31860  pCache->szPage = szPage;
31861}
31862
31863/*
31864** Try to obtain a page from the cache.
31865*/
31866SQLITE_PRIVATE int sqlite3PcacheFetch(
31867  PCache *pCache,       /* Obtain the page from this cache */
31868  Pgno pgno,            /* Page number to obtain */
31869  int createFlag,       /* If true, create page if it does not exist already */
31870  PgHdr **ppPage        /* Write the page here */
31871){
31872  PgHdr *pPage = 0;
31873  int eCreate;
31874
31875  assert( pCache!=0 );
31876  assert( createFlag==1 || createFlag==0 );
31877  assert( pgno>0 );
31878
31879  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
31880  ** allocate it now.
31881  */
31882  if( !pCache->pCache && createFlag ){
31883    sqlite3_pcache *p;
31884    int nByte;
31885    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
31886    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
31887    if( !p ){
31888      return SQLITE_NOMEM;
31889    }
31890    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
31891    pCache->pCache = p;
31892  }
31893
31894  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
31895  if( pCache->pCache ){
31896    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
31897  }
31898
31899  if( !pPage && eCreate==1 ){
31900    PgHdr *pPg;
31901
31902    /* Find a dirty page to write-out and recycle. First try to find a
31903    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
31904    ** cleared), but if that is not possible settle for any other
31905    ** unreferenced dirty page.
31906    */
31907    expensive_assert( pcacheCheckSynced(pCache) );
31908    for(pPg=pCache->pSynced;
31909        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
31910        pPg=pPg->pDirtyPrev
31911    );
31912    pCache->pSynced = pPg;
31913    if( !pPg ){
31914      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
31915    }
31916    if( pPg ){
31917      int rc;
31918      rc = pCache->xStress(pCache->pStress, pPg);
31919      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
31920        return rc;
31921      }
31922    }
31923
31924    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
31925  }
31926
31927  if( pPage ){
31928    if( !pPage->pData ){
31929      memset(pPage, 0, sizeof(PgHdr));
31930      pPage->pData = (void *)&pPage[1];
31931      pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
31932      memset(pPage->pExtra, 0, pCache->szExtra);
31933      pPage->pCache = pCache;
31934      pPage->pgno = pgno;
31935    }
31936    assert( pPage->pCache==pCache );
31937    assert( pPage->pgno==pgno );
31938    assert( pPage->pData==(void *)&pPage[1] );
31939    assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
31940
31941    if( 0==pPage->nRef ){
31942      pCache->nRef++;
31943    }
31944    pPage->nRef++;
31945    if( pgno==1 ){
31946      pCache->pPage1 = pPage;
31947    }
31948  }
31949  *ppPage = pPage;
31950  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
31951}
31952
31953/*
31954** Decrement the reference count on a page. If the page is clean and the
31955** reference count drops to 0, then it is made elible for recycling.
31956*/
31957SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
31958  assert( p->nRef>0 );
31959  p->nRef--;
31960  if( p->nRef==0 ){
31961    PCache *pCache = p->pCache;
31962    pCache->nRef--;
31963    if( (p->flags&PGHDR_DIRTY)==0 ){
31964      pcacheUnpin(p);
31965    }else{
31966      /* Move the page to the head of the dirty list. */
31967      pcacheRemoveFromDirtyList(p);
31968      pcacheAddToDirtyList(p);
31969    }
31970  }
31971}
31972
31973/*
31974** Increase the reference count of a supplied page by 1.
31975*/
31976SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
31977  assert(p->nRef>0);
31978  p->nRef++;
31979}
31980
31981/*
31982** Drop a page from the cache. There must be exactly one reference to the
31983** page. This function deletes that reference, so after it returns the
31984** page pointed to by p is invalid.
31985*/
31986SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
31987  PCache *pCache;
31988  assert( p->nRef==1 );
31989  if( p->flags&PGHDR_DIRTY ){
31990    pcacheRemoveFromDirtyList(p);
31991  }
31992  pCache = p->pCache;
31993  pCache->nRef--;
31994  if( p->pgno==1 ){
31995    pCache->pPage1 = 0;
31996  }
31997  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
31998}
31999
32000/*
32001** Make sure the page is marked as dirty. If it isn't dirty already,
32002** make it so.
32003*/
32004SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
32005  p->flags &= ~PGHDR_DONT_WRITE;
32006  assert( p->nRef>0 );
32007  if( 0==(p->flags & PGHDR_DIRTY) ){
32008    p->flags |= PGHDR_DIRTY;
32009    pcacheAddToDirtyList( p);
32010  }
32011}
32012
32013/*
32014** Make sure the page is marked as clean. If it isn't clean already,
32015** make it so.
32016*/
32017SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
32018  if( (p->flags & PGHDR_DIRTY) ){
32019    pcacheRemoveFromDirtyList(p);
32020    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
32021    if( p->nRef==0 ){
32022      pcacheUnpin(p);
32023    }
32024  }
32025}
32026
32027/*
32028** Make every page in the cache clean.
32029*/
32030SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
32031  PgHdr *p;
32032  while( (p = pCache->pDirty)!=0 ){
32033    sqlite3PcacheMakeClean(p);
32034  }
32035}
32036
32037/*
32038** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
32039*/
32040SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
32041  PgHdr *p;
32042  for(p=pCache->pDirty; p; p=p->pDirtyNext){
32043    p->flags &= ~PGHDR_NEED_SYNC;
32044  }
32045  pCache->pSynced = pCache->pDirtyTail;
32046}
32047
32048/*
32049** Change the page number of page p to newPgno.
32050*/
32051SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
32052  PCache *pCache = p->pCache;
32053  assert( p->nRef>0 );
32054  assert( newPgno>0 );
32055  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
32056  p->pgno = newPgno;
32057  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
32058    pcacheRemoveFromDirtyList(p);
32059    pcacheAddToDirtyList(p);
32060  }
32061}
32062
32063/*
32064** Drop every cache entry whose page number is greater than "pgno". The
32065** caller must ensure that there are no outstanding references to any pages
32066** other than page 1 with a page number greater than pgno.
32067**
32068** If there is a reference to page 1 and the pgno parameter passed to this
32069** function is 0, then the data area associated with page 1 is zeroed, but
32070** the page object is not dropped.
32071*/
32072SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
32073  if( pCache->pCache ){
32074    PgHdr *p;
32075    PgHdr *pNext;
32076    for(p=pCache->pDirty; p; p=pNext){
32077      pNext = p->pDirtyNext;
32078      /* This routine never gets call with a positive pgno except right
32079      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
32080      ** it must be that pgno==0.
32081      */
32082      assert( p->pgno>0 );
32083      if( ALWAYS(p->pgno>pgno) ){
32084        assert( p->flags&PGHDR_DIRTY );
32085        sqlite3PcacheMakeClean(p);
32086      }
32087    }
32088    if( pgno==0 && pCache->pPage1 ){
32089      memset(pCache->pPage1->pData, 0, pCache->szPage);
32090      pgno = 1;
32091    }
32092    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
32093  }
32094}
32095
32096/*
32097** Close a cache.
32098*/
32099SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
32100  if( pCache->pCache ){
32101    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32102  }
32103}
32104
32105/*
32106** Discard the contents of the cache.
32107*/
32108SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
32109  sqlite3PcacheTruncate(pCache, 0);
32110}
32111
32112/*
32113** Merge two lists of pages connected by pDirty and in pgno order.
32114** Do not both fixing the pDirtyPrev pointers.
32115*/
32116static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
32117  PgHdr result, *pTail;
32118  pTail = &result;
32119  while( pA && pB ){
32120    if( pA->pgno<pB->pgno ){
32121      pTail->pDirty = pA;
32122      pTail = pA;
32123      pA = pA->pDirty;
32124    }else{
32125      pTail->pDirty = pB;
32126      pTail = pB;
32127      pB = pB->pDirty;
32128    }
32129  }
32130  if( pA ){
32131    pTail->pDirty = pA;
32132  }else if( pB ){
32133    pTail->pDirty = pB;
32134  }else{
32135    pTail->pDirty = 0;
32136  }
32137  return result.pDirty;
32138}
32139
32140/*
32141** Sort the list of pages in accending order by pgno.  Pages are
32142** connected by pDirty pointers.  The pDirtyPrev pointers are
32143** corrupted by this sort.
32144**
32145** Since there cannot be more than 2^31 distinct pages in a database,
32146** there cannot be more than 31 buckets required by the merge sorter.
32147** One extra bucket is added to catch overflow in case something
32148** ever changes to make the previous sentence incorrect.
32149*/
32150#define N_SORT_BUCKET  32
32151static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
32152  PgHdr *a[N_SORT_BUCKET], *p;
32153  int i;
32154  memset(a, 0, sizeof(a));
32155  while( pIn ){
32156    p = pIn;
32157    pIn = p->pDirty;
32158    p->pDirty = 0;
32159    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
32160      if( a[i]==0 ){
32161        a[i] = p;
32162        break;
32163      }else{
32164        p = pcacheMergeDirtyList(a[i], p);
32165        a[i] = 0;
32166      }
32167    }
32168    if( NEVER(i==N_SORT_BUCKET-1) ){
32169      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
32170      ** the input list.  But that is impossible.
32171      */
32172      a[i] = pcacheMergeDirtyList(a[i], p);
32173    }
32174  }
32175  p = a[0];
32176  for(i=1; i<N_SORT_BUCKET; i++){
32177    p = pcacheMergeDirtyList(p, a[i]);
32178  }
32179  return p;
32180}
32181
32182/*
32183** Return a list of all dirty pages in the cache, sorted by page number.
32184*/
32185SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
32186  PgHdr *p;
32187  for(p=pCache->pDirty; p; p=p->pDirtyNext){
32188    p->pDirty = p->pDirtyNext;
32189  }
32190  return pcacheSortDirtyList(pCache->pDirty);
32191}
32192
32193/*
32194** Return the total number of referenced pages held by the cache.
32195*/
32196SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
32197  return pCache->nRef;
32198}
32199
32200/*
32201** Return the number of references to the page supplied as an argument.
32202*/
32203SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
32204  return p->nRef;
32205}
32206
32207/*
32208** Return the total number of pages in the cache.
32209*/
32210SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
32211  int nPage = 0;
32212  if( pCache->pCache ){
32213    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
32214  }
32215  return nPage;
32216}
32217
32218#ifdef SQLITE_TEST
32219/*
32220** Get the suggested cache-size value.
32221*/
32222SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
32223  return pCache->nMax;
32224}
32225#endif
32226
32227/*
32228** Set the suggested cache-size value.
32229*/
32230SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
32231  pCache->nMax = mxPage;
32232  if( pCache->pCache ){
32233    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
32234  }
32235}
32236
32237#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
32238/*
32239** For all dirty pages currently in the cache, invoke the specified
32240** callback. This is only used if the SQLITE_CHECK_PAGES macro is
32241** defined.
32242*/
32243SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
32244  PgHdr *pDirty;
32245  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
32246    xIter(pDirty);
32247  }
32248}
32249#endif
32250
32251/************** End of pcache.c **********************************************/
32252/************** Begin file pcache1.c *****************************************/
32253/*
32254** 2008 November 05
32255**
32256** The author disclaims copyright to this source code.  In place of
32257** a legal notice, here is a blessing:
32258**
32259**    May you do good and not evil.
32260**    May you find forgiveness for yourself and forgive others.
32261**    May you share freely, never taking more than you give.
32262**
32263*************************************************************************
32264**
32265** This file implements the default page cache implementation (the
32266** sqlite3_pcache interface). It also contains part of the implementation
32267** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
32268** If the default page cache implementation is overriden, then neither of
32269** these two features are available.
32270*/
32271
32272
32273typedef struct PCache1 PCache1;
32274typedef struct PgHdr1 PgHdr1;
32275typedef struct PgFreeslot PgFreeslot;
32276
32277/* Pointers to structures of this type are cast and returned as
32278** opaque sqlite3_pcache* handles
32279*/
32280struct PCache1 {
32281  /* Cache configuration parameters. Page size (szPage) and the purgeable
32282  ** flag (bPurgeable) are set when the cache is created. nMax may be
32283  ** modified at any time by a call to the pcache1CacheSize() method.
32284  ** The global mutex must be held when accessing nMax.
32285  */
32286  int szPage;                         /* Size of allocated pages in bytes */
32287  int bPurgeable;                     /* True if cache is purgeable */
32288  unsigned int nMin;                  /* Minimum number of pages reserved */
32289  unsigned int nMax;                  /* Configured "cache_size" value */
32290
32291  /* Hash table of all pages. The following variables may only be accessed
32292  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
32293  ** and pcache1LeaveMutex()).
32294  */
32295  unsigned int nRecyclable;           /* Number of pages in the LRU list */
32296  unsigned int nPage;                 /* Total number of pages in apHash */
32297  unsigned int nHash;                 /* Number of slots in apHash[] */
32298  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
32299
32300  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
32301};
32302
32303/*
32304** Each cache entry is represented by an instance of the following
32305** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
32306** directly before this structure in memory (see the PGHDR1_TO_PAGE()
32307** macro below).
32308*/
32309struct PgHdr1 {
32310  unsigned int iKey;             /* Key value (page number) */
32311  PgHdr1 *pNext;                 /* Next in hash table chain */
32312  PCache1 *pCache;               /* Cache that currently owns this page */
32313  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
32314  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
32315};
32316
32317/*
32318** Free slots in the allocator used to divide up the buffer provided using
32319** the SQLITE_CONFIG_PAGECACHE mechanism.
32320*/
32321struct PgFreeslot {
32322  PgFreeslot *pNext;  /* Next free slot */
32323};
32324
32325/*
32326** Global data used by this cache.
32327*/
32328static SQLITE_WSD struct PCacheGlobal {
32329  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
32330
32331  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
32332  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
32333  int nCurrentPage;                   /* Number of purgeable pages allocated */
32334  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
32335
32336  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
32337  int szSlot;                         /* Size of each free slot */
32338  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
32339  PgFreeslot *pFree;                  /* Free page blocks */
32340  int isInit;                         /* True if initialized */
32341} pcache1_g;
32342
32343/*
32344** All code in this file should access the global structure above via the
32345** alias "pcache1". This ensures that the WSD emulation is used when
32346** compiling for systems that do not support real WSD.
32347*/
32348#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
32349
32350/*
32351** When a PgHdr1 structure is allocated, the associated PCache1.szPage
32352** bytes of data are located directly before it in memory (i.e. the total
32353** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
32354** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
32355** an argument and returns a pointer to the associated block of szPage
32356** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
32357** a pointer to a block of szPage bytes of data and the return value is
32358** a pointer to the associated PgHdr1 structure.
32359**
32360**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
32361*/
32362#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
32363#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
32364
32365/*
32366** Macros to enter and leave the global LRU mutex.
32367*/
32368#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
32369#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
32370
32371/******************************************************************************/
32372/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
32373
32374/*
32375** This function is called during initialization if a static buffer is
32376** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
32377** verb to sqlite3_config(). Parameter pBuf points to an allocation large
32378** enough to contain 'n' buffers of 'sz' bytes each.
32379*/
32380SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
32381  if( pcache1.isInit ){
32382    PgFreeslot *p;
32383    sz = ROUNDDOWN8(sz);
32384    pcache1.szSlot = sz;
32385    pcache1.pStart = pBuf;
32386    pcache1.pFree = 0;
32387    while( n-- ){
32388      p = (PgFreeslot*)pBuf;
32389      p->pNext = pcache1.pFree;
32390      pcache1.pFree = p;
32391      pBuf = (void*)&((char*)pBuf)[sz];
32392    }
32393    pcache1.pEnd = pBuf;
32394  }
32395}
32396
32397/*
32398** Malloc function used within this file to allocate space from the buffer
32399** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
32400** such buffer exists or there is no space left in it, this function falls
32401** back to sqlite3Malloc().
32402*/
32403static void *pcache1Alloc(int nByte){
32404  void *p;
32405  assert( sqlite3_mutex_held(pcache1.mutex) );
32406  if( nByte<=pcache1.szSlot && pcache1.pFree ){
32407    assert( pcache1.isInit );
32408    p = (PgHdr1 *)pcache1.pFree;
32409    pcache1.pFree = pcache1.pFree->pNext;
32410    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
32411    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32412  }else{
32413
32414    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
32415    ** global pcache mutex and unlock the pager-cache object pCache. This is
32416    ** so that if the attempt to allocate a new buffer causes the the
32417    ** configured soft-heap-limit to be breached, it will be possible to
32418    ** reclaim memory from this pager-cache.
32419    */
32420    pcache1LeaveMutex();
32421    p = sqlite3Malloc(nByte);
32422    pcache1EnterMutex();
32423    if( p ){
32424      int sz = sqlite3MallocSize(p);
32425      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
32426    }
32427    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
32428  }
32429  return p;
32430}
32431
32432/*
32433** Free an allocated buffer obtained from pcache1Alloc().
32434*/
32435static void pcache1Free(void *p){
32436  assert( sqlite3_mutex_held(pcache1.mutex) );
32437  if( p==0 ) return;
32438  if( p>=pcache1.pStart && p<pcache1.pEnd ){
32439    PgFreeslot *pSlot;
32440    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
32441    pSlot = (PgFreeslot*)p;
32442    pSlot->pNext = pcache1.pFree;
32443    pcache1.pFree = pSlot;
32444  }else{
32445    int iSize;
32446    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
32447    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
32448    iSize = sqlite3MallocSize(p);
32449    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
32450    sqlite3_free(p);
32451  }
32452}
32453
32454/*
32455** Allocate a new page object initially associated with cache pCache.
32456*/
32457static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
32458  int nByte = sizeof(PgHdr1) + pCache->szPage;
32459  void *pPg = pcache1Alloc(nByte);
32460  PgHdr1 *p;
32461  if( pPg ){
32462    p = PAGE_TO_PGHDR1(pCache, pPg);
32463    if( pCache->bPurgeable ){
32464      pcache1.nCurrentPage++;
32465    }
32466  }else{
32467    p = 0;
32468  }
32469  return p;
32470}
32471
32472/*
32473** Free a page object allocated by pcache1AllocPage().
32474**
32475** The pointer is allowed to be NULL, which is prudent.  But it turns out
32476** that the current implementation happens to never call this routine
32477** with a NULL pointer, so we mark the NULL test with ALWAYS().
32478*/
32479static void pcache1FreePage(PgHdr1 *p){
32480  if( ALWAYS(p) ){
32481    if( p->pCache->bPurgeable ){
32482      pcache1.nCurrentPage--;
32483    }
32484    pcache1Free(PGHDR1_TO_PAGE(p));
32485  }
32486}
32487
32488/*
32489** Malloc function used by SQLite to obtain space from the buffer configured
32490** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
32491** exists, this function falls back to sqlite3Malloc().
32492*/
32493SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
32494  void *p;
32495  pcache1EnterMutex();
32496  p = pcache1Alloc(sz);
32497  pcache1LeaveMutex();
32498  return p;
32499}
32500
32501/*
32502** Free an allocated buffer obtained from sqlite3PageMalloc().
32503*/
32504SQLITE_PRIVATE void sqlite3PageFree(void *p){
32505  pcache1EnterMutex();
32506  pcache1Free(p);
32507  pcache1LeaveMutex();
32508}
32509
32510/******************************************************************************/
32511/******** General Implementation Functions ************************************/
32512
32513/*
32514** This function is used to resize the hash table used by the cache passed
32515** as the first argument.
32516**
32517** The global mutex must be held when this function is called.
32518*/
32519static int pcache1ResizeHash(PCache1 *p){
32520  PgHdr1 **apNew;
32521  unsigned int nNew;
32522  unsigned int i;
32523
32524  assert( sqlite3_mutex_held(pcache1.mutex) );
32525
32526  nNew = p->nHash*2;
32527  if( nNew<256 ){
32528    nNew = 256;
32529  }
32530
32531  pcache1LeaveMutex();
32532  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
32533  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
32534  if( p->nHash ){ sqlite3EndBenignMalloc(); }
32535  pcache1EnterMutex();
32536  if( apNew ){
32537    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
32538    for(i=0; i<p->nHash; i++){
32539      PgHdr1 *pPage;
32540      PgHdr1 *pNext = p->apHash[i];
32541      while( (pPage = pNext)!=0 ){
32542        unsigned int h = pPage->iKey % nNew;
32543        pNext = pPage->pNext;
32544        pPage->pNext = apNew[h];
32545        apNew[h] = pPage;
32546      }
32547    }
32548    sqlite3_free(p->apHash);
32549    p->apHash = apNew;
32550    p->nHash = nNew;
32551  }
32552
32553  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
32554}
32555
32556/*
32557** This function is used internally to remove the page pPage from the
32558** global LRU list, if is part of it. If pPage is not part of the global
32559** LRU list, then this function is a no-op.
32560**
32561** The global mutex must be held when this function is called.
32562*/
32563static void pcache1PinPage(PgHdr1 *pPage){
32564  assert( sqlite3_mutex_held(pcache1.mutex) );
32565  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
32566    if( pPage->pLruPrev ){
32567      pPage->pLruPrev->pLruNext = pPage->pLruNext;
32568    }
32569    if( pPage->pLruNext ){
32570      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
32571    }
32572    if( pcache1.pLruHead==pPage ){
32573      pcache1.pLruHead = pPage->pLruNext;
32574    }
32575    if( pcache1.pLruTail==pPage ){
32576      pcache1.pLruTail = pPage->pLruPrev;
32577    }
32578    pPage->pLruNext = 0;
32579    pPage->pLruPrev = 0;
32580    pPage->pCache->nRecyclable--;
32581  }
32582}
32583
32584
32585/*
32586** Remove the page supplied as an argument from the hash table
32587** (PCache1.apHash structure) that it is currently stored in.
32588**
32589** The global mutex must be held when this function is called.
32590*/
32591static void pcache1RemoveFromHash(PgHdr1 *pPage){
32592  unsigned int h;
32593  PCache1 *pCache = pPage->pCache;
32594  PgHdr1 **pp;
32595
32596  h = pPage->iKey % pCache->nHash;
32597  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
32598  *pp = (*pp)->pNext;
32599
32600  pCache->nPage--;
32601}
32602
32603/*
32604** If there are currently more than pcache.nMaxPage pages allocated, try
32605** to recycle pages to reduce the number allocated to pcache.nMaxPage.
32606*/
32607static void pcache1EnforceMaxPage(void){
32608  assert( sqlite3_mutex_held(pcache1.mutex) );
32609  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
32610    PgHdr1 *p = pcache1.pLruTail;
32611    pcache1PinPage(p);
32612    pcache1RemoveFromHash(p);
32613    pcache1FreePage(p);
32614  }
32615}
32616
32617/*
32618** Discard all pages from cache pCache with a page number (key value)
32619** greater than or equal to iLimit. Any pinned pages that meet this
32620** criteria are unpinned before they are discarded.
32621**
32622** The global mutex must be held when this function is called.
32623*/
32624static void pcache1TruncateUnsafe(
32625  PCache1 *pCache,
32626  unsigned int iLimit
32627){
32628  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
32629  unsigned int h;
32630  assert( sqlite3_mutex_held(pcache1.mutex) );
32631  for(h=0; h<pCache->nHash; h++){
32632    PgHdr1 **pp = &pCache->apHash[h];
32633    PgHdr1 *pPage;
32634    while( (pPage = *pp)!=0 ){
32635      if( pPage->iKey>=iLimit ){
32636        pCache->nPage--;
32637        *pp = pPage->pNext;
32638        pcache1PinPage(pPage);
32639        pcache1FreePage(pPage);
32640      }else{
32641        pp = &pPage->pNext;
32642        TESTONLY( nPage++; )
32643      }
32644    }
32645  }
32646  assert( pCache->nPage==nPage );
32647}
32648
32649/******************************************************************************/
32650/******** sqlite3_pcache Methods **********************************************/
32651
32652/*
32653** Implementation of the sqlite3_pcache.xInit method.
32654*/
32655static int pcache1Init(void *NotUsed){
32656  UNUSED_PARAMETER(NotUsed);
32657  assert( pcache1.isInit==0 );
32658  memset(&pcache1, 0, sizeof(pcache1));
32659  if( sqlite3GlobalConfig.bCoreMutex ){
32660    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
32661  }
32662  pcache1.isInit = 1;
32663  return SQLITE_OK;
32664}
32665
32666/*
32667** Implementation of the sqlite3_pcache.xShutdown method.
32668** Note that the static mutex allocated in xInit does
32669** not need to be freed.
32670*/
32671static void pcache1Shutdown(void *NotUsed){
32672  UNUSED_PARAMETER(NotUsed);
32673  assert( pcache1.isInit!=0 );
32674  memset(&pcache1, 0, sizeof(pcache1));
32675}
32676
32677/*
32678** Implementation of the sqlite3_pcache.xCreate method.
32679**
32680** Allocate a new cache.
32681*/
32682static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
32683  PCache1 *pCache;
32684
32685  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
32686  if( pCache ){
32687    memset(pCache, 0, sizeof(PCache1));
32688    pCache->szPage = szPage;
32689    pCache->bPurgeable = (bPurgeable ? 1 : 0);
32690    if( bPurgeable ){
32691      pCache->nMin = 10;
32692      pcache1EnterMutex();
32693      pcache1.nMinPage += pCache->nMin;
32694      pcache1LeaveMutex();
32695    }
32696  }
32697  return (sqlite3_pcache *)pCache;
32698}
32699
32700/*
32701** Implementation of the sqlite3_pcache.xCachesize method.
32702**
32703** Configure the cache_size limit for a cache.
32704*/
32705static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
32706  PCache1 *pCache = (PCache1 *)p;
32707  if( pCache->bPurgeable ){
32708    pcache1EnterMutex();
32709    pcache1.nMaxPage += (nMax - pCache->nMax);
32710    pCache->nMax = nMax;
32711    pcache1EnforceMaxPage();
32712    pcache1LeaveMutex();
32713  }
32714}
32715
32716/*
32717** Implementation of the sqlite3_pcache.xPagecount method.
32718*/
32719static int pcache1Pagecount(sqlite3_pcache *p){
32720  int n;
32721  pcache1EnterMutex();
32722  n = ((PCache1 *)p)->nPage;
32723  pcache1LeaveMutex();
32724  return n;
32725}
32726
32727/*
32728** Implementation of the sqlite3_pcache.xFetch method.
32729**
32730** Fetch a page by key value.
32731**
32732** Whether or not a new page may be allocated by this function depends on
32733** the value of the createFlag argument.  0 means do not allocate a new
32734** page.  1 means allocate a new page if space is easily available.  2
32735** means to try really hard to allocate a new page.
32736**
32737** For a non-purgeable cache (a cache used as the storage for an in-memory
32738** database) there is really no difference between createFlag 1 and 2.  So
32739** the calling function (pcache.c) will never have a createFlag of 1 on
32740** a non-purgable cache.
32741**
32742** There are three different approaches to obtaining space for a page,
32743** depending on the value of parameter createFlag (which may be 0, 1 or 2).
32744**
32745**   1. Regardless of the value of createFlag, the cache is searched for a
32746**      copy of the requested page. If one is found, it is returned.
32747**
32748**   2. If createFlag==0 and the page is not already in the cache, NULL is
32749**      returned.
32750**
32751**   3. If createFlag is 1, and the page is not already in the cache,
32752**      and if either of the following are true, return NULL:
32753**
32754**       (a) the number of pages pinned by the cache is greater than
32755**           PCache1.nMax, or
32756**       (b) the number of pages pinned by the cache is greater than
32757**           the sum of nMax for all purgeable caches, less the sum of
32758**           nMin for all other purgeable caches.
32759**
32760**   4. If none of the first three conditions apply and the cache is marked
32761**      as purgeable, and if one of the following is true:
32762**
32763**       (a) The number of pages allocated for the cache is already
32764**           PCache1.nMax, or
32765**
32766**       (b) The number of pages allocated for all purgeable caches is
32767**           already equal to or greater than the sum of nMax for all
32768**           purgeable caches,
32769**
32770**      then attempt to recycle a page from the LRU list. If it is the right
32771**      size, return the recycled buffer. Otherwise, free the buffer and
32772**      proceed to step 5.
32773**
32774**   5. Otherwise, allocate and return a new page buffer.
32775*/
32776static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
32777  unsigned int nPinned;
32778  PCache1 *pCache = (PCache1 *)p;
32779  PgHdr1 *pPage = 0;
32780
32781  assert( pCache->bPurgeable || createFlag!=1 );
32782  pcache1EnterMutex();
32783  if( createFlag==1 ) sqlite3BeginBenignMalloc();
32784
32785  /* Search the hash table for an existing entry. */
32786  if( pCache->nHash>0 ){
32787    unsigned int h = iKey % pCache->nHash;
32788    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
32789  }
32790
32791  if( pPage || createFlag==0 ){
32792    pcache1PinPage(pPage);
32793    goto fetch_out;
32794  }
32795
32796  /* Step 3 of header comment. */
32797  nPinned = pCache->nPage - pCache->nRecyclable;
32798  if( createFlag==1 && (
32799        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
32800     || nPinned>=(pCache->nMax * 9 / 10)
32801  )){
32802    goto fetch_out;
32803  }
32804
32805  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
32806    goto fetch_out;
32807  }
32808
32809  /* Step 4. Try to recycle a page buffer if appropriate. */
32810  if( pCache->bPurgeable && pcache1.pLruTail && (
32811     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
32812  )){
32813    pPage = pcache1.pLruTail;
32814    pcache1RemoveFromHash(pPage);
32815    pcache1PinPage(pPage);
32816    if( pPage->pCache->szPage!=pCache->szPage ){
32817      pcache1FreePage(pPage);
32818      pPage = 0;
32819    }else{
32820      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
32821    }
32822  }
32823
32824  /* Step 5. If a usable page buffer has still not been found,
32825  ** attempt to allocate a new one.
32826  */
32827  if( !pPage ){
32828    pPage = pcache1AllocPage(pCache);
32829  }
32830
32831  if( pPage ){
32832    unsigned int h = iKey % pCache->nHash;
32833    pCache->nPage++;
32834    pPage->iKey = iKey;
32835    pPage->pNext = pCache->apHash[h];
32836    pPage->pCache = pCache;
32837    pPage->pLruPrev = 0;
32838    pPage->pLruNext = 0;
32839    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
32840    pCache->apHash[h] = pPage;
32841  }
32842
32843fetch_out:
32844  if( pPage && iKey>pCache->iMaxKey ){
32845    pCache->iMaxKey = iKey;
32846  }
32847  if( createFlag==1 ) sqlite3EndBenignMalloc();
32848  pcache1LeaveMutex();
32849  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
32850}
32851
32852
32853/*
32854** Implementation of the sqlite3_pcache.xUnpin method.
32855**
32856** Mark a page as unpinned (eligible for asynchronous recycling).
32857*/
32858static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
32859  PCache1 *pCache = (PCache1 *)p;
32860  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
32861
32862  assert( pPage->pCache==pCache );
32863  pcache1EnterMutex();
32864
32865  /* It is an error to call this function if the page is already
32866  ** part of the global LRU list.
32867  */
32868  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
32869  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
32870
32871  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
32872    pcache1RemoveFromHash(pPage);
32873    pcache1FreePage(pPage);
32874  }else{
32875    /* Add the page to the global LRU list. Normally, the page is added to
32876    ** the head of the list (last page to be recycled). However, if the
32877    ** reuseUnlikely flag passed to this function is true, the page is added
32878    ** to the tail of the list (first page to be recycled).
32879    */
32880    if( pcache1.pLruHead ){
32881      pcache1.pLruHead->pLruPrev = pPage;
32882      pPage->pLruNext = pcache1.pLruHead;
32883      pcache1.pLruHead = pPage;
32884    }else{
32885      pcache1.pLruTail = pPage;
32886      pcache1.pLruHead = pPage;
32887    }
32888    pCache->nRecyclable++;
32889  }
32890
32891  pcache1LeaveMutex();
32892}
32893
32894/*
32895** Implementation of the sqlite3_pcache.xRekey method.
32896*/
32897static void pcache1Rekey(
32898  sqlite3_pcache *p,
32899  void *pPg,
32900  unsigned int iOld,
32901  unsigned int iNew
32902){
32903  PCache1 *pCache = (PCache1 *)p;
32904  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
32905  PgHdr1 **pp;
32906  unsigned int h;
32907  assert( pPage->iKey==iOld );
32908  assert( pPage->pCache==pCache );
32909
32910  pcache1EnterMutex();
32911
32912  h = iOld%pCache->nHash;
32913  pp = &pCache->apHash[h];
32914  while( (*pp)!=pPage ){
32915    pp = &(*pp)->pNext;
32916  }
32917  *pp = pPage->pNext;
32918
32919  h = iNew%pCache->nHash;
32920  pPage->iKey = iNew;
32921  pPage->pNext = pCache->apHash[h];
32922  pCache->apHash[h] = pPage;
32923  if( iNew>pCache->iMaxKey ){
32924    pCache->iMaxKey = iNew;
32925  }
32926
32927  pcache1LeaveMutex();
32928}
32929
32930/*
32931** Implementation of the sqlite3_pcache.xTruncate method.
32932**
32933** Discard all unpinned pages in the cache with a page number equal to
32934** or greater than parameter iLimit. Any pinned pages with a page number
32935** equal to or greater than iLimit are implicitly unpinned.
32936*/
32937static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
32938  PCache1 *pCache = (PCache1 *)p;
32939  pcache1EnterMutex();
32940  if( iLimit<=pCache->iMaxKey ){
32941    pcache1TruncateUnsafe(pCache, iLimit);
32942    pCache->iMaxKey = iLimit-1;
32943  }
32944  pcache1LeaveMutex();
32945}
32946
32947/*
32948** Implementation of the sqlite3_pcache.xDestroy method.
32949**
32950** Destroy a cache allocated using pcache1Create().
32951*/
32952static void pcache1Destroy(sqlite3_pcache *p){
32953  PCache1 *pCache = (PCache1 *)p;
32954  pcache1EnterMutex();
32955  pcache1TruncateUnsafe(pCache, 0);
32956  pcache1.nMaxPage -= pCache->nMax;
32957  pcache1.nMinPage -= pCache->nMin;
32958  pcache1EnforceMaxPage();
32959  pcache1LeaveMutex();
32960  sqlite3_free(pCache->apHash);
32961  sqlite3_free(pCache);
32962}
32963
32964/*
32965** This function is called during initialization (sqlite3_initialize()) to
32966** install the default pluggable cache module, assuming the user has not
32967** already provided an alternative.
32968*/
32969SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
32970  static const sqlite3_pcache_methods defaultMethods = {
32971    0,                       /* pArg */
32972    pcache1Init,             /* xInit */
32973    pcache1Shutdown,         /* xShutdown */
32974    pcache1Create,           /* xCreate */
32975    pcache1Cachesize,        /* xCachesize */
32976    pcache1Pagecount,        /* xPagecount */
32977    pcache1Fetch,            /* xFetch */
32978    pcache1Unpin,            /* xUnpin */
32979    pcache1Rekey,            /* xRekey */
32980    pcache1Truncate,         /* xTruncate */
32981    pcache1Destroy           /* xDestroy */
32982  };
32983  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
32984}
32985
32986#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
32987/*
32988** This function is called to free superfluous dynamically allocated memory
32989** held by the pager system. Memory in use by any SQLite pager allocated
32990** by the current thread may be sqlite3_free()ed.
32991**
32992** nReq is the number of bytes of memory required. Once this much has
32993** been released, the function returns. The return value is the total number
32994** of bytes of memory released.
32995*/
32996SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
32997  int nFree = 0;
32998  if( pcache1.pStart==0 ){
32999    PgHdr1 *p;
33000    pcache1EnterMutex();
33001    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
33002      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
33003      pcache1PinPage(p);
33004      pcache1RemoveFromHash(p);
33005      pcache1FreePage(p);
33006    }
33007    pcache1LeaveMutex();
33008  }
33009  return nFree;
33010}
33011#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33012
33013#ifdef SQLITE_TEST
33014/*
33015** This function is used by test procedures to inspect the internal state
33016** of the global cache.
33017*/
33018SQLITE_PRIVATE void sqlite3PcacheStats(
33019  int *pnCurrent,      /* OUT: Total number of pages cached */
33020  int *pnMax,          /* OUT: Global maximum cache size */
33021  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
33022  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
33023){
33024  PgHdr1 *p;
33025  int nRecyclable = 0;
33026  for(p=pcache1.pLruHead; p; p=p->pLruNext){
33027    nRecyclable++;
33028  }
33029  *pnCurrent = pcache1.nCurrentPage;
33030  *pnMax = pcache1.nMaxPage;
33031  *pnMin = pcache1.nMinPage;
33032  *pnRecyclable = nRecyclable;
33033}
33034#endif
33035
33036/************** End of pcache1.c *********************************************/
33037/************** Begin file rowset.c ******************************************/
33038/*
33039** 2008 December 3
33040**
33041** The author disclaims copyright to this source code.  In place of
33042** a legal notice, here is a blessing:
33043**
33044**    May you do good and not evil.
33045**    May you find forgiveness for yourself and forgive others.
33046**    May you share freely, never taking more than you give.
33047**
33048*************************************************************************
33049**
33050** This module implements an object we call a "RowSet".
33051**
33052** The RowSet object is a collection of rowids.  Rowids
33053** are inserted into the RowSet in an arbitrary order.  Inserts
33054** can be intermixed with tests to see if a given rowid has been
33055** previously inserted into the RowSet.
33056**
33057** After all inserts are finished, it is possible to extract the
33058** elements of the RowSet in sorted order.  Once this extraction
33059** process has started, no new elements may be inserted.
33060**
33061** Hence, the primitive operations for a RowSet are:
33062**
33063**    CREATE
33064**    INSERT
33065**    TEST
33066**    SMALLEST
33067**    DESTROY
33068**
33069** The CREATE and DESTROY primitives are the constructor and destructor,
33070** obviously.  The INSERT primitive adds a new element to the RowSet.
33071** TEST checks to see if an element is already in the RowSet.  SMALLEST
33072** extracts the least value from the RowSet.
33073**
33074** The INSERT primitive might allocate additional memory.  Memory is
33075** allocated in chunks so most INSERTs do no allocation.  There is an
33076** upper bound on the size of allocated memory.  No memory is freed
33077** until DESTROY.
33078**
33079** The TEST primitive includes a "batch" number.  The TEST primitive
33080** will only see elements that were inserted before the last change
33081** in the batch number.  In other words, if an INSERT occurs between
33082** two TESTs where the TESTs have the same batch nubmer, then the
33083** value added by the INSERT will not be visible to the second TEST.
33084** The initial batch number is zero, so if the very first TEST contains
33085** a non-zero batch number, it will see all prior INSERTs.
33086**
33087** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
33088** that is attempted.
33089**
33090** The cost of an INSERT is roughly constant.  (Sometime new memory
33091** has to be allocated on an INSERT.)  The cost of a TEST with a new
33092** batch number is O(NlogN) where N is the number of elements in the RowSet.
33093** The cost of a TEST using the same batch number is O(logN).  The cost
33094** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
33095** primitives are constant time.  The cost of DESTROY is O(N).
33096**
33097** There is an added cost of O(N) when switching between TEST and
33098** SMALLEST primitives.
33099*/
33100
33101
33102/*
33103** Target size for allocation chunks.
33104*/
33105#define ROWSET_ALLOCATION_SIZE 1024
33106
33107/*
33108** The number of rowset entries per allocation chunk.
33109*/
33110#define ROWSET_ENTRY_PER_CHUNK  \
33111                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
33112
33113/*
33114** Each entry in a RowSet is an instance of the following object.
33115*/
33116struct RowSetEntry {
33117  i64 v;                        /* ROWID value for this entry */
33118  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
33119  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
33120};
33121
33122/*
33123** RowSetEntry objects are allocated in large chunks (instances of the
33124** following structure) to reduce memory allocation overhead.  The
33125** chunks are kept on a linked list so that they can be deallocated
33126** when the RowSet is destroyed.
33127*/
33128struct RowSetChunk {
33129  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
33130  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
33131};
33132
33133/*
33134** A RowSet in an instance of the following structure.
33135**
33136** A typedef of this structure if found in sqliteInt.h.
33137*/
33138struct RowSet {
33139  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
33140  sqlite3 *db;                   /* The database connection */
33141  struct RowSetEntry *pEntry;    /* List of entries using pRight */
33142  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
33143  struct RowSetEntry *pFresh;    /* Source of new entry objects */
33144  struct RowSetEntry *pTree;     /* Binary tree of entries */
33145  u16 nFresh;                    /* Number of objects on pFresh */
33146  u8 isSorted;                   /* True if pEntry is sorted */
33147  u8 iBatch;                     /* Current insert batch */
33148};
33149
33150/*
33151** Turn bulk memory into a RowSet object.  N bytes of memory
33152** are available at pSpace.  The db pointer is used as a memory context
33153** for any subsequent allocations that need to occur.
33154** Return a pointer to the new RowSet object.
33155**
33156** It must be the case that N is sufficient to make a Rowset.  If not
33157** an assertion fault occurs.
33158**
33159** If N is larger than the minimum, use the surplus as an initial
33160** allocation of entries available to be filled.
33161*/
33162SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
33163  RowSet *p;
33164  assert( N >= ROUND8(sizeof(*p)) );
33165  p = pSpace;
33166  p->pChunk = 0;
33167  p->db = db;
33168  p->pEntry = 0;
33169  p->pLast = 0;
33170  p->pTree = 0;
33171  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
33172  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
33173  p->isSorted = 1;
33174  p->iBatch = 0;
33175  return p;
33176}
33177
33178/*
33179** Deallocate all chunks from a RowSet.  This frees all memory that
33180** the RowSet has allocated over its lifetime.  This routine is
33181** the destructor for the RowSet.
33182*/
33183SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
33184  struct RowSetChunk *pChunk, *pNextChunk;
33185  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
33186    pNextChunk = pChunk->pNextChunk;
33187    sqlite3DbFree(p->db, pChunk);
33188  }
33189  p->pChunk = 0;
33190  p->nFresh = 0;
33191  p->pEntry = 0;
33192  p->pLast = 0;
33193  p->pTree = 0;
33194  p->isSorted = 1;
33195}
33196
33197/*
33198** Insert a new value into a RowSet.
33199**
33200** The mallocFailed flag of the database connection is set if a
33201** memory allocation fails.
33202*/
33203SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
33204  struct RowSetEntry *pEntry;  /* The new entry */
33205  struct RowSetEntry *pLast;   /* The last prior entry */
33206  assert( p!=0 );
33207  if( p->nFresh==0 ){
33208    struct RowSetChunk *pNew;
33209    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
33210    if( pNew==0 ){
33211      return;
33212    }
33213    pNew->pNextChunk = p->pChunk;
33214    p->pChunk = pNew;
33215    p->pFresh = pNew->aEntry;
33216    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
33217  }
33218  pEntry = p->pFresh++;
33219  p->nFresh--;
33220  pEntry->v = rowid;
33221  pEntry->pRight = 0;
33222  pLast = p->pLast;
33223  if( pLast ){
33224    if( p->isSorted && rowid<=pLast->v ){
33225      p->isSorted = 0;
33226    }
33227    pLast->pRight = pEntry;
33228  }else{
33229    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
33230    p->pEntry = pEntry;
33231  }
33232  p->pLast = pEntry;
33233}
33234
33235/*
33236** Merge two lists of RowSetEntry objects.  Remove duplicates.
33237**
33238** The input lists are connected via pRight pointers and are
33239** assumed to each already be in sorted order.
33240*/
33241static struct RowSetEntry *rowSetMerge(
33242  struct RowSetEntry *pA,    /* First sorted list to be merged */
33243  struct RowSetEntry *pB     /* Second sorted list to be merged */
33244){
33245  struct RowSetEntry head;
33246  struct RowSetEntry *pTail;
33247
33248  pTail = &head;
33249  while( pA && pB ){
33250    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33251    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
33252    if( pA->v<pB->v ){
33253      pTail->pRight = pA;
33254      pA = pA->pRight;
33255      pTail = pTail->pRight;
33256    }else if( pB->v<pA->v ){
33257      pTail->pRight = pB;
33258      pB = pB->pRight;
33259      pTail = pTail->pRight;
33260    }else{
33261      pA = pA->pRight;
33262    }
33263  }
33264  if( pA ){
33265    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33266    pTail->pRight = pA;
33267  }else{
33268    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
33269    pTail->pRight = pB;
33270  }
33271  return head.pRight;
33272}
33273
33274/*
33275** Sort all elements on the pEntry list of the RowSet into ascending order.
33276*/
33277static void rowSetSort(RowSet *p){
33278  unsigned int i;
33279  struct RowSetEntry *pEntry;
33280  struct RowSetEntry *aBucket[40];
33281
33282  assert( p->isSorted==0 );
33283  memset(aBucket, 0, sizeof(aBucket));
33284  while( p->pEntry ){
33285    pEntry = p->pEntry;
33286    p->pEntry = pEntry->pRight;
33287    pEntry->pRight = 0;
33288    for(i=0; aBucket[i]; i++){
33289      pEntry = rowSetMerge(aBucket[i], pEntry);
33290      aBucket[i] = 0;
33291    }
33292    aBucket[i] = pEntry;
33293  }
33294  pEntry = 0;
33295  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
33296    pEntry = rowSetMerge(pEntry, aBucket[i]);
33297  }
33298  p->pEntry = pEntry;
33299  p->pLast = 0;
33300  p->isSorted = 1;
33301}
33302
33303
33304/*
33305** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
33306** Convert this tree into a linked list connected by the pRight pointers
33307** and return pointers to the first and last elements of the new list.
33308*/
33309static void rowSetTreeToList(
33310  struct RowSetEntry *pIn,         /* Root of the input tree */
33311  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
33312  struct RowSetEntry **ppLast      /* Write tail of the output list here */
33313){
33314  assert( pIn!=0 );
33315  if( pIn->pLeft ){
33316    struct RowSetEntry *p;
33317    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
33318    p->pRight = pIn;
33319  }else{
33320    *ppFirst = pIn;
33321  }
33322  if( pIn->pRight ){
33323    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
33324  }else{
33325    *ppLast = pIn;
33326  }
33327  assert( (*ppLast)->pRight==0 );
33328}
33329
33330
33331/*
33332** Convert a sorted list of elements (connected by pRight) into a binary
33333** tree with depth of iDepth.  A depth of 1 means the tree contains a single
33334** node taken from the head of *ppList.  A depth of 2 means a tree with
33335** three nodes.  And so forth.
33336**
33337** Use as many entries from the input list as required and update the
33338** *ppList to point to the unused elements of the list.  If the input
33339** list contains too few elements, then construct an incomplete tree
33340** and leave *ppList set to NULL.
33341**
33342** Return a pointer to the root of the constructed binary tree.
33343*/
33344static struct RowSetEntry *rowSetNDeepTree(
33345  struct RowSetEntry **ppList,
33346  int iDepth
33347){
33348  struct RowSetEntry *p;         /* Root of the new tree */
33349  struct RowSetEntry *pLeft;     /* Left subtree */
33350  if( *ppList==0 ){
33351    return 0;
33352  }
33353  if( iDepth==1 ){
33354    p = *ppList;
33355    *ppList = p->pRight;
33356    p->pLeft = p->pRight = 0;
33357    return p;
33358  }
33359  pLeft = rowSetNDeepTree(ppList, iDepth-1);
33360  p = *ppList;
33361  if( p==0 ){
33362    return pLeft;
33363  }
33364  p->pLeft = pLeft;
33365  *ppList = p->pRight;
33366  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
33367  return p;
33368}
33369
33370/*
33371** Convert a sorted list of elements into a binary tree. Make the tree
33372** as deep as it needs to be in order to contain the entire list.
33373*/
33374static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
33375  int iDepth;           /* Depth of the tree so far */
33376  struct RowSetEntry *p;       /* Current tree root */
33377  struct RowSetEntry *pLeft;   /* Left subtree */
33378
33379  assert( pList!=0 );
33380  p = pList;
33381  pList = p->pRight;
33382  p->pLeft = p->pRight = 0;
33383  for(iDepth=1; pList; iDepth++){
33384    pLeft = p;
33385    p = pList;
33386    pList = p->pRight;
33387    p->pLeft = pLeft;
33388    p->pRight = rowSetNDeepTree(&pList, iDepth);
33389  }
33390  return p;
33391}
33392
33393/*
33394** Convert the list in p->pEntry into a sorted list if it is not
33395** sorted already.  If there is a binary tree on p->pTree, then
33396** convert it into a list too and merge it into the p->pEntry list.
33397*/
33398static void rowSetToList(RowSet *p){
33399  if( !p->isSorted ){
33400    rowSetSort(p);
33401  }
33402  if( p->pTree ){
33403    struct RowSetEntry *pHead, *pTail;
33404    rowSetTreeToList(p->pTree, &pHead, &pTail);
33405    p->pTree = 0;
33406    p->pEntry = rowSetMerge(p->pEntry, pHead);
33407  }
33408}
33409
33410/*
33411** Extract the smallest element from the RowSet.
33412** Write the element into *pRowid.  Return 1 on success.  Return
33413** 0 if the RowSet is already empty.
33414**
33415** After this routine has been called, the sqlite3RowSetInsert()
33416** routine may not be called again.
33417*/
33418SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
33419  rowSetToList(p);
33420  if( p->pEntry ){
33421    *pRowid = p->pEntry->v;
33422    p->pEntry = p->pEntry->pRight;
33423    if( p->pEntry==0 ){
33424      sqlite3RowSetClear(p);
33425    }
33426    return 1;
33427  }else{
33428    return 0;
33429  }
33430}
33431
33432/*
33433** Check to see if element iRowid was inserted into the the rowset as
33434** part of any insert batch prior to iBatch.  Return 1 or 0.
33435*/
33436SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
33437  struct RowSetEntry *p;
33438  if( iBatch!=pRowSet->iBatch ){
33439    if( pRowSet->pEntry ){
33440      rowSetToList(pRowSet);
33441      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
33442      pRowSet->pEntry = 0;
33443      pRowSet->pLast = 0;
33444    }
33445    pRowSet->iBatch = iBatch;
33446  }
33447  p = pRowSet->pTree;
33448  while( p ){
33449    if( p->v<iRowid ){
33450      p = p->pRight;
33451    }else if( p->v>iRowid ){
33452      p = p->pLeft;
33453    }else{
33454      return 1;
33455    }
33456  }
33457  return 0;
33458}
33459
33460/************** End of rowset.c **********************************************/
33461/************** Begin file pager.c *******************************************/
33462/*
33463** 2001 September 15
33464**
33465** The author disclaims copyright to this source code.  In place of
33466** a legal notice, here is a blessing:
33467**
33468**    May you do good and not evil.
33469**    May you find forgiveness for yourself and forgive others.
33470**    May you share freely, never taking more than you give.
33471**
33472*************************************************************************
33473** This is the implementation of the page cache subsystem or "pager".
33474**
33475** The pager is used to access a database disk file.  It implements
33476** atomic commit and rollback through the use of a journal file that
33477** is separate from the database file.  The pager also implements file
33478** locking to prevent two processes from writing the same database
33479** file simultaneously, or one process from reading the database while
33480** another is writing.
33481*/
33482#ifndef SQLITE_OMIT_DISKIO
33483/************** Include wal.h in the middle of pager.c ***********************/
33484/************** Begin file wal.h *********************************************/
33485/*
33486** 2010 February 1
33487**
33488** The author disclaims copyright to this source code.  In place of
33489** a legal notice, here is a blessing:
33490**
33491**    May you do good and not evil.
33492**    May you find forgiveness for yourself and forgive others.
33493**    May you share freely, never taking more than you give.
33494**
33495*************************************************************************
33496** This header file defines the interface to the write-ahead logging
33497** system. Refer to the comments below and the header comment attached to
33498** the implementation of each function in log.c for further details.
33499*/
33500
33501#ifndef _WAL_H_
33502#define _WAL_H_
33503
33504
33505#ifdef SQLITE_OMIT_WAL
33506# define sqlite3WalOpen(x,y,z)                 0
33507# define sqlite3WalClose(w,x,y,z)              0
33508# define sqlite3WalBeginReadTransaction(y,z)   0
33509# define sqlite3WalEndReadTransaction(z)
33510# define sqlite3WalRead(v,w,x,y,z)             0
33511# define sqlite3WalDbsize(y,z)
33512# define sqlite3WalBeginWriteTransaction(y)    0
33513# define sqlite3WalEndWRiteTransaction(x)      0
33514# define sqlite3WalUndo(x,y,z)                 0
33515# define sqlite3WalSavepoint(y,z)
33516# define sqlite3WalSavepointUndo(y,z)          0
33517# define sqlite3WalFrames(u,v,w,x,y,z)         0
33518# define sqlite3WalCheckpoint(u,v,w,x)         0
33519# define sqlite3WalCallback(z)                 0
33520#else
33521
33522#define WAL_SAVEPOINT_NDATA 4
33523
33524/* Connection to a write-ahead log (WAL) file.
33525** There is one object of this type for each pager.
33526*/
33527typedef struct Wal Wal;
33528
33529/* Open and close a connection to a write-ahead log. */
33530SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
33531SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
33532
33533/* Used by readers to open (lock) and close (unlock) a snapshot.  A
33534** snapshot is like a read-transaction.  It is the state of the database
33535** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
33536** preserves the current state even if the other threads or processes
33537** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
33538** transaction and releases the lock.
33539*/
33540SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
33541SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
33542
33543/* Read a page from the write-ahead log, if it is present. */
33544SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
33545
33546/* Return the size of the database as it existed at the beginning
33547** of the snapshot */
33548SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno);
33549
33550/* Obtain or release the WRITER lock. */
33551SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
33552SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
33553
33554/* Undo any frames written (but not committed) to the log */
33555SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
33556
33557/* Return an integer that records the current (uncommitted) write
33558** position in the WAL */
33559SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
33560
33561/* Move the write position of the WAL back to iFrame.  Called in
33562** response to a ROLLBACK TO command. */
33563SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
33564
33565/* Write a frame or frames to the log. */
33566SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
33567
33568/* Copy pages from the log to the database file */
33569SQLITE_PRIVATE int sqlite3WalCheckpoint(
33570  Wal *pWal,                      /* Write-ahead log connection */
33571  int sync_flags,                 /* Flags to sync db file with (or 0) */
33572  int nBuf,                       /* Size of buffer nBuf */
33573  u8 *zBuf                        /* Temporary buffer to use */
33574);
33575
33576/* Return the value to pass to a sqlite3_wal_hook callback, the
33577** number of frames in the WAL at the point of the last commit since
33578** sqlite3WalCallback() was called.  If no commits have occurred since
33579** the last call, then return 0.
33580*/
33581SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
33582
33583/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
33584** by the pager layer on the database file.
33585*/
33586SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
33587
33588#endif /* ifndef SQLITE_OMIT_WAL */
33589#endif /* _WAL_H_ */
33590
33591/************** End of wal.h *************************************************/
33592/************** Continuing where we left off in pager.c **********************/
33593
33594/*
33595******************** NOTES ON THE DESIGN OF THE PAGER ************************
33596**
33597** Within this comment block, a page is deemed to have been synced
33598** automatically as soon as it is written when PRAGMA synchronous=OFF.
33599** Otherwise, the page is not synced until the xSync method of the VFS
33600** is called successfully on the file containing the page.
33601**
33602** Definition:  A page of the database file is said to be "overwriteable" if
33603** one or more of the following are true about the page:
33604**
33605**     (a)  The original content of the page as it was at the beginning of
33606**          the transaction has been written into the rollback journal and
33607**          synced.
33608**
33609**     (b)  The page was a freelist leaf page at the start of the transaction.
33610**
33611**     (c)  The page number is greater than the largest page that existed in
33612**          the database file at the start of the transaction.
33613**
33614** (1) A page of the database file is never overwritten unless one of the
33615**     following are true:
33616**
33617**     (a) The page and all other pages on the same sector are overwriteable.
33618**
33619**     (b) The atomic page write optimization is enabled, and the entire
33620**         transaction other than the update of the transaction sequence
33621**         number consists of a single page change.
33622**
33623** (2) The content of a page written into the rollback journal exactly matches
33624**     both the content in the database when the rollback journal was written
33625**     and the content in the database at the beginning of the current
33626**     transaction.
33627**
33628** (3) Writes to the database file are an integer multiple of the page size
33629**     in length and are aligned to a page boundary.
33630**
33631** (4) Reads from the database file are either aligned on a page boundary and
33632**     an integer multiple of the page size in length or are taken from the
33633**     first 100 bytes of the database file.
33634**
33635** (5) All writes to the database file are synced prior to the rollback journal
33636**     being deleted, truncated, or zeroed.
33637**
33638** (6) If a master journal file is used, then all writes to the database file
33639**     are synced prior to the master journal being deleted.
33640**
33641** Definition: Two databases (or the same database at two points it time)
33642** are said to be "logically equivalent" if they give the same answer to
33643** all queries.  Note in particular the the content of freelist leaf
33644** pages can be changed arbitarily without effecting the logical equivalence
33645** of the database.
33646**
33647** (7) At any time, if any subset, including the empty set and the total set,
33648**     of the unsynced changes to a rollback journal are removed and the
33649**     journal is rolled back, the resulting database file will be logical
33650**     equivalent to the database file at the beginning of the transaction.
33651**
33652** (8) When a transaction is rolled back, the xTruncate method of the VFS
33653**     is called to restore the database file to the same size it was at
33654**     the beginning of the transaction.  (In some VFSes, the xTruncate
33655**     method is a no-op, but that does not change the fact the SQLite will
33656**     invoke it.)
33657**
33658** (9) Whenever the database file is modified, at least one bit in the range
33659**     of bytes from 24 through 39 inclusive will be changed prior to releasing
33660**     the EXCLUSIVE lock.
33661**
33662** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
33663**      than one billion transactions.
33664**
33665** (11) A database file is well-formed at the beginning and at the conclusion
33666**      of every transaction.
33667**
33668** (12) An EXCLUSIVE lock is held on the database file when writing to
33669**      the database file.
33670**
33671** (13) A SHARED lock is held on the database file while reading any
33672**      content out of the database file.
33673*/
33674
33675/*
33676** Macros for troubleshooting.  Normally turned off
33677*/
33678#if 0
33679int sqlite3PagerTrace=1;  /* True to enable tracing */
33680#define sqlite3DebugPrintf printf
33681#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
33682#else
33683#define PAGERTRACE(X)
33684#endif
33685
33686/*
33687** The following two macros are used within the PAGERTRACE() macros above
33688** to print out file-descriptors.
33689**
33690** PAGERID() takes a pointer to a Pager struct as its argument. The
33691** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
33692** struct as its argument.
33693*/
33694#define PAGERID(p) ((int)(p->fd))
33695#define FILEHANDLEID(fd) ((int)fd)
33696
33697/*
33698** The page cache as a whole is always in one of the following
33699** states:
33700**
33701**   PAGER_UNLOCK        The page cache is not currently reading or
33702**                       writing the database file.  There is no
33703**                       data held in memory.  This is the initial
33704**                       state.
33705**
33706**   PAGER_SHARED        The page cache is reading the database.
33707**                       Writing is not permitted.  There can be
33708**                       multiple readers accessing the same database
33709**                       file at the same time.
33710**
33711**   PAGER_RESERVED      This process has reserved the database for writing
33712**                       but has not yet made any changes.  Only one process
33713**                       at a time can reserve the database.  The original
33714**                       database file has not been modified so other
33715**                       processes may still be reading the on-disk
33716**                       database file.
33717**
33718**   PAGER_EXCLUSIVE     The page cache is writing the database.
33719**                       Access is exclusive.  No other processes or
33720**                       threads can be reading or writing while one
33721**                       process is writing.
33722**
33723**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
33724**                       after all dirty pages have been written to the
33725**                       database file and the file has been synced to
33726**                       disk. All that remains to do is to remove or
33727**                       truncate the journal file and the transaction
33728**                       will be committed.
33729**
33730** The page cache comes up in PAGER_UNLOCK.  The first time a
33731** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
33732** After all pages have been released using sqlite_page_unref(),
33733** the state transitions back to PAGER_UNLOCK.  The first time
33734** that sqlite3PagerWrite() is called, the state transitions to
33735** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
33736** called on an outstanding page which means that the pager must
33737** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
33738** PAGER_RESERVED means that there is an open rollback journal.
33739** The transition to PAGER_EXCLUSIVE occurs before any changes
33740** are made to the database file, though writes to the rollback
33741** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
33742** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
33743** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
33744*/
33745#define PAGER_UNLOCK      0
33746#define PAGER_SHARED      1   /* same as SHARED_LOCK */
33747#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
33748#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
33749#define PAGER_SYNCED      5
33750
33751/*
33752** A macro used for invoking the codec if there is one
33753*/
33754#ifdef SQLITE_HAS_CODEC
33755# define CODEC1(P,D,N,X,E) \
33756    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
33757# define CODEC2(P,D,N,X,E,O) \
33758    if( P->xCodec==0 ){ O=(char*)D; }else \
33759    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
33760#else
33761# define CODEC1(P,D,N,X,E)   /* NO-OP */
33762# define CODEC2(P,D,N,X,E,O) O=(char*)D
33763#endif
33764
33765/*
33766** The maximum allowed sector size. 64KiB. If the xSectorsize() method
33767** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
33768** This could conceivably cause corruption following a power failure on
33769** such a system. This is currently an undocumented limit.
33770*/
33771#define MAX_SECTOR_SIZE 0x10000
33772
33773/*
33774** An instance of the following structure is allocated for each active
33775** savepoint and statement transaction in the system. All such structures
33776** are stored in the Pager.aSavepoint[] array, which is allocated and
33777** resized using sqlite3Realloc().
33778**
33779** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
33780** set to 0. If a journal-header is written into the main journal while
33781** the savepoint is active, then iHdrOffset is set to the byte offset
33782** immediately following the last journal record written into the main
33783** journal before the journal-header. This is required during savepoint
33784** rollback (see pagerPlaybackSavepoint()).
33785*/
33786typedef struct PagerSavepoint PagerSavepoint;
33787struct PagerSavepoint {
33788  i64 iOffset;                 /* Starting offset in main journal */
33789  i64 iHdrOffset;              /* See above */
33790  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
33791  Pgno nOrig;                  /* Original number of pages in file */
33792  Pgno iSubRec;                /* Index of first record in sub-journal */
33793  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
33794};
33795
33796/*
33797** A open page cache is an instance of the following structure.
33798**
33799** errCode
33800**
33801**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
33802**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
33803**   and is returned as the result of every major pager API call.  The
33804**   SQLITE_FULL return code is slightly different. It persists only until the
33805**   next successful rollback is performed on the pager cache. Also,
33806**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
33807**   APIs, they may still be used successfully.
33808**
33809** dbSizeValid, dbSize, dbOrigSize, dbFileSize
33810**
33811**   Managing the size of the database file in pages is a little complicated.
33812**   The variable Pager.dbSize contains the number of pages that the database
33813**   image currently contains. As the database image grows or shrinks this
33814**   variable is updated. The variable Pager.dbFileSize contains the number
33815**   of pages in the database file. This may be different from Pager.dbSize
33816**   if some pages have been appended to the database image but not yet written
33817**   out from the cache to the actual file on disk. Or if the image has been
33818**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
33819**   contains the number of pages in the database image when the current
33820**   transaction was opened. The contents of all three of these variables is
33821**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
33822**
33823**   TODO: Under what conditions is dbSizeValid set? Cleared?
33824**
33825** changeCountDone
33826**
33827**   This boolean variable is used to make sure that the change-counter
33828**   (the 4-byte header field at byte offset 24 of the database file) is
33829**   not updated more often than necessary.
33830**
33831**   It is set to true when the change-counter field is updated, which
33832**   can only happen if an exclusive lock is held on the database file.
33833**   It is cleared (set to false) whenever an exclusive lock is
33834**   relinquished on the database file. Each time a transaction is committed,
33835**   The changeCountDone flag is inspected. If it is true, the work of
33836**   updating the change-counter is omitted for the current transaction.
33837**
33838**   This mechanism means that when running in exclusive mode, a connection
33839**   need only update the change-counter once, for the first transaction
33840**   committed.
33841**
33842** dbModified
33843**
33844**   The dbModified flag is set whenever a database page is dirtied.
33845**   It is cleared at the end of each transaction.
33846**
33847**   It is used when committing or otherwise ending a transaction. If
33848**   the dbModified flag is clear then less work has to be done.
33849**
33850** journalStarted
33851**
33852**   This flag is set whenever the the main journal is opened and
33853**   initialized
33854**
33855**   The point of this flag is that it must be set after the
33856**   first journal header in a journal file has been synced to disk.
33857**   After this has happened, new pages appended to the database
33858**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
33859**   to wait for a journal sync before they can be written out to
33860**   the database file (see function pager_write()).
33861**
33862** setMaster
33863**
33864**   This variable is used to ensure that the master journal file name
33865**   (if any) is only written into the journal file once.
33866**
33867**   When committing a transaction, the master journal file name (if any)
33868**   may be written into the journal file while the pager is still in
33869**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
33870**   then attempts to upgrade to an exclusive lock. If this attempt
33871**   fails, then SQLITE_BUSY may be returned to the user and the user
33872**   may attempt to commit the transaction again later (calling
33873**   CommitPhaseOne() again). This flag is used to ensure that the
33874**   master journal name is only written to the journal file the first
33875**   time CommitPhaseOne() is called.
33876**
33877** doNotSpill, doNotSyncSpill
33878**
33879**   When enabled, cache spills are prohibited.  The doNotSpill variable
33880**   inhibits all cache spill and doNotSyncSpill inhibits those spills that
33881**   would require a journal sync.  The doNotSyncSpill is set and cleared
33882**   by sqlite3PagerWrite() in order to prevent a journal sync from happening
33883**   in between the journalling of two pages on the same sector.  The
33884**   doNotSpill value set to prevent pagerStress() from trying to use
33885**   the journal during a rollback.
33886**
33887** needSync
33888**
33889**   TODO: It might be easier to set this variable in writeJournalHdr()
33890**   and writeMasterJournal() only. Change its meaning to "unsynced data
33891**   has been written to the journal".
33892**
33893** subjInMemory
33894**
33895**   This is a boolean variable. If true, then any required sub-journal
33896**   is opened as an in-memory journal file. If false, then in-memory
33897**   sub-journals are only used for in-memory pager files.
33898*/
33899struct Pager {
33900  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
33901  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
33902  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
33903  u8 useJournal;              /* Use a rollback journal on this file */
33904  u8 noReadlock;              /* Do not bother to obtain readlocks */
33905  u8 noSync;                  /* Do not sync the journal if true */
33906  u8 fullSync;                /* Do extra syncs of the journal for robustness */
33907  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
33908  u8 tempFile;                /* zFilename is a temporary file */
33909  u8 readOnly;                /* True for a read-only database */
33910  u8 memDb;                   /* True to inhibit all file I/O */
33911
33912  /* The following block contains those class members that are dynamically
33913  ** modified during normal operations. The other variables in this structure
33914  ** are either constant throughout the lifetime of the pager, or else
33915  ** used to store configuration parameters that affect the way the pager
33916  ** operates.
33917  **
33918  ** The 'state' variable is described in more detail along with the
33919  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
33920  ** other variables in this block are described in the comment directly
33921  ** above this class definition.
33922  */
33923  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
33924  u8 dbModified;              /* True if there are any changes to the Db */
33925  u8 needSync;                /* True if an fsync() is needed on the journal */
33926  u8 journalStarted;          /* True if header of journal is synced */
33927  u8 changeCountDone;         /* Set after incrementing the change-counter */
33928  u8 setMaster;               /* True if a m-j name has been written to jrnl */
33929  u8 doNotSpill;              /* Do not spill the cache when non-zero */
33930  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
33931  u8 dbSizeValid;             /* Set when dbSize is correct */
33932  u8 subjInMemory;            /* True to use in-memory sub-journals */
33933  Pgno dbSize;                /* Number of pages in the database */
33934  Pgno dbOrigSize;            /* dbSize before the current transaction */
33935  Pgno dbFileSize;            /* Number of pages in the database file */
33936  int errCode;                /* One of several kinds of errors */
33937  int nRec;                   /* Pages journalled since last j-header written */
33938  u32 cksumInit;              /* Quasi-random value added to every checksum */
33939  u32 nSubRec;                /* Number of records written to sub-journal */
33940  Bitvec *pInJournal;         /* One bit for each page in the database file */
33941  sqlite3_file *fd;           /* File descriptor for database */
33942  sqlite3_file *jfd;          /* File descriptor for main journal */
33943  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
33944  i64 journalOff;             /* Current write offset in the journal file */
33945  i64 journalHdr;             /* Byte offset to previous journal header */
33946  i64 journalSizeLimit;       /* Size limit for persistent journal files */
33947  PagerSavepoint *aSavepoint; /* Array of active savepoints */
33948  int nSavepoint;             /* Number of elements in aSavepoint[] */
33949  char dbFileVers[16];        /* Changes whenever database file changes */
33950  u32 sectorSize;             /* Assumed sector size during rollback */
33951
33952  u16 nExtra;                 /* Add this many bytes to each in-memory page */
33953  i16 nReserve;               /* Number of unused bytes at end of each page */
33954  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
33955  int pageSize;               /* Number of bytes in a page */
33956  Pgno mxPgno;                /* Maximum allowed size of the database */
33957  char *zFilename;            /* Name of the database file */
33958  char *zJournal;             /* Name of the journal file */
33959  int (*xBusyHandler)(void*); /* Function to call when busy */
33960  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
33961#ifdef SQLITE_TEST
33962  int nHit, nMiss;            /* Cache hits and missing */
33963  int nRead, nWrite;          /* Database pages read/written */
33964#endif
33965  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
33966#ifdef SQLITE_HAS_CODEC
33967  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
33968  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
33969  void (*xCodecFree)(void*);             /* Destructor for the codec */
33970  void *pCodec;               /* First argument to xCodec... methods */
33971#endif
33972  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
33973  PCache *pPCache;            /* Pointer to page cache object */
33974  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
33975#ifndef SQLITE_OMIT_WAL
33976  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
33977#endif
33978};
33979
33980/*
33981** The following global variables hold counters used for
33982** testing purposes only.  These variables do not exist in
33983** a non-testing build.  These variables are not thread-safe.
33984*/
33985#ifdef SQLITE_TEST
33986SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
33987SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
33988SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
33989# define PAGER_INCR(v)  v++
33990#else
33991# define PAGER_INCR(v)
33992#endif
33993
33994
33995
33996/*
33997** Journal files begin with the following magic string.  The data
33998** was obtained from /dev/random.  It is used only as a sanity check.
33999**
34000** Since version 2.8.0, the journal format contains additional sanity
34001** checking information.  If the power fails while the journal is being
34002** written, semi-random garbage data might appear in the journal
34003** file after power is restored.  If an attempt is then made
34004** to roll the journal back, the database could be corrupted.  The additional
34005** sanity checking data is an attempt to discover the garbage in the
34006** journal and ignore it.
34007**
34008** The sanity checking information for the new journal format consists
34009** of a 32-bit checksum on each page of data.  The checksum covers both
34010** the page number and the pPager->pageSize bytes of data for the page.
34011** This cksum is initialized to a 32-bit random value that appears in the
34012** journal file right after the header.  The random initializer is important,
34013** because garbage data that appears at the end of a journal is likely
34014** data that was once in other files that have now been deleted.  If the
34015** garbage data came from an obsolete journal file, the checksums might
34016** be correct.  But by initializing the checksum to random value which
34017** is different for every journal, we minimize that risk.
34018*/
34019static const unsigned char aJournalMagic[] = {
34020  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
34021};
34022
34023/*
34024** The size of the of each page record in the journal is given by
34025** the following macro.
34026*/
34027#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
34028
34029/*
34030** The journal header size for this pager. This is usually the same
34031** size as a single disk sector. See also setSectorSize().
34032*/
34033#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
34034
34035/*
34036** The macro MEMDB is true if we are dealing with an in-memory database.
34037** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
34038** the value of MEMDB will be a constant and the compiler will optimize
34039** out code that would never execute.
34040*/
34041#ifdef SQLITE_OMIT_MEMORYDB
34042# define MEMDB 0
34043#else
34044# define MEMDB pPager->memDb
34045#endif
34046
34047/*
34048** The maximum legal page number is (2^31 - 1).
34049*/
34050#define PAGER_MAX_PGNO 2147483647
34051
34052#ifndef NDEBUG
34053/*
34054** Usage:
34055**
34056**   assert( assert_pager_state(pPager) );
34057*/
34058static int assert_pager_state(Pager *pPager){
34059
34060  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
34061  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
34062
34063  /* The changeCountDone flag is always set for temp-files */
34064  assert( pPager->tempFile==0 || pPager->changeCountDone );
34065
34066  return 1;
34067}
34068#endif
34069
34070/*
34071** Return true if it is necessary to write page *pPg into the sub-journal.
34072** A page needs to be written into the sub-journal if there exists one
34073** or more open savepoints for which:
34074**
34075**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
34076**   * The bit corresponding to the page-number is not set in
34077**     PagerSavepoint.pInSavepoint.
34078*/
34079static int subjRequiresPage(PgHdr *pPg){
34080  Pgno pgno = pPg->pgno;
34081  Pager *pPager = pPg->pPager;
34082  int i;
34083  for(i=0; i<pPager->nSavepoint; i++){
34084    PagerSavepoint *p = &pPager->aSavepoint[i];
34085    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
34086      return 1;
34087    }
34088  }
34089  return 0;
34090}
34091
34092/*
34093** Return true if the page is already in the journal file.
34094*/
34095static int pageInJournal(PgHdr *pPg){
34096  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
34097}
34098
34099/*
34100** Read a 32-bit integer from the given file descriptor.  Store the integer
34101** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
34102** error code is something goes wrong.
34103**
34104** All values are stored on disk as big-endian.
34105*/
34106static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
34107  unsigned char ac[4];
34108  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
34109  if( rc==SQLITE_OK ){
34110    *pRes = sqlite3Get4byte(ac);
34111  }
34112  return rc;
34113}
34114
34115/*
34116** Write a 32-bit integer into a string buffer in big-endian byte order.
34117*/
34118#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
34119
34120/*
34121** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
34122** on success or an error code is something goes wrong.
34123*/
34124static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
34125  char ac[4];
34126  put32bits(ac, val);
34127  return sqlite3OsWrite(fd, ac, 4, offset);
34128}
34129
34130/*
34131** The argument to this macro is a file descriptor (type sqlite3_file*).
34132** Return 0 if it is not open, or non-zero (but not 1) if it is.
34133**
34134** This is so that expressions can be written as:
34135**
34136**   if( isOpen(pPager->jfd) ){ ...
34137**
34138** instead of
34139**
34140**   if( pPager->jfd->pMethods ){ ...
34141*/
34142#define isOpen(pFd) ((pFd)->pMethods)
34143
34144/*
34145** If file pFd is open, call sqlite3OsUnlock() on it.
34146*/
34147static int osUnlock(sqlite3_file *pFd, int eLock){
34148  if( !isOpen(pFd) ){
34149    return SQLITE_OK;
34150  }
34151  return sqlite3OsUnlock(pFd, eLock);
34152}
34153
34154/*
34155** This function determines whether or not the atomic-write optimization
34156** can be used with this pager. The optimization can be used if:
34157**
34158**  (a) the value returned by OsDeviceCharacteristics() indicates that
34159**      a database page may be written atomically, and
34160**  (b) the value returned by OsSectorSize() is less than or equal
34161**      to the page size.
34162**
34163** The optimization is also always enabled for temporary files. It is
34164** an error to call this function if pPager is opened on an in-memory
34165** database.
34166**
34167** If the optimization cannot be used, 0 is returned. If it can be used,
34168** then the value returned is the size of the journal file when it
34169** contains rollback data for exactly one page.
34170*/
34171#ifdef SQLITE_ENABLE_ATOMIC_WRITE
34172static int jrnlBufferSize(Pager *pPager){
34173  assert( !MEMDB );
34174  if( !pPager->tempFile ){
34175    int dc;                           /* Device characteristics */
34176    int nSector;                      /* Sector size */
34177    int szPage;                       /* Page size */
34178
34179    assert( isOpen(pPager->fd) );
34180    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
34181    nSector = pPager->sectorSize;
34182    szPage = pPager->pageSize;
34183
34184    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34185    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34186    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
34187      return 0;
34188    }
34189  }
34190
34191  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
34192}
34193#endif
34194
34195/*
34196** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
34197** on the cache using a hash function.  This is used for testing
34198** and debugging only.
34199*/
34200#ifdef SQLITE_CHECK_PAGES
34201/*
34202** Return a 32-bit hash of the page data for pPage.
34203*/
34204static u32 pager_datahash(int nByte, unsigned char *pData){
34205  u32 hash = 0;
34206  int i;
34207  for(i=0; i<nByte; i++){
34208    hash = (hash*1039) + pData[i];
34209  }
34210  return hash;
34211}
34212static u32 pager_pagehash(PgHdr *pPage){
34213  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
34214}
34215static void pager_set_pagehash(PgHdr *pPage){
34216  pPage->pageHash = pager_pagehash(pPage);
34217}
34218
34219/*
34220** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
34221** is defined, and NDEBUG is not defined, an assert() statement checks
34222** that the page is either dirty or still matches the calculated page-hash.
34223*/
34224#define CHECK_PAGE(x) checkPage(x)
34225static void checkPage(PgHdr *pPg){
34226  Pager *pPager = pPg->pPager;
34227  assert( !pPg->pageHash || pPager->errCode
34228      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
34229}
34230
34231#else
34232#define pager_datahash(X,Y)  0
34233#define pager_pagehash(X)  0
34234#define CHECK_PAGE(x)
34235#endif  /* SQLITE_CHECK_PAGES */
34236
34237/*
34238** When this is called the journal file for pager pPager must be open.
34239** This function attempts to read a master journal file name from the
34240** end of the file and, if successful, copies it into memory supplied
34241** by the caller. See comments above writeMasterJournal() for the format
34242** used to store a master journal file name at the end of a journal file.
34243**
34244** zMaster must point to a buffer of at least nMaster bytes allocated by
34245** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
34246** enough space to write the master journal name). If the master journal
34247** name in the journal is longer than nMaster bytes (including a
34248** nul-terminator), then this is handled as if no master journal name
34249** were present in the journal.
34250**
34251** If a master journal file name is present at the end of the journal
34252** file, then it is copied into the buffer pointed to by zMaster. A
34253** nul-terminator byte is appended to the buffer following the master
34254** journal file name.
34255**
34256** If it is determined that no master journal file name is present
34257** zMaster[0] is set to 0 and SQLITE_OK returned.
34258**
34259** If an error occurs while reading from the journal file, an SQLite
34260** error code is returned.
34261*/
34262static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
34263  int rc;                    /* Return code */
34264  u32 len;                   /* Length in bytes of master journal name */
34265  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
34266  u32 cksum;                 /* MJ checksum value read from journal */
34267  u32 u;                     /* Unsigned loop counter */
34268  unsigned char aMagic[8];   /* A buffer to hold the magic header */
34269  zMaster[0] = '\0';
34270
34271  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
34272   || szJ<16
34273   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
34274   || len>=nMaster
34275   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
34276   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
34277   || memcmp(aMagic, aJournalMagic, 8)
34278   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
34279  ){
34280    return rc;
34281  }
34282
34283  /* See if the checksum matches the master journal name */
34284  for(u=0; u<len; u++){
34285    cksum -= zMaster[u];
34286  }
34287  if( cksum ){
34288    /* If the checksum doesn't add up, then one or more of the disk sectors
34289    ** containing the master journal filename is corrupted. This means
34290    ** definitely roll back, so just return SQLITE_OK and report a (nul)
34291    ** master-journal filename.
34292    */
34293    len = 0;
34294  }
34295  zMaster[len] = '\0';
34296
34297  return SQLITE_OK;
34298}
34299
34300/*
34301** Return the offset of the sector boundary at or immediately
34302** following the value in pPager->journalOff, assuming a sector
34303** size of pPager->sectorSize bytes.
34304**
34305** i.e for a sector size of 512:
34306**
34307**   Pager.journalOff          Return value
34308**   ---------------------------------------
34309**   0                         0
34310**   512                       512
34311**   100                       512
34312**   2000                      2048
34313**
34314*/
34315static i64 journalHdrOffset(Pager *pPager){
34316  i64 offset = 0;
34317  i64 c = pPager->journalOff;
34318  if( c ){
34319    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
34320  }
34321  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
34322  assert( offset>=c );
34323  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
34324  return offset;
34325}
34326
34327/*
34328** The journal file must be open when this function is called.
34329**
34330** This function is a no-op if the journal file has not been written to
34331** within the current transaction (i.e. if Pager.journalOff==0).
34332**
34333** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
34334** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
34335** zero the 28-byte header at the start of the journal file. In either case,
34336** if the pager is not in no-sync mode, sync the journal file immediately
34337** after writing or truncating it.
34338**
34339** If Pager.journalSizeLimit is set to a positive, non-zero value, and
34340** following the truncation or zeroing described above the size of the
34341** journal file in bytes is larger than this value, then truncate the
34342** journal file to Pager.journalSizeLimit bytes. The journal file does
34343** not need to be synced following this operation.
34344**
34345** If an IO error occurs, abandon processing and return the IO error code.
34346** Otherwise, return SQLITE_OK.
34347*/
34348static int zeroJournalHdr(Pager *pPager, int doTruncate){
34349  int rc = SQLITE_OK;                               /* Return code */
34350  assert( isOpen(pPager->jfd) );
34351  if( pPager->journalOff ){
34352    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
34353
34354    IOTRACE(("JZEROHDR %p\n", pPager))
34355    if( doTruncate || iLimit==0 ){
34356      rc = sqlite3OsTruncate(pPager->jfd, 0);
34357    }else{
34358      static const char zeroHdr[28] = {0};
34359      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
34360    }
34361    if( rc==SQLITE_OK && !pPager->noSync ){
34362      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
34363    }
34364
34365    /* At this point the transaction is committed but the write lock
34366    ** is still held on the file. If there is a size limit configured for
34367    ** the persistent journal and the journal file currently consumes more
34368    ** space than that limit allows for, truncate it now. There is no need
34369    ** to sync the file following this operation.
34370    */
34371    if( rc==SQLITE_OK && iLimit>0 ){
34372      i64 sz;
34373      rc = sqlite3OsFileSize(pPager->jfd, &sz);
34374      if( rc==SQLITE_OK && sz>iLimit ){
34375        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
34376      }
34377    }
34378  }
34379  return rc;
34380}
34381
34382/*
34383** The journal file must be open when this routine is called. A journal
34384** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
34385** current location.
34386**
34387** The format for the journal header is as follows:
34388** - 8 bytes: Magic identifying journal format.
34389** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
34390** - 4 bytes: Random number used for page hash.
34391** - 4 bytes: Initial database page count.
34392** - 4 bytes: Sector size used by the process that wrote this journal.
34393** - 4 bytes: Database page size.
34394**
34395** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
34396*/
34397static int writeJournalHdr(Pager *pPager){
34398  int rc = SQLITE_OK;                 /* Return code */
34399  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
34400  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
34401  u32 nWrite;                         /* Bytes of header sector written */
34402  int ii;                             /* Loop counter */
34403
34404  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34405
34406  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
34407    nHeader = JOURNAL_HDR_SZ(pPager);
34408  }
34409
34410  /* If there are active savepoints and any of them were created
34411  ** since the most recent journal header was written, update the
34412  ** PagerSavepoint.iHdrOffset fields now.
34413  */
34414  for(ii=0; ii<pPager->nSavepoint; ii++){
34415    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
34416      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
34417    }
34418  }
34419
34420  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
34421
34422  /*
34423  ** Write the nRec Field - the number of page records that follow this
34424  ** journal header. Normally, zero is written to this value at this time.
34425  ** After the records are added to the journal (and the journal synced,
34426  ** if in full-sync mode), the zero is overwritten with the true number
34427  ** of records (see syncJournal()).
34428  **
34429  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
34430  ** reading the journal this value tells SQLite to assume that the
34431  ** rest of the journal file contains valid page records. This assumption
34432  ** is dangerous, as if a failure occurred whilst writing to the journal
34433  ** file it may contain some garbage data. There are two scenarios
34434  ** where this risk can be ignored:
34435  **
34436  **   * When the pager is in no-sync mode. Corruption can follow a
34437  **     power failure in this case anyway.
34438  **
34439  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
34440  **     that garbage data is never appended to the journal file.
34441  */
34442  assert( isOpen(pPager->fd) || pPager->noSync );
34443  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
34444   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34445  ){
34446    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34447    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
34448  }else{
34449    memset(zHeader, 0, sizeof(aJournalMagic)+4);
34450  }
34451
34452  /* The random check-hash initialiser */
34453  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
34454  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
34455  /* The initial database size */
34456  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
34457  /* The assumed sector size for this process */
34458  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
34459
34460  /* The page size */
34461  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
34462
34463  /* Initializing the tail of the buffer is not necessary.  Everything
34464  ** works find if the following memset() is omitted.  But initializing
34465  ** the memory prevents valgrind from complaining, so we are willing to
34466  ** take the performance hit.
34467  */
34468  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
34469         nHeader-(sizeof(aJournalMagic)+20));
34470
34471  /* In theory, it is only necessary to write the 28 bytes that the
34472  ** journal header consumes to the journal file here. Then increment the
34473  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
34474  ** record is written to the following sector (leaving a gap in the file
34475  ** that will be implicitly filled in by the OS).
34476  **
34477  ** However it has been discovered that on some systems this pattern can
34478  ** be significantly slower than contiguously writing data to the file,
34479  ** even if that means explicitly writing data to the block of
34480  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
34481  ** is done.
34482  **
34483  ** The loop is required here in case the sector-size is larger than the
34484  ** database page size. Since the zHeader buffer is only Pager.pageSize
34485  ** bytes in size, more than one call to sqlite3OsWrite() may be required
34486  ** to populate the entire journal header sector.
34487  */
34488  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
34489    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
34490    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
34491    assert( pPager->journalHdr <= pPager->journalOff );
34492    pPager->journalOff += nHeader;
34493  }
34494
34495  return rc;
34496}
34497
34498/*
34499** The journal file must be open when this is called. A journal header file
34500** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
34501** file. The current location in the journal file is given by
34502** pPager->journalOff. See comments above function writeJournalHdr() for
34503** a description of the journal header format.
34504**
34505** If the header is read successfully, *pNRec is set to the number of
34506** page records following this header and *pDbSize is set to the size of the
34507** database before the transaction began, in pages. Also, pPager->cksumInit
34508** is set to the value read from the journal header. SQLITE_OK is returned
34509** in this case.
34510**
34511** If the journal header file appears to be corrupted, SQLITE_DONE is
34512** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
34513** cannot be read from the journal file an error code is returned.
34514*/
34515static int readJournalHdr(
34516  Pager *pPager,               /* Pager object */
34517  int isHot,
34518  i64 journalSize,             /* Size of the open journal file in bytes */
34519  u32 *pNRec,                  /* OUT: Value read from the nRec field */
34520  u32 *pDbSize                 /* OUT: Value of original database size field */
34521){
34522  int rc;                      /* Return code */
34523  unsigned char aMagic[8];     /* A buffer to hold the magic header */
34524  i64 iHdrOff;                 /* Offset of journal header being read */
34525
34526  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34527
34528  /* Advance Pager.journalOff to the start of the next sector. If the
34529  ** journal file is too small for there to be a header stored at this
34530  ** point, return SQLITE_DONE.
34531  */
34532  pPager->journalOff = journalHdrOffset(pPager);
34533  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
34534    return SQLITE_DONE;
34535  }
34536  iHdrOff = pPager->journalOff;
34537
34538  /* Read in the first 8 bytes of the journal header. If they do not match
34539  ** the  magic string found at the start of each journal header, return
34540  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
34541  ** proceed.
34542  */
34543  if( isHot || iHdrOff!=pPager->journalHdr ){
34544    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
34545    if( rc ){
34546      return rc;
34547    }
34548    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
34549      return SQLITE_DONE;
34550    }
34551  }
34552
34553  /* Read the first three 32-bit fields of the journal header: The nRec
34554  ** field, the checksum-initializer and the database size at the start
34555  ** of the transaction. Return an error code if anything goes wrong.
34556  */
34557  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
34558   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
34559   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
34560  ){
34561    return rc;
34562  }
34563
34564  if( pPager->journalOff==0 ){
34565    u32 iPageSize;               /* Page-size field of journal header */
34566    u32 iSectorSize;             /* Sector-size field of journal header */
34567    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
34568
34569    /* Read the page-size and sector-size journal header fields. */
34570    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
34571     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
34572    ){
34573      return rc;
34574    }
34575
34576    /* Check that the values read from the page-size and sector-size fields
34577    ** are within range. To be 'in range', both values need to be a power
34578    ** of two greater than or equal to 512 or 32, and not greater than their
34579    ** respective compile time maximum limits.
34580    */
34581    if( iPageSize<512                  || iSectorSize<32
34582     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
34583     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
34584    ){
34585      /* If the either the page-size or sector-size in the journal-header is
34586      ** invalid, then the process that wrote the journal-header must have
34587      ** crashed before the header was synced. In this case stop reading
34588      ** the journal file here.
34589      */
34590      return SQLITE_DONE;
34591    }
34592
34593    /* Update the page-size to match the value read from the journal.
34594    ** Use a testcase() macro to make sure that malloc failure within
34595    ** PagerSetPagesize() is tested.
34596    */
34597    iPageSize16 = (u16)iPageSize;
34598    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
34599    testcase( rc!=SQLITE_OK );
34600    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
34601
34602    /* Update the assumed sector-size to match the value used by
34603    ** the process that created this journal. If this journal was
34604    ** created by a process other than this one, then this routine
34605    ** is being called from within pager_playback(). The local value
34606    ** of Pager.sectorSize is restored at the end of that routine.
34607    */
34608    pPager->sectorSize = iSectorSize;
34609  }
34610
34611  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
34612  return rc;
34613}
34614
34615
34616/*
34617** Write the supplied master journal name into the journal file for pager
34618** pPager at the current location. The master journal name must be the last
34619** thing written to a journal file. If the pager is in full-sync mode, the
34620** journal file descriptor is advanced to the next sector boundary before
34621** anything is written. The format is:
34622**
34623**   + 4 bytes: PAGER_MJ_PGNO.
34624**   + N bytes: Master journal filename in utf-8.
34625**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
34626**   + 4 bytes: Master journal name checksum.
34627**   + 8 bytes: aJournalMagic[].
34628**
34629** The master journal page checksum is the sum of the bytes in the master
34630** journal name, where each byte is interpreted as a signed 8-bit integer.
34631**
34632** If zMaster is a NULL pointer (occurs for a single database transaction),
34633** this call is a no-op.
34634*/
34635static int writeMasterJournal(Pager *pPager, const char *zMaster){
34636  int rc;                          /* Return code */
34637  int nMaster;                     /* Length of string zMaster */
34638  i64 iHdrOff;                     /* Offset of header in journal file */
34639  i64 jrnlSize;                    /* Size of journal file on disk */
34640  u32 cksum = 0;                   /* Checksum of string zMaster */
34641
34642  if( !zMaster || pPager->setMaster
34643   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
34644   || pPager->journalMode==PAGER_JOURNALMODE_OFF
34645  ){
34646    return SQLITE_OK;
34647  }
34648  pPager->setMaster = 1;
34649  assert( isOpen(pPager->jfd) );
34650  assert( pPager->journalHdr <= pPager->journalOff );
34651
34652  /* Calculate the length in bytes and the checksum of zMaster */
34653  for(nMaster=0; zMaster[nMaster]; nMaster++){
34654    cksum += zMaster[nMaster];
34655  }
34656
34657  /* If in full-sync mode, advance to the next disk sector before writing
34658  ** the master journal name. This is in case the previous page written to
34659  ** the journal has already been synced.
34660  */
34661  if( pPager->fullSync ){
34662    pPager->journalOff = journalHdrOffset(pPager);
34663  }
34664  iHdrOff = pPager->journalOff;
34665
34666  /* Write the master journal data to the end of the journal file. If
34667  ** an error occurs, return the error code to the caller.
34668  */
34669  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
34670   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
34671   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
34672   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
34673   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
34674  ){
34675    return rc;
34676  }
34677  pPager->journalOff += (nMaster+20);
34678  pPager->needSync = !pPager->noSync;
34679
34680  /* If the pager is in peristent-journal mode, then the physical
34681  ** journal-file may extend past the end of the master-journal name
34682  ** and 8 bytes of magic data just written to the file. This is
34683  ** dangerous because the code to rollback a hot-journal file
34684  ** will not be able to find the master-journal name to determine
34685  ** whether or not the journal is hot.
34686  **
34687  ** Easiest thing to do in this scenario is to truncate the journal
34688  ** file to the required size.
34689  */
34690  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
34691   && jrnlSize>pPager->journalOff
34692  ){
34693    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
34694  }
34695  return rc;
34696}
34697
34698/*
34699** Find a page in the hash table given its page number. Return
34700** a pointer to the page or NULL if the requested page is not
34701** already in memory.
34702*/
34703static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
34704  PgHdr *p;                         /* Return value */
34705
34706  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
34707  ** fail, since no attempt to allocate dynamic memory will be made.
34708  */
34709  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
34710  return p;
34711}
34712
34713/*
34714** Unless the pager is in error-state, discard all in-memory pages. If
34715** the pager is in error-state, then this call is a no-op.
34716**
34717** TODO: Why can we not reset the pager while in error state?
34718*/
34719static void pager_reset(Pager *pPager){
34720  if( SQLITE_OK==pPager->errCode ){
34721    sqlite3BackupRestart(pPager->pBackup);
34722    sqlite3PcacheClear(pPager->pPCache);
34723    pPager->dbSizeValid = 0;
34724  }
34725}
34726
34727/*
34728** Free all structures in the Pager.aSavepoint[] array and set both
34729** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
34730** if it is open and the pager is not in exclusive mode.
34731*/
34732static void releaseAllSavepoints(Pager *pPager){
34733  int ii;               /* Iterator for looping through Pager.aSavepoint */
34734  for(ii=0; ii<pPager->nSavepoint; ii++){
34735    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
34736  }
34737  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
34738    sqlite3OsClose(pPager->sjfd);
34739  }
34740  sqlite3_free(pPager->aSavepoint);
34741  pPager->aSavepoint = 0;
34742  pPager->nSavepoint = 0;
34743  pPager->nSubRec = 0;
34744}
34745
34746/*
34747** Set the bit number pgno in the PagerSavepoint.pInSavepoint
34748** bitvecs of all open savepoints. Return SQLITE_OK if successful
34749** or SQLITE_NOMEM if a malloc failure occurs.
34750*/
34751static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
34752  int ii;                   /* Loop counter */
34753  int rc = SQLITE_OK;       /* Result code */
34754
34755  for(ii=0; ii<pPager->nSavepoint; ii++){
34756    PagerSavepoint *p = &pPager->aSavepoint[ii];
34757    if( pgno<=p->nOrig ){
34758      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
34759      testcase( rc==SQLITE_NOMEM );
34760      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
34761    }
34762  }
34763  return rc;
34764}
34765
34766/*
34767** Return true if this pager uses a write-ahead log instead of the usual
34768** rollback journal. Otherwise false.
34769*/
34770#ifndef SQLITE_OMIT_WAL
34771static int pagerUseWal(Pager *pPager){
34772  return (pPager->pWal!=0);
34773}
34774#else
34775# define pagerUseWal(x) 0
34776# define pagerRollbackWal(x) 0
34777# define pagerWalFrames(v,w,x,y,z) 0
34778# define pagerOpenWalIfPresent(z) SQLITE_OK
34779# define pagerBeginReadTransaction(z) SQLITE_OK
34780#endif
34781
34782/*
34783** Unlock the database file. This function is a no-op if the pager
34784** is in exclusive mode.
34785**
34786** If the pager is currently in error state, discard the contents of
34787** the cache and reset the Pager structure internal state. If there is
34788** an open journal-file, then the next time a shared-lock is obtained
34789** on the pager file (by this or any other process), it will be
34790** treated as a hot-journal and rolled back.
34791*/
34792static void pager_unlock(Pager *pPager){
34793  if( !pPager->exclusiveMode ){
34794    int rc = SQLITE_OK;          /* Return code */
34795    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
34796
34797    /* If the operating system support deletion of open files, then
34798    ** close the journal file when dropping the database lock.  Otherwise
34799    ** another connection with journal_mode=delete might delete the file
34800    ** out from under us.
34801    */
34802    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
34803    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
34804    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
34805    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
34806    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
34807    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
34808    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
34809     || 1!=(pPager->journalMode & 5)
34810    ){
34811      sqlite3OsClose(pPager->jfd);
34812    }
34813
34814    sqlite3BitvecDestroy(pPager->pInJournal);
34815    pPager->pInJournal = 0;
34816    releaseAllSavepoints(pPager);
34817
34818    /* If the file is unlocked, somebody else might change it. The
34819    ** values stored in Pager.dbSize etc. might become invalid if
34820    ** this happens.  One can argue that this doesn't need to be cleared
34821    ** until the change-counter check fails in PagerSharedLock().
34822    ** Clearing the page size cache here is being conservative.
34823    */
34824    pPager->dbSizeValid = 0;
34825
34826    if( pagerUseWal(pPager) ){
34827      sqlite3WalEndReadTransaction(pPager->pWal);
34828    }else{
34829      rc = osUnlock(pPager->fd, NO_LOCK);
34830    }
34831    if( rc ){
34832      pPager->errCode = rc;
34833    }
34834    IOTRACE(("UNLOCK %p\n", pPager))
34835
34836    /* If Pager.errCode is set, the contents of the pager cache cannot be
34837    ** trusted. Now that the pager file is unlocked, the contents of the
34838    ** cache can be discarded and the error code safely cleared.
34839    */
34840    if( pPager->errCode ){
34841      if( rc==SQLITE_OK ){
34842        pPager->errCode = SQLITE_OK;
34843      }
34844      pager_reset(pPager);
34845    }
34846
34847    pPager->changeCountDone = 0;
34848    pPager->state = PAGER_UNLOCK;
34849    pPager->dbModified = 0;
34850  }
34851}
34852
34853/*
34854** This function should be called when an IOERR, CORRUPT or FULL error
34855** may have occurred. The first argument is a pointer to the pager
34856** structure, the second the error-code about to be returned by a pager
34857** API function. The value returned is a copy of the second argument
34858** to this function.
34859**
34860** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
34861** the error becomes persistent. Until the persistent error is cleared,
34862** subsequent API calls on this Pager will immediately return the same
34863** error code.
34864**
34865** A persistent error indicates that the contents of the pager-cache
34866** cannot be trusted. This state can be cleared by completely discarding
34867** the contents of the pager-cache. If a transaction was active when
34868** the persistent error occurred, then the rollback journal may need
34869** to be replayed to restore the contents of the database file (as if
34870** it were a hot-journal).
34871*/
34872static int pager_error(Pager *pPager, int rc){
34873  int rc2 = rc & 0xff;
34874  assert( rc==SQLITE_OK || !MEMDB );
34875  assert(
34876       pPager->errCode==SQLITE_FULL ||
34877       pPager->errCode==SQLITE_OK ||
34878       (pPager->errCode & 0xff)==SQLITE_IOERR
34879  );
34880  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
34881    pPager->errCode = rc;
34882  }
34883  return rc;
34884}
34885
34886/*
34887** Execute a rollback if a transaction is active and unlock the
34888** database file.
34889**
34890** If the pager has already entered the error state, do not attempt
34891** the rollback at this time. Instead, pager_unlock() is called. The
34892** call to pager_unlock() will discard all in-memory pages, unlock
34893** the database file and clear the error state. If this means that
34894** there is a hot-journal left in the file-system, the next connection
34895** to obtain a shared lock on the pager (which may be this one) will
34896** roll it back.
34897**
34898** If the pager has not already entered the error state, but an IO or
34899** malloc error occurs during a rollback, then this will itself cause
34900** the pager to enter the error state. Which will be cleared by the
34901** call to pager_unlock(), as described above.
34902*/
34903static void pagerUnlockAndRollback(Pager *pPager){
34904  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
34905    sqlite3BeginBenignMalloc();
34906    sqlite3PagerRollback(pPager);
34907    sqlite3EndBenignMalloc();
34908  }
34909  pager_unlock(pPager);
34910}
34911
34912/*
34913** This routine ends a transaction. A transaction is usually ended by
34914** either a COMMIT or a ROLLBACK operation. This routine may be called
34915** after rollback of a hot-journal, or if an error occurs while opening
34916** the journal file or writing the very first journal-header of a
34917** database transaction.
34918**
34919** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
34920** routine is called, it is a no-op (returns SQLITE_OK).
34921**
34922** Otherwise, any active savepoints are released.
34923**
34924** If the journal file is open, then it is "finalized". Once a journal
34925** file has been finalized it is not possible to use it to roll back a
34926** transaction. Nor will it be considered to be a hot-journal by this
34927** or any other database connection. Exactly how a journal is finalized
34928** depends on whether or not the pager is running in exclusive mode and
34929** the current journal-mode (Pager.journalMode value), as follows:
34930**
34931**   journalMode==MEMORY
34932**     Journal file descriptor is simply closed. This destroys an
34933**     in-memory journal.
34934**
34935**   journalMode==TRUNCATE
34936**     Journal file is truncated to zero bytes in size.
34937**
34938**   journalMode==PERSIST
34939**     The first 28 bytes of the journal file are zeroed. This invalidates
34940**     the first journal header in the file, and hence the entire journal
34941**     file. An invalid journal file cannot be rolled back.
34942**
34943**   journalMode==DELETE
34944**     The journal file is closed and deleted using sqlite3OsDelete().
34945**
34946**     If the pager is running in exclusive mode, this method of finalizing
34947**     the journal file is never used. Instead, if the journalMode is
34948**     DELETE and the pager is in exclusive mode, the method described under
34949**     journalMode==PERSIST is used instead.
34950**
34951** After the journal is finalized, if running in non-exclusive mode, the
34952** pager moves to PAGER_SHARED state (and downgrades the lock on the
34953** database file accordingly).
34954**
34955** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
34956** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
34957** exclusive mode.
34958**
34959** SQLITE_OK is returned if no error occurs. If an error occurs during
34960** any of the IO operations to finalize the journal file or unlock the
34961** database then the IO error code is returned to the user. If the
34962** operation to finalize the journal file fails, then the code still
34963** tries to unlock the database file if not in exclusive mode. If the
34964** unlock operation fails as well, then the first error code related
34965** to the first error encountered (the journal finalization one) is
34966** returned.
34967*/
34968static int pager_end_transaction(Pager *pPager, int hasMaster){
34969  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
34970  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
34971
34972  if( pPager->state<PAGER_RESERVED ){
34973    return SQLITE_OK;
34974  }
34975  releaseAllSavepoints(pPager);
34976
34977  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
34978  if( isOpen(pPager->jfd) ){
34979    assert( !pagerUseWal(pPager) );
34980
34981    /* Finalize the journal file. */
34982    if( sqlite3IsMemJournal(pPager->jfd) ){
34983      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
34984      sqlite3OsClose(pPager->jfd);
34985    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
34986      if( pPager->journalOff==0 ){
34987        rc = SQLITE_OK;
34988      }else{
34989        rc = sqlite3OsTruncate(pPager->jfd, 0);
34990      }
34991      pPager->journalOff = 0;
34992      pPager->journalStarted = 0;
34993    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
34994      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
34995    ){
34996      rc = zeroJournalHdr(pPager, hasMaster);
34997      pager_error(pPager, rc);
34998      pPager->journalOff = 0;
34999      pPager->journalStarted = 0;
35000    }else{
35001      /* This branch may be executed with Pager.journalMode==MEMORY if
35002      ** a hot-journal was just rolled back. In this case the journal
35003      ** file should be closed and deleted. If this connection writes to
35004      ** the database file, it will do so using an in-memory journal.
35005      */
35006      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
35007           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
35008           || pPager->journalMode==PAGER_JOURNALMODE_WAL
35009      );
35010      sqlite3OsClose(pPager->jfd);
35011      if( !pPager->tempFile ){
35012        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
35013      }
35014    }
35015
35016#ifdef SQLITE_CHECK_PAGES
35017    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
35018#endif
35019  }
35020  sqlite3BitvecDestroy(pPager->pInJournal);
35021  pPager->pInJournal = 0;
35022  pPager->nRec = 0;
35023  sqlite3PcacheCleanAll(pPager->pPCache);
35024
35025  if( pagerUseWal(pPager) ){
35026    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
35027    assert( rc2==SQLITE_OK );
35028    pPager->state = PAGER_SHARED;
35029
35030    /* If the connection was in locking_mode=exclusive mode but is no longer,
35031    ** drop the EXCLUSIVE lock held on the database file.
35032    */
35033    if( !pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, 0) ){
35034      rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35035    }
35036  }else if( !pPager->exclusiveMode ){
35037    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35038    pPager->state = PAGER_SHARED;
35039    pPager->changeCountDone = 0;
35040  }else if( pPager->state==PAGER_SYNCED ){
35041    pPager->state = PAGER_EXCLUSIVE;
35042  }
35043  pPager->setMaster = 0;
35044  pPager->needSync = 0;
35045  pPager->dbModified = 0;
35046
35047  /* TODO: Is this optimal? Why is the db size invalidated here
35048  ** when the database file is not unlocked? */
35049  pPager->dbOrigSize = 0;
35050  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
35051  if( !MEMDB ){
35052    pPager->dbSizeValid = 0;
35053  }
35054
35055  return (rc==SQLITE_OK?rc2:rc);
35056}
35057
35058/*
35059** Parameter aData must point to a buffer of pPager->pageSize bytes
35060** of data. Compute and return a checksum based ont the contents of the
35061** page of data and the current value of pPager->cksumInit.
35062**
35063** This is not a real checksum. It is really just the sum of the
35064** random initial value (pPager->cksumInit) and every 200th byte
35065** of the page data, starting with byte offset (pPager->pageSize%200).
35066** Each byte is interpreted as an 8-bit unsigned integer.
35067**
35068** Changing the formula used to compute this checksum results in an
35069** incompatible journal file format.
35070**
35071** If journal corruption occurs due to a power failure, the most likely
35072** scenario is that one end or the other of the record will be changed.
35073** It is much less likely that the two ends of the journal record will be
35074** correct and the middle be corrupt.  Thus, this "checksum" scheme,
35075** though fast and simple, catches the mostly likely kind of corruption.
35076*/
35077static u32 pager_cksum(Pager *pPager, const u8 *aData){
35078  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
35079  int i = pPager->pageSize-200;          /* Loop counter */
35080  while( i>0 ){
35081    cksum += aData[i];
35082    i -= 200;
35083  }
35084  return cksum;
35085}
35086
35087/*
35088** Read a single page from either the journal file (if isMainJrnl==1) or
35089** from the sub-journal (if isMainJrnl==0) and playback that page.
35090** The page begins at offset *pOffset into the file. The *pOffset
35091** value is increased to the start of the next page in the journal.
35092**
35093** The isMainJrnl flag is true if this is the main rollback journal and
35094** false for the statement journal.  The main rollback journal uses
35095** checksums - the statement journal does not.
35096**
35097** If the page number of the page record read from the (sub-)journal file
35098** is greater than the current value of Pager.dbSize, then playback is
35099** skipped and SQLITE_OK is returned.
35100**
35101** If pDone is not NULL, then it is a record of pages that have already
35102** been played back.  If the page at *pOffset has already been played back
35103** (if the corresponding pDone bit is set) then skip the playback.
35104** Make sure the pDone bit corresponding to the *pOffset page is set
35105** prior to returning.
35106**
35107** If the page record is successfully read from the (sub-)journal file
35108** and played back, then SQLITE_OK is returned. If an IO error occurs
35109** while reading the record from the (sub-)journal file or while writing
35110** to the database file, then the IO error code is returned. If data
35111** is successfully read from the (sub-)journal file but appears to be
35112** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
35113** two circumstances:
35114**
35115**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
35116**   * If the record is being rolled back from the main journal file
35117**     and the checksum field does not match the record content.
35118**
35119** Neither of these two scenarios are possible during a savepoint rollback.
35120**
35121** If this is a savepoint rollback, then memory may have to be dynamically
35122** allocated by this function. If this is the case and an allocation fails,
35123** SQLITE_NOMEM is returned.
35124*/
35125static int pager_playback_one_page(
35126  Pager *pPager,                /* The pager being played back */
35127  i64 *pOffset,                 /* Offset of record to playback */
35128  Bitvec *pDone,                /* Bitvec of pages already played back */
35129  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
35130  int isSavepnt                 /* True for a savepoint rollback */
35131){
35132  int rc;
35133  PgHdr *pPg;                   /* An existing page in the cache */
35134  Pgno pgno;                    /* The page number of a page in journal */
35135  u32 cksum;                    /* Checksum used for sanity checking */
35136  char *aData;                  /* Temporary storage for the page */
35137  sqlite3_file *jfd;            /* The file descriptor for the journal file */
35138  int isSynced;                 /* True if journal page is synced */
35139
35140  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
35141  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
35142  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
35143  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
35144
35145  aData = pPager->pTmpSpace;
35146  assert( aData );         /* Temp storage must have already been allocated */
35147  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
35148
35149  /* Read the page number and page data from the journal or sub-journal
35150  ** file. Return an error code to the caller if an IO error occurs.
35151  */
35152  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
35153  rc = read32bits(jfd, *pOffset, &pgno);
35154  if( rc!=SQLITE_OK ) return rc;
35155  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
35156  if( rc!=SQLITE_OK ) return rc;
35157  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
35158
35159  /* Sanity checking on the page.  This is more important that I originally
35160  ** thought.  If a power failure occurs while the journal is being written,
35161  ** it could cause invalid data to be written into the journal.  We need to
35162  ** detect this invalid data (with high probability) and ignore it.
35163  */
35164  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
35165    assert( !isSavepnt );
35166    return SQLITE_DONE;
35167  }
35168  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
35169    return SQLITE_OK;
35170  }
35171  if( isMainJrnl ){
35172    rc = read32bits(jfd, (*pOffset)-4, &cksum);
35173    if( rc ) return rc;
35174    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
35175      return SQLITE_DONE;
35176    }
35177  }
35178
35179  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
35180    return rc;
35181  }
35182
35183  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
35184
35185  /* If the pager is in RESERVED state, then there must be a copy of this
35186  ** page in the pager cache. In this case just update the pager cache,
35187  ** not the database file. The page is left marked dirty in this case.
35188  **
35189  ** An exception to the above rule: If the database is in no-sync mode
35190  ** and a page is moved during an incremental vacuum then the page may
35191  ** not be in the pager cache. Later: if a malloc() or IO error occurs
35192  ** during a Movepage() call, then the page may not be in the cache
35193  ** either. So the condition described in the above paragraph is not
35194  ** assert()able.
35195  **
35196  ** If in EXCLUSIVE state, then we update the pager cache if it exists
35197  ** and the main file. The page is then marked not dirty.
35198  **
35199  ** Ticket #1171:  The statement journal might contain page content that is
35200  ** different from the page content at the start of the transaction.
35201  ** This occurs when a page is changed prior to the start of a statement
35202  ** then changed again within the statement.  When rolling back such a
35203  ** statement we must not write to the original database unless we know
35204  ** for certain that original page contents are synced into the main rollback
35205  ** journal.  Otherwise, a power loss might leave modified data in the
35206  ** database file without an entry in the rollback journal that can
35207  ** restore the database to its original form.  Two conditions must be
35208  ** met before writing to the database files. (1) the database must be
35209  ** locked.  (2) we know that the original page content is fully synced
35210  ** in the main journal either because the page is not in cache or else
35211  ** the page is marked as needSync==0.
35212  **
35213  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
35214  ** is possible to fail a statement on a database that does not yet exist.
35215  ** Do not attempt to write if database file has never been opened.
35216  */
35217  if( pagerUseWal(pPager) ){
35218    pPg = 0;
35219  }else{
35220    pPg = pager_lookup(pPager, pgno);
35221  }
35222  assert( pPg || !MEMDB );
35223  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
35224           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
35225           (isMainJrnl?"main-journal":"sub-journal")
35226  ));
35227  if( isMainJrnl ){
35228    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
35229  }else{
35230    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
35231  }
35232  if( (pPager->state>=PAGER_EXCLUSIVE)
35233   && isOpen(pPager->fd)
35234   && isSynced
35235  ){
35236    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
35237    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
35238    assert( !pagerUseWal(pPager) );
35239    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
35240    if( pgno>pPager->dbFileSize ){
35241      pPager->dbFileSize = pgno;
35242    }
35243    if( pPager->pBackup ){
35244      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
35245      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
35246      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
35247    }
35248  }else if( !isMainJrnl && pPg==0 ){
35249    /* If this is a rollback of a savepoint and data was not written to
35250    ** the database and the page is not in-memory, there is a potential
35251    ** problem. When the page is next fetched by the b-tree layer, it
35252    ** will be read from the database file, which may or may not be
35253    ** current.
35254    **
35255    ** There are a couple of different ways this can happen. All are quite
35256    ** obscure. When running in synchronous mode, this can only happen
35257    ** if the page is on the free-list at the start of the transaction, then
35258    ** populated, then moved using sqlite3PagerMovepage().
35259    **
35260    ** The solution is to add an in-memory page to the cache containing
35261    ** the data just read from the sub-journal. Mark the page as dirty
35262    ** and if the pager requires a journal-sync, then mark the page as
35263    ** requiring a journal-sync before it is written.
35264    */
35265    assert( isSavepnt );
35266    assert( pPager->doNotSpill==0 );
35267    pPager->doNotSpill++;
35268    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
35269    assert( pPager->doNotSpill==1 );
35270    pPager->doNotSpill--;
35271    if( rc!=SQLITE_OK ) return rc;
35272    pPg->flags &= ~PGHDR_NEED_READ;
35273    sqlite3PcacheMakeDirty(pPg);
35274  }
35275  if( pPg ){
35276    /* No page should ever be explicitly rolled back that is in use, except
35277    ** for page 1 which is held in use in order to keep the lock on the
35278    ** database active. However such a page may be rolled back as a result
35279    ** of an internal error resulting in an automatic call to
35280    ** sqlite3PagerRollback().
35281    */
35282    void *pData;
35283    pData = pPg->pData;
35284    memcpy(pData, (u8*)aData, pPager->pageSize);
35285    pPager->xReiniter(pPg);
35286    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
35287      /* If the contents of this page were just restored from the main
35288      ** journal file, then its content must be as they were when the
35289      ** transaction was first opened. In this case we can mark the page
35290      ** as clean, since there will be no need to write it out to the
35291      ** database.
35292      **
35293      ** There is one exception to this rule. If the page is being rolled
35294      ** back as part of a savepoint (or statement) rollback from an
35295      ** unsynced portion of the main journal file, then it is not safe
35296      ** to mark the page as clean. This is because marking the page as
35297      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
35298      ** already in the journal file (recorded in Pager.pInJournal) and
35299      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
35300      ** again within this transaction, it will be marked as dirty but
35301      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
35302      ** be written out into the database file before its journal file
35303      ** segment is synced. If a crash occurs during or following this,
35304      ** database corruption may ensue.
35305      */
35306      assert( !pagerUseWal(pPager) );
35307      sqlite3PcacheMakeClean(pPg);
35308    }
35309#ifdef SQLITE_CHECK_PAGES
35310    pPg->pageHash = pager_pagehash(pPg);
35311#endif
35312    /* If this was page 1, then restore the value of Pager.dbFileVers.
35313    ** Do this before any decoding. */
35314    if( pgno==1 ){
35315      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
35316    }
35317
35318    /* Decode the page just read from disk */
35319    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
35320    sqlite3PcacheRelease(pPg);
35321  }
35322  return rc;
35323}
35324
35325/*
35326** Parameter zMaster is the name of a master journal file. A single journal
35327** file that referred to the master journal file has just been rolled back.
35328** This routine checks if it is possible to delete the master journal file,
35329** and does so if it is.
35330**
35331** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
35332** available for use within this function.
35333**
35334** When a master journal file is created, it is populated with the names
35335** of all of its child journals, one after another, formatted as utf-8
35336** encoded text. The end of each child journal file is marked with a
35337** nul-terminator byte (0x00). i.e. the entire contents of a master journal
35338** file for a transaction involving two databases might be:
35339**
35340**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
35341**
35342** A master journal file may only be deleted once all of its child
35343** journals have been rolled back.
35344**
35345** This function reads the contents of the master-journal file into
35346** memory and loops through each of the child journal names. For
35347** each child journal, it checks if:
35348**
35349**   * if the child journal exists, and if so
35350**   * if the child journal contains a reference to master journal
35351**     file zMaster
35352**
35353** If a child journal can be found that matches both of the criteria
35354** above, this function returns without doing anything. Otherwise, if
35355** no such child journal can be found, file zMaster is deleted from
35356** the file-system using sqlite3OsDelete().
35357**
35358** If an IO error within this function, an error code is returned. This
35359** function allocates memory by calling sqlite3Malloc(). If an allocation
35360** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
35361** occur, SQLITE_OK is returned.
35362**
35363** TODO: This function allocates a single block of memory to load
35364** the entire contents of the master journal file. This could be
35365** a couple of kilobytes or so - potentially larger than the page
35366** size.
35367*/
35368static int pager_delmaster(Pager *pPager, const char *zMaster){
35369  sqlite3_vfs *pVfs = pPager->pVfs;
35370  int rc;                   /* Return code */
35371  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
35372  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
35373  char *zMasterJournal = 0; /* Contents of master journal file */
35374  i64 nMasterJournal;       /* Size of master journal file */
35375  char *zJournal;           /* Pointer to one journal within MJ file */
35376  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
35377  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
35378
35379  /* Allocate space for both the pJournal and pMaster file descriptors.
35380  ** If successful, open the master journal file for reading.
35381  */
35382  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
35383  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
35384  if( !pMaster ){
35385    rc = SQLITE_NOMEM;
35386  }else{
35387    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
35388    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
35389  }
35390  if( rc!=SQLITE_OK ) goto delmaster_out;
35391
35392  /* Load the entire master journal file into space obtained from
35393  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
35394  ** sufficient space (in zMasterPtr) to hold the names of master
35395  ** journal files extracted from regular rollback-journals.
35396  */
35397  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
35398  if( rc!=SQLITE_OK ) goto delmaster_out;
35399  nMasterPtr = pVfs->mxPathname+1;
35400  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
35401  if( !zMasterJournal ){
35402    rc = SQLITE_NOMEM;
35403    goto delmaster_out;
35404  }
35405  zMasterPtr = &zMasterJournal[nMasterJournal+1];
35406  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
35407  if( rc!=SQLITE_OK ) goto delmaster_out;
35408  zMasterJournal[nMasterJournal] = 0;
35409
35410  zJournal = zMasterJournal;
35411  while( (zJournal-zMasterJournal)<nMasterJournal ){
35412    int exists;
35413    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
35414    if( rc!=SQLITE_OK ){
35415      goto delmaster_out;
35416    }
35417    if( exists ){
35418      /* One of the journals pointed to by the master journal exists.
35419      ** Open it and check if it points at the master journal. If
35420      ** so, return without deleting the master journal file.
35421      */
35422      int c;
35423      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
35424      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
35425      if( rc!=SQLITE_OK ){
35426        goto delmaster_out;
35427      }
35428
35429      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
35430      sqlite3OsClose(pJournal);
35431      if( rc!=SQLITE_OK ){
35432        goto delmaster_out;
35433      }
35434
35435      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
35436      if( c ){
35437        /* We have a match. Do not delete the master journal file. */
35438        goto delmaster_out;
35439      }
35440    }
35441    zJournal += (sqlite3Strlen30(zJournal)+1);
35442  }
35443
35444  sqlite3OsClose(pMaster);
35445  rc = sqlite3OsDelete(pVfs, zMaster, 0);
35446
35447delmaster_out:
35448  sqlite3_free(zMasterJournal);
35449  if( pMaster ){
35450    sqlite3OsClose(pMaster);
35451    assert( !isOpen(pJournal) );
35452    sqlite3_free(pMaster);
35453  }
35454  return rc;
35455}
35456
35457
35458/*
35459** This function is used to change the actual size of the database
35460** file in the file-system. This only happens when committing a transaction,
35461** or rolling back a transaction (including rolling back a hot-journal).
35462**
35463** If the main database file is not open, or an exclusive lock is not
35464** held, this function is a no-op. Otherwise, the size of the file is
35465** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
35466** on disk is currently larger than nPage pages, then use the VFS
35467** xTruncate() method to truncate it.
35468**
35469** Or, it might might be the case that the file on disk is smaller than
35470** nPage pages. Some operating system implementations can get confused if
35471** you try to truncate a file to some size that is larger than it
35472** currently is, so detect this case and write a single zero byte to
35473** the end of the new file instead.
35474**
35475** If successful, return SQLITE_OK. If an IO error occurs while modifying
35476** the database file, return the error code to the caller.
35477*/
35478static int pager_truncate(Pager *pPager, Pgno nPage){
35479  int rc = SQLITE_OK;
35480  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
35481    i64 currentSize, newSize;
35482    /* TODO: Is it safe to use Pager.dbFileSize here? */
35483    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
35484    newSize = pPager->pageSize*(i64)nPage;
35485    if( rc==SQLITE_OK && currentSize!=newSize ){
35486      if( currentSize>newSize ){
35487        rc = sqlite3OsTruncate(pPager->fd, newSize);
35488      }else{
35489        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
35490      }
35491      if( rc==SQLITE_OK ){
35492        pPager->dbFileSize = nPage;
35493      }
35494    }
35495  }
35496  return rc;
35497}
35498
35499/*
35500** Set the value of the Pager.sectorSize variable for the given
35501** pager based on the value returned by the xSectorSize method
35502** of the open database file. The sector size will be used used
35503** to determine the size and alignment of journal header and
35504** master journal pointers within created journal files.
35505**
35506** For temporary files the effective sector size is always 512 bytes.
35507**
35508** Otherwise, for non-temporary files, the effective sector size is
35509** the value returned by the xSectorSize() method rounded up to 32 if
35510** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
35511** is greater than MAX_SECTOR_SIZE.
35512*/
35513static void setSectorSize(Pager *pPager){
35514  assert( isOpen(pPager->fd) || pPager->tempFile );
35515
35516  if( !pPager->tempFile ){
35517    /* Sector size doesn't matter for temporary files. Also, the file
35518    ** may not have been opened yet, in which case the OsSectorSize()
35519    ** call will segfault.
35520    */
35521    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
35522  }
35523  if( pPager->sectorSize<32 ){
35524    pPager->sectorSize = 512;
35525  }
35526  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
35527    assert( MAX_SECTOR_SIZE>=512 );
35528    pPager->sectorSize = MAX_SECTOR_SIZE;
35529  }
35530}
35531
35532/*
35533** Playback the journal and thus restore the database file to
35534** the state it was in before we started making changes.
35535**
35536** The journal file format is as follows:
35537**
35538**  (1)  8 byte prefix.  A copy of aJournalMagic[].
35539**  (2)  4 byte big-endian integer which is the number of valid page records
35540**       in the journal.  If this value is 0xffffffff, then compute the
35541**       number of page records from the journal size.
35542**  (3)  4 byte big-endian integer which is the initial value for the
35543**       sanity checksum.
35544**  (4)  4 byte integer which is the number of pages to truncate the
35545**       database to during a rollback.
35546**  (5)  4 byte big-endian integer which is the sector size.  The header
35547**       is this many bytes in size.
35548**  (6)  4 byte big-endian integer which is the page size.
35549**  (7)  zero padding out to the next sector size.
35550**  (8)  Zero or more pages instances, each as follows:
35551**        +  4 byte page number.
35552**        +  pPager->pageSize bytes of data.
35553**        +  4 byte checksum
35554**
35555** When we speak of the journal header, we mean the first 7 items above.
35556** Each entry in the journal is an instance of the 8th item.
35557**
35558** Call the value from the second bullet "nRec".  nRec is the number of
35559** valid page entries in the journal.  In most cases, you can compute the
35560** value of nRec from the size of the journal file.  But if a power
35561** failure occurred while the journal was being written, it could be the
35562** case that the size of the journal file had already been increased but
35563** the extra entries had not yet made it safely to disk.  In such a case,
35564** the value of nRec computed from the file size would be too large.  For
35565** that reason, we always use the nRec value in the header.
35566**
35567** If the nRec value is 0xffffffff it means that nRec should be computed
35568** from the file size.  This value is used when the user selects the
35569** no-sync option for the journal.  A power failure could lead to corruption
35570** in this case.  But for things like temporary table (which will be
35571** deleted when the power is restored) we don't care.
35572**
35573** If the file opened as the journal file is not a well-formed
35574** journal file then all pages up to the first corrupted page are rolled
35575** back (or no pages if the journal header is corrupted). The journal file
35576** is then deleted and SQLITE_OK returned, just as if no corruption had
35577** been encountered.
35578**
35579** If an I/O or malloc() error occurs, the journal-file is not deleted
35580** and an error code is returned.
35581**
35582** The isHot parameter indicates that we are trying to rollback a journal
35583** that might be a hot journal.  Or, it could be that the journal is
35584** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
35585** If the journal really is hot, reset the pager cache prior rolling
35586** back any content.  If the journal is merely persistent, no reset is
35587** needed.
35588*/
35589static int pager_playback(Pager *pPager, int isHot){
35590  sqlite3_vfs *pVfs = pPager->pVfs;
35591  i64 szJ;                 /* Size of the journal file in bytes */
35592  u32 nRec;                /* Number of Records in the journal */
35593  u32 u;                   /* Unsigned loop counter */
35594  Pgno mxPg = 0;           /* Size of the original file in pages */
35595  int rc;                  /* Result code of a subroutine */
35596  int res = 1;             /* Value returned by sqlite3OsAccess() */
35597  char *zMaster = 0;       /* Name of master journal file if any */
35598  int needPagerReset;      /* True to reset page prior to first page rollback */
35599
35600  /* Figure out how many records are in the journal.  Abort early if
35601  ** the journal is empty.
35602  */
35603  assert( isOpen(pPager->jfd) );
35604  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
35605  if( rc!=SQLITE_OK || szJ==0 ){
35606    goto end_playback;
35607  }
35608
35609  /* Read the master journal name from the journal, if it is present.
35610  ** If a master journal file name is specified, but the file is not
35611  ** present on disk, then the journal is not hot and does not need to be
35612  ** played back.
35613  **
35614  ** TODO: Technically the following is an error because it assumes that
35615  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
35616  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
35617  **  mxPathname is 512, which is the same as the minimum allowable value
35618  ** for pageSize.
35619  */
35620  zMaster = pPager->pTmpSpace;
35621  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
35622  if( rc==SQLITE_OK && zMaster[0] ){
35623    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
35624  }
35625  zMaster = 0;
35626  if( rc!=SQLITE_OK || !res ){
35627    goto end_playback;
35628  }
35629  pPager->journalOff = 0;
35630  needPagerReset = isHot;
35631
35632  /* This loop terminates either when a readJournalHdr() or
35633  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
35634  ** occurs.
35635  */
35636  while( 1 ){
35637    /* Read the next journal header from the journal file.  If there are
35638    ** not enough bytes left in the journal file for a complete header, or
35639    ** it is corrupted, then a process must of failed while writing it.
35640    ** This indicates nothing more needs to be rolled back.
35641    */
35642    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
35643    if( rc!=SQLITE_OK ){
35644      if( rc==SQLITE_DONE ){
35645        rc = SQLITE_OK;
35646      }
35647      goto end_playback;
35648    }
35649
35650    /* If nRec is 0xffffffff, then this journal was created by a process
35651    ** working in no-sync mode. This means that the rest of the journal
35652    ** file consists of pages, there are no more journal headers. Compute
35653    ** the value of nRec based on this assumption.
35654    */
35655    if( nRec==0xffffffff ){
35656      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35657      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
35658    }
35659
35660    /* If nRec is 0 and this rollback is of a transaction created by this
35661    ** process and if this is the final header in the journal, then it means
35662    ** that this part of the journal was being filled but has not yet been
35663    ** synced to disk.  Compute the number of pages based on the remaining
35664    ** size of the file.
35665    **
35666    ** The third term of the test was added to fix ticket #2565.
35667    ** When rolling back a hot journal, nRec==0 always means that the next
35668    ** chunk of the journal contains zero pages to be rolled back.  But
35669    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
35670    ** the journal, it means that the journal might contain additional
35671    ** pages that need to be rolled back and that the number of pages
35672    ** should be computed based on the journal file size.
35673    */
35674    if( nRec==0 && !isHot &&
35675        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
35676      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
35677    }
35678
35679    /* If this is the first header read from the journal, truncate the
35680    ** database file back to its original size.
35681    */
35682    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
35683      rc = pager_truncate(pPager, mxPg);
35684      if( rc!=SQLITE_OK ){
35685        goto end_playback;
35686      }
35687      pPager->dbSize = mxPg;
35688    }
35689
35690    /* Copy original pages out of the journal and back into the
35691    ** database file and/or page cache.
35692    */
35693    for(u=0; u<nRec; u++){
35694      if( needPagerReset ){
35695        pager_reset(pPager);
35696        needPagerReset = 0;
35697      }
35698      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
35699      if( rc!=SQLITE_OK ){
35700        if( rc==SQLITE_DONE ){
35701          rc = SQLITE_OK;
35702          pPager->journalOff = szJ;
35703          break;
35704        }else if( rc==SQLITE_IOERR_SHORT_READ ){
35705          /* If the journal has been truncated, simply stop reading and
35706          ** processing the journal. This might happen if the journal was
35707          ** not completely written and synced prior to a crash.  In that
35708          ** case, the database should have never been written in the
35709          ** first place so it is OK to simply abandon the rollback. */
35710          rc = SQLITE_OK;
35711          goto end_playback;
35712        }else{
35713          /* If we are unable to rollback, quit and return the error
35714          ** code.  This will cause the pager to enter the error state
35715          ** so that no further harm will be done.  Perhaps the next
35716          ** process to come along will be able to rollback the database.
35717          */
35718          goto end_playback;
35719        }
35720      }
35721    }
35722  }
35723  /*NOTREACHED*/
35724  assert( 0 );
35725
35726end_playback:
35727  /* Following a rollback, the database file should be back in its original
35728  ** state prior to the start of the transaction, so invoke the
35729  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
35730  ** assertion that the transaction counter was modified.
35731  */
35732  assert(
35733    pPager->fd->pMethods==0 ||
35734    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
35735  );
35736
35737  /* If this playback is happening automatically as a result of an IO or
35738  ** malloc error that occurred after the change-counter was updated but
35739  ** before the transaction was committed, then the change-counter
35740  ** modification may just have been reverted. If this happens in exclusive
35741  ** mode, then subsequent transactions performed by the connection will not
35742  ** update the change-counter at all. This may lead to cache inconsistency
35743  ** problems for other processes at some point in the future. So, just
35744  ** in case this has happened, clear the changeCountDone flag now.
35745  */
35746  pPager->changeCountDone = pPager->tempFile;
35747
35748  if( rc==SQLITE_OK ){
35749    zMaster = pPager->pTmpSpace;
35750    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
35751    testcase( rc!=SQLITE_OK );
35752  }
35753  if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
35754    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35755  }
35756  if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
35757    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35758  }
35759  if( rc==SQLITE_OK ){
35760    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
35761    testcase( rc!=SQLITE_OK );
35762  }
35763  if( rc==SQLITE_OK && zMaster[0] && res ){
35764    /* If there was a master journal and this routine will return success,
35765    ** see if it is possible to delete the master journal.
35766    */
35767    rc = pager_delmaster(pPager, zMaster);
35768    testcase( rc!=SQLITE_OK );
35769  }
35770
35771  /* The Pager.sectorSize variable may have been updated while rolling
35772  ** back a journal created by a process with a different sector size
35773  ** value. Reset it to the correct value for this process.
35774  */
35775  setSectorSize(pPager);
35776  return rc;
35777}
35778
35779
35780/*
35781** Read the content for page pPg out of the database file and into
35782** pPg->pData. A shared lock or greater must be held on the database
35783** file before this function is called.
35784**
35785** If page 1 is read, then the value of Pager.dbFileVers[] is set to
35786** the value read from the database file.
35787**
35788** If an IO error occurs, then the IO error is returned to the caller.
35789** Otherwise, SQLITE_OK is returned.
35790*/
35791static int readDbPage(PgHdr *pPg){
35792  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
35793  Pgno pgno = pPg->pgno;       /* Page number to read */
35794  int rc = SQLITE_OK;          /* Return code */
35795  int isInWal = 0;             /* True if page is in log file */
35796  int pgsz = pPager->pageSize; /* Number of bytes to read */
35797
35798  assert( pPager->state>=PAGER_SHARED && !MEMDB );
35799  assert( isOpen(pPager->fd) );
35800
35801  if( NEVER(!isOpen(pPager->fd)) ){
35802    assert( pPager->tempFile );
35803    memset(pPg->pData, 0, pPager->pageSize);
35804    return SQLITE_OK;
35805  }
35806
35807  if( pagerUseWal(pPager) ){
35808    /* Try to pull the page from the write-ahead log. */
35809    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
35810  }
35811  if( rc==SQLITE_OK && !isInWal ){
35812    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
35813    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
35814    if( rc==SQLITE_IOERR_SHORT_READ ){
35815      rc = SQLITE_OK;
35816    }
35817  }
35818
35819  if( pgno==1 ){
35820    if( rc ){
35821      /* If the read is unsuccessful, set the dbFileVers[] to something
35822      ** that will never be a valid file version.  dbFileVers[] is a copy
35823      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
35824      ** zero or the size of the database in page. Bytes 32..35 and 35..39
35825      ** should be page numbers which are never 0xffffffff.  So filling
35826      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
35827      **
35828      ** For an encrypted database, the situation is more complex:  bytes
35829      ** 24..39 of the database are white noise.  But the probability of
35830      ** white noising equaling 16 bytes of 0xff is vanishingly small so
35831      ** we should still be ok.
35832      */
35833      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
35834    }else{
35835      u8 *dbFileVers = &((u8*)pPg->pData)[24];
35836      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
35837    }
35838  }
35839  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
35840
35841  PAGER_INCR(sqlite3_pager_readdb_count);
35842  PAGER_INCR(pPager->nRead);
35843  IOTRACE(("PGIN %p %d\n", pPager, pgno));
35844  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
35845               PAGERID(pPager), pgno, pager_pagehash(pPg)));
35846
35847  return rc;
35848}
35849
35850#ifndef SQLITE_OMIT_WAL
35851/*
35852** This function is invoked once for each page that has already been
35853** written into the log file when a WAL transaction is rolled back.
35854** Parameter iPg is the page number of said page. The pCtx argument
35855** is actually a pointer to the Pager structure.
35856**
35857** If page iPg is present in the cache, and has no outstanding references,
35858** it is discarded. Otherwise, if there are one or more outstanding
35859** references, the page content is reloaded from the database. If the
35860** attempt to reload content from the database is required and fails,
35861** return an SQLite error code. Otherwise, SQLITE_OK.
35862*/
35863static int pagerUndoCallback(void *pCtx, Pgno iPg){
35864  int rc = SQLITE_OK;
35865  Pager *pPager = (Pager *)pCtx;
35866  PgHdr *pPg;
35867
35868  pPg = sqlite3PagerLookup(pPager, iPg);
35869  if( pPg ){
35870    if( sqlite3PcachePageRefcount(pPg)==1 ){
35871      sqlite3PcacheDrop(pPg);
35872    }else{
35873      rc = readDbPage(pPg);
35874      if( rc==SQLITE_OK ){
35875        pPager->xReiniter(pPg);
35876      }
35877      sqlite3PagerUnref(pPg);
35878    }
35879  }
35880
35881  /* Normally, if a transaction is rolled back, any backup processes are
35882  ** updated as data is copied out of the rollback journal and into the
35883  ** database. This is not generally possible with a WAL database, as
35884  ** rollback involves simply truncating the log file. Therefore, if one
35885  ** or more frames have already been written to the log (and therefore
35886  ** also copied into the backup databases) as part of this transaction,
35887  ** the backups must be restarted.
35888  */
35889  sqlite3BackupRestart(pPager->pBackup);
35890
35891  return rc;
35892}
35893
35894/*
35895** This function is called to rollback a transaction on a WAL database.
35896*/
35897static int pagerRollbackWal(Pager *pPager){
35898  int rc;                         /* Return Code */
35899  PgHdr *pList;                   /* List of dirty pages to revert */
35900
35901  /* For all pages in the cache that are currently dirty or have already
35902  ** been written (but not committed) to the log file, do one of the
35903  ** following:
35904  **
35905  **   + Discard the cached page (if refcount==0), or
35906  **   + Reload page content from the database (if refcount>0).
35907  */
35908  pPager->dbSize = pPager->dbOrigSize;
35909  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
35910  pList = sqlite3PcacheDirtyList(pPager->pPCache);
35911  while( pList && rc==SQLITE_OK ){
35912    PgHdr *pNext = pList->pDirty;
35913    rc = pagerUndoCallback((void *)pPager, pList->pgno);
35914    pList = pNext;
35915  }
35916
35917  return rc;
35918}
35919
35920/*
35921** This function is a wrapper around sqlite3WalFrames(). As well as logging
35922** the contents of the list of pages headed by pList (connected by pDirty),
35923** this function notifies any active backup processes that the pages have
35924** changed.
35925*/
35926static int pagerWalFrames(
35927  Pager *pPager,                  /* Pager object */
35928  PgHdr *pList,                   /* List of frames to log */
35929  Pgno nTruncate,                 /* Database size after this commit */
35930  int isCommit,                   /* True if this is a commit */
35931  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
35932){
35933  int rc;                         /* Return code */
35934
35935  assert( pPager->pWal );
35936  rc = sqlite3WalFrames(pPager->pWal,
35937      pPager->pageSize, pList, nTruncate, isCommit, sync_flags
35938  );
35939  if( rc==SQLITE_OK && pPager->pBackup ){
35940    PgHdr *p;
35941    for(p=pList; p; p=p->pDirty){
35942      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
35943    }
35944  }
35945  return rc;
35946}
35947
35948/*
35949** Begin a read transaction on the WAL.
35950**
35951** This routine used to be called "pagerOpenSnapshot()" because it essentially
35952** makes a snapshot of the database at the current point in time and preserves
35953** that snapshot for use by the reader in spite of concurrently changes by
35954** other writers or checkpointers.
35955*/
35956static int pagerBeginReadTransaction(Pager *pPager){
35957  int rc;                         /* Return code */
35958  int changed = 0;                /* True if cache must be reset */
35959
35960  assert( pagerUseWal(pPager) );
35961
35962  /* sqlite3WalEndReadTransaction() was not called for the previous
35963  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
35964  ** are in locking_mode=NORMAL and EndRead() was previously called,
35965  ** the duplicate call is harmless.
35966  */
35967  sqlite3WalEndReadTransaction(pPager->pWal);
35968
35969  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
35970  if( rc==SQLITE_OK ){
35971    int dummy;
35972    if( changed ){
35973      pager_reset(pPager);
35974      assert( pPager->errCode || pPager->dbSizeValid==0 );
35975    }
35976    rc = sqlite3PagerPagecount(pPager, &dummy);
35977  }
35978  pPager->state = PAGER_SHARED;
35979
35980  return rc;
35981}
35982
35983/*
35984** Check if the *-wal file that corresponds to the database opened by pPager
35985** exists. Assuming no error occurs, set *pExists to 1 if the file exists,
35986** or 0 otherwise and return SQLITE_OK. If an IO or OOM error occurs, return
35987** an SQLite error code.
35988*/
35989static int pagerHasWAL(Pager *pPager, int *pExists){
35990  int rc;                         /* Return code */
35991  char *zWal;                     /* Name of the WAL file */
35992
35993  assert( !pPager->tempFile );
35994  zWal = sqlite3_mprintf("%s-wal", pPager->zFilename);
35995  if( !zWal ){
35996    rc = SQLITE_NOMEM;
35997  }else{
35998    rc = sqlite3OsAccess(pPager->pVfs, zWal, SQLITE_ACCESS_EXISTS, pExists);
35999    sqlite3_free(zWal);
36000  }
36001  return rc;
36002}
36003
36004/*
36005** Check if the *-wal file that corresponds to the database opened by pPager
36006** exists. If it does, open the pager in WAL mode. Otherwise, if no error
36007** occurs, make sure Pager.journalMode is not set to PAGER_JOURNALMODE_WAL.
36008** If an IO or OOM error occurs, return an SQLite error code.
36009**
36010** If the WAL file is opened, also open a snapshot (read transaction).
36011**
36012** The caller must hold a SHARED lock on the database file to call this
36013** function. Because an EXCLUSIVE lock on the db file is required to delete
36014** a WAL, this ensures there is no race condition between the xAccess()
36015** below and an xDelete() being executed by some other connection.
36016*/
36017static int pagerOpenWalIfPresent(Pager *pPager){
36018  int rc = SQLITE_OK;
36019  if( !pPager->tempFile ){
36020    int isWal;                    /* True if WAL file exists */
36021    rc = pagerHasWAL(pPager, &isWal);
36022    if( rc==SQLITE_OK ){
36023      if( isWal ){
36024        pager_reset(pPager);
36025        rc = sqlite3PagerOpenWal(pPager, 0);
36026        if( rc==SQLITE_OK ){
36027          rc = pagerBeginReadTransaction(pPager);
36028        }
36029      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
36030        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
36031      }
36032    }
36033  }
36034  return rc;
36035}
36036#endif
36037
36038/*
36039** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
36040** the entire master journal file. The case pSavepoint==NULL occurs when
36041** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
36042** savepoint.
36043**
36044** When pSavepoint is not NULL (meaning a non-transaction savepoint is
36045** being rolled back), then the rollback consists of up to three stages,
36046** performed in the order specified:
36047**
36048**   * Pages are played back from the main journal starting at byte
36049**     offset PagerSavepoint.iOffset and continuing to
36050**     PagerSavepoint.iHdrOffset, or to the end of the main journal
36051**     file if PagerSavepoint.iHdrOffset is zero.
36052**
36053**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
36054**     back starting from the journal header immediately following
36055**     PagerSavepoint.iHdrOffset to the end of the main journal file.
36056**
36057**   * Pages are then played back from the sub-journal file, starting
36058**     with the PagerSavepoint.iSubRec and continuing to the end of
36059**     the journal file.
36060**
36061** Throughout the rollback process, each time a page is rolled back, the
36062** corresponding bit is set in a bitvec structure (variable pDone in the
36063** implementation below). This is used to ensure that a page is only
36064** rolled back the first time it is encountered in either journal.
36065**
36066** If pSavepoint is NULL, then pages are only played back from the main
36067** journal file. There is no need for a bitvec in this case.
36068**
36069** In either case, before playback commences the Pager.dbSize variable
36070** is reset to the value that it held at the start of the savepoint
36071** (or transaction). No page with a page-number greater than this value
36072** is played back. If one is encountered it is simply skipped.
36073*/
36074static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
36075  i64 szJ;                 /* Effective size of the main journal */
36076  i64 iHdrOff;             /* End of first segment of main-journal records */
36077  int rc = SQLITE_OK;      /* Return code */
36078  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
36079
36080  assert( pPager->state>=PAGER_SHARED );
36081
36082  /* Allocate a bitvec to use to store the set of pages rolled back */
36083  if( pSavepoint ){
36084    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
36085    if( !pDone ){
36086      return SQLITE_NOMEM;
36087    }
36088  }
36089
36090  /* Set the database size back to the value it was before the savepoint
36091  ** being reverted was opened.
36092  */
36093  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
36094
36095  if( !pSavepoint && pagerUseWal(pPager) ){
36096    return pagerRollbackWal(pPager);
36097  }
36098
36099  /* Use pPager->journalOff as the effective size of the main rollback
36100  ** journal.  The actual file might be larger than this in
36101  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
36102  ** past pPager->journalOff is off-limits to us.
36103  */
36104  szJ = pPager->journalOff;
36105  assert( pagerUseWal(pPager)==0 || szJ==0 );
36106
36107  /* Begin by rolling back records from the main journal starting at
36108  ** PagerSavepoint.iOffset and continuing to the next journal header.
36109  ** There might be records in the main journal that have a page number
36110  ** greater than the current database size (pPager->dbSize) but those
36111  ** will be skipped automatically.  Pages are added to pDone as they
36112  ** are played back.
36113  */
36114  if( pSavepoint && !pagerUseWal(pPager) ){
36115    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
36116    pPager->journalOff = pSavepoint->iOffset;
36117    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
36118      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36119    }
36120    assert( rc!=SQLITE_DONE );
36121  }else{
36122    pPager->journalOff = 0;
36123  }
36124
36125  /* Continue rolling back records out of the main journal starting at
36126  ** the first journal header seen and continuing until the effective end
36127  ** of the main journal file.  Continue to skip out-of-range pages and
36128  ** continue adding pages rolled back to pDone.
36129  */
36130  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
36131    u32 ii;            /* Loop counter */
36132    u32 nJRec = 0;     /* Number of Journal Records */
36133    u32 dummy;
36134    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
36135    assert( rc!=SQLITE_DONE );
36136
36137    /*
36138    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
36139    ** test is related to ticket #2565.  See the discussion in the
36140    ** pager_playback() function for additional information.
36141    */
36142    if( nJRec==0
36143     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
36144    ){
36145      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
36146    }
36147    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
36148      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36149    }
36150    assert( rc!=SQLITE_DONE );
36151  }
36152  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
36153
36154  /* Finally,  rollback pages from the sub-journal.  Page that were
36155  ** previously rolled back out of the main journal (and are hence in pDone)
36156  ** will be skipped.  Out-of-range pages are also skipped.
36157  */
36158  if( pSavepoint ){
36159    u32 ii;            /* Loop counter */
36160    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
36161
36162    if( pagerUseWal(pPager) ){
36163      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
36164    }
36165    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
36166      assert( offset==ii*(4+pPager->pageSize) );
36167      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
36168    }
36169    assert( rc!=SQLITE_DONE );
36170  }
36171
36172  sqlite3BitvecDestroy(pDone);
36173  if( rc==SQLITE_OK ){
36174    pPager->journalOff = szJ;
36175  }
36176
36177  return rc;
36178}
36179
36180/*
36181** Change the maximum number of in-memory pages that are allowed.
36182*/
36183SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
36184  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
36185}
36186
36187/*
36188** Adjust the robustness of the database to damage due to OS crashes
36189** or power failures by changing the number of syncs()s when writing
36190** the rollback journal.  There are three levels:
36191**
36192**    OFF       sqlite3OsSync() is never called.  This is the default
36193**              for temporary and transient files.
36194**
36195**    NORMAL    The journal is synced once before writes begin on the
36196**              database.  This is normally adequate protection, but
36197**              it is theoretically possible, though very unlikely,
36198**              that an inopertune power failure could leave the journal
36199**              in a state which would cause damage to the database
36200**              when it is rolled back.
36201**
36202**    FULL      The journal is synced twice before writes begin on the
36203**              database (with some additional information - the nRec field
36204**              of the journal header - being written in between the two
36205**              syncs).  If we assume that writing a
36206**              single disk sector is atomic, then this mode provides
36207**              assurance that the journal will not be corrupted to the
36208**              point of causing damage to the database during rollback.
36209**
36210** Numeric values associated with these states are OFF==1, NORMAL=2,
36211** and FULL=3.
36212*/
36213#ifndef SQLITE_OMIT_PAGER_PRAGMAS
36214SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
36215  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
36216  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
36217  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
36218  if( pPager->noSync ) pPager->needSync = 0;
36219}
36220#endif
36221
36222/*
36223** The following global variable is incremented whenever the library
36224** attempts to open a temporary file.  This information is used for
36225** testing and analysis only.
36226*/
36227#ifdef SQLITE_TEST
36228SQLITE_API int sqlite3_opentemp_count = 0;
36229#endif
36230
36231/*
36232** Open a temporary file.
36233**
36234** Write the file descriptor into *pFile. Return SQLITE_OK on success
36235** or some other error code if we fail. The OS will automatically
36236** delete the temporary file when it is closed.
36237**
36238** The flags passed to the VFS layer xOpen() call are those specified
36239** by parameter vfsFlags ORed with the following:
36240**
36241**     SQLITE_OPEN_READWRITE
36242**     SQLITE_OPEN_CREATE
36243**     SQLITE_OPEN_EXCLUSIVE
36244**     SQLITE_OPEN_DELETEONCLOSE
36245*/
36246static int pagerOpentemp(
36247  Pager *pPager,        /* The pager object */
36248  sqlite3_file *pFile,  /* Write the file descriptor here */
36249  int vfsFlags          /* Flags passed through to the VFS */
36250){
36251  int rc;               /* Return code */
36252
36253#ifdef SQLITE_TEST
36254  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
36255#endif
36256
36257  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
36258            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
36259  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
36260  assert( rc!=SQLITE_OK || isOpen(pFile) );
36261  return rc;
36262}
36263
36264/*
36265** Set the busy handler function.
36266**
36267** The pager invokes the busy-handler if sqlite3OsLock() returns
36268** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
36269** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
36270** lock. It does *not* invoke the busy handler when upgrading from
36271** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
36272** (which occurs during hot-journal rollback). Summary:
36273**
36274**   Transition                        | Invokes xBusyHandler
36275**   --------------------------------------------------------
36276**   NO_LOCK       -> SHARED_LOCK      | Yes
36277**   SHARED_LOCK   -> RESERVED_LOCK    | No
36278**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
36279**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
36280**
36281** If the busy-handler callback returns non-zero, the lock is
36282** retried. If it returns zero, then the SQLITE_BUSY error is
36283** returned to the caller of the pager API function.
36284*/
36285SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
36286  Pager *pPager,                       /* Pager object */
36287  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
36288  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
36289){
36290  pPager->xBusyHandler = xBusyHandler;
36291  pPager->pBusyHandlerArg = pBusyHandlerArg;
36292}
36293
36294/*
36295** Report the current page size and number of reserved bytes back
36296** to the codec.
36297*/
36298#ifdef SQLITE_HAS_CODEC
36299static void pagerReportSize(Pager *pPager){
36300  if( pPager->xCodecSizeChng ){
36301    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36302                           (int)pPager->nReserve);
36303  }
36304}
36305#else
36306# define pagerReportSize(X)     /* No-op if we do not support a codec */
36307#endif
36308
36309/*
36310** Change the page size used by the Pager object. The new page size
36311** is passed in *pPageSize.
36312**
36313** If the pager is in the error state when this function is called, it
36314** is a no-op. The value returned is the error state error code (i.e.
36315** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
36316**
36317** Otherwise, if all of the following are true:
36318**
36319**   * the new page size (value of *pPageSize) is valid (a power
36320**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
36321**
36322**   * there are no outstanding page references, and
36323**
36324**   * the database is either not an in-memory database or it is
36325**     an in-memory database that currently consists of zero pages.
36326**
36327** then the pager object page size is set to *pPageSize.
36328**
36329** If the page size is changed, then this function uses sqlite3PagerMalloc()
36330** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
36331** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
36332** In all other cases, SQLITE_OK is returned.
36333**
36334** If the page size is not changed, either because one of the enumerated
36335** conditions above is not true, the pager was in error state when this
36336** function was called, or because the memory allocation attempt failed,
36337** then *pPageSize is set to the old, retained page size before returning.
36338*/
36339SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
36340  int rc = pPager->errCode;
36341
36342  if( rc==SQLITE_OK ){
36343    u16 pageSize = *pPageSize;
36344    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
36345    if( (pPager->memDb==0 || pPager->dbSize==0)
36346     && sqlite3PcacheRefCount(pPager->pPCache)==0
36347     && pageSize && pageSize!=pPager->pageSize
36348    ){
36349      char *pNew = (char *)sqlite3PageMalloc(pageSize);
36350      if( !pNew ){
36351        rc = SQLITE_NOMEM;
36352      }else{
36353        pager_reset(pPager);
36354        pPager->pageSize = pageSize;
36355        sqlite3PageFree(pPager->pTmpSpace);
36356        pPager->pTmpSpace = pNew;
36357        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
36358      }
36359    }
36360    *pPageSize = (u16)pPager->pageSize;
36361    if( nReserve<0 ) nReserve = pPager->nReserve;
36362    assert( nReserve>=0 && nReserve<1000 );
36363    pPager->nReserve = (i16)nReserve;
36364    pagerReportSize(pPager);
36365  }
36366  return rc;
36367}
36368
36369/*
36370** Return a pointer to the "temporary page" buffer held internally
36371** by the pager.  This is a buffer that is big enough to hold the
36372** entire content of a database page.  This buffer is used internally
36373** during rollback and will be overwritten whenever a rollback
36374** occurs.  But other modules are free to use it too, as long as
36375** no rollbacks are happening.
36376*/
36377SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
36378  return pPager->pTmpSpace;
36379}
36380
36381/*
36382** Attempt to set the maximum database page count if mxPage is positive.
36383** Make no changes if mxPage is zero or negative.  And never reduce the
36384** maximum page count below the current size of the database.
36385**
36386** Regardless of mxPage, return the current maximum page count.
36387*/
36388SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
36389  int nPage;
36390  if( mxPage>0 ){
36391    pPager->mxPgno = mxPage;
36392  }
36393  if( pPager->state!=PAGER_UNLOCK ){
36394    sqlite3PagerPagecount(pPager, &nPage);
36395    assert( pPager->mxPgno>=nPage );
36396  }
36397  return pPager->mxPgno;
36398}
36399
36400/*
36401** The following set of routines are used to disable the simulated
36402** I/O error mechanism.  These routines are used to avoid simulated
36403** errors in places where we do not care about errors.
36404**
36405** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
36406** and generate no code.
36407*/
36408#ifdef SQLITE_TEST
36409SQLITE_API extern int sqlite3_io_error_pending;
36410SQLITE_API extern int sqlite3_io_error_hit;
36411static int saved_cnt;
36412void disable_simulated_io_errors(void){
36413  saved_cnt = sqlite3_io_error_pending;
36414  sqlite3_io_error_pending = -1;
36415}
36416void enable_simulated_io_errors(void){
36417  sqlite3_io_error_pending = saved_cnt;
36418}
36419#else
36420# define disable_simulated_io_errors()
36421# define enable_simulated_io_errors()
36422#endif
36423
36424/*
36425** Read the first N bytes from the beginning of the file into memory
36426** that pDest points to.
36427**
36428** If the pager was opened on a transient file (zFilename==""), or
36429** opened on a file less than N bytes in size, the output buffer is
36430** zeroed and SQLITE_OK returned. The rationale for this is that this
36431** function is used to read database headers, and a new transient or
36432** zero sized database has a header than consists entirely of zeroes.
36433**
36434** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
36435** the error code is returned to the caller and the contents of the
36436** output buffer undefined.
36437*/
36438SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
36439  int rc = SQLITE_OK;
36440  memset(pDest, 0, N);
36441  assert( isOpen(pPager->fd) || pPager->tempFile );
36442
36443  /* This routine is only called by btree immediately after creating
36444  ** the Pager object.  There has not been an opportunity to transition
36445  ** to WAL mode yet.
36446  */
36447  assert( !pagerUseWal(pPager) );
36448#if 0
36449  if( pagerUseWal(pPager) ){
36450    int isInWal = 0;
36451    rc = sqlite3WalRead(pPager->pWal, 1, &isInWal, N, pDest);
36452    if( rc!=SQLITE_OK || isInWal ){
36453      return rc;
36454    }
36455  }
36456#endif
36457
36458  if( isOpen(pPager->fd) ){
36459    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
36460    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
36461    if( rc==SQLITE_IOERR_SHORT_READ ){
36462      rc = SQLITE_OK;
36463    }
36464  }
36465  return rc;
36466}
36467
36468/*
36469** Return the total number of pages in the database file associated
36470** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
36471** However, if the file is between 1 and <page-size> bytes in size, then
36472** this is considered a 1 page file.
36473**
36474** If the pager is in error state when this function is called, then the
36475** error state error code is returned and *pnPage left unchanged. Or,
36476** if the file system has to be queried for the size of the file and
36477** the query attempt returns an IO error, the IO error code is returned
36478** and *pnPage is left unchanged.
36479**
36480** Otherwise, if everything is successful, then SQLITE_OK is returned
36481** and *pnPage is set to the number of pages in the database.
36482*/
36483SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
36484  Pgno nPage = 0;           /* Value to return via *pnPage */
36485
36486  /* Determine the number of pages in the file. Store this in nPage. */
36487  if( pPager->dbSizeValid ){
36488    nPage = pPager->dbSize;
36489  }else{
36490    int rc;                 /* Error returned by OsFileSize() */
36491    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
36492
36493    if( pagerUseWal(pPager) && pPager->state!=PAGER_UNLOCK ){
36494      sqlite3WalDbsize(pPager->pWal, &nPage);
36495    }
36496
36497    if( nPage==0 ){
36498      assert( isOpen(pPager->fd) || pPager->tempFile );
36499      if( isOpen(pPager->fd) ){
36500        if( SQLITE_OK!=(rc = sqlite3OsFileSize(pPager->fd, &n)) ){
36501          pager_error(pPager, rc);
36502          return rc;
36503        }
36504      }
36505      if( n>0 && n<pPager->pageSize ){
36506        nPage = 1;
36507      }else{
36508        nPage = (Pgno)(n / pPager->pageSize);
36509      }
36510    }
36511    if( pPager->state!=PAGER_UNLOCK ){
36512      pPager->dbSize = nPage;
36513      pPager->dbFileSize = nPage;
36514      pPager->dbSizeValid = 1;
36515    }
36516  }
36517
36518  /* If the current number of pages in the file is greater than the
36519  ** configured maximum pager number, increase the allowed limit so
36520  ** that the file can be read.
36521  */
36522  if( nPage>pPager->mxPgno ){
36523    pPager->mxPgno = (Pgno)nPage;
36524  }
36525
36526  /* Set the output variable and return SQLITE_OK */
36527  *pnPage = nPage;
36528  return SQLITE_OK;
36529}
36530
36531
36532/*
36533** Try to obtain a lock of type locktype on the database file. If
36534** a similar or greater lock is already held, this function is a no-op
36535** (returning SQLITE_OK immediately).
36536**
36537** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
36538** the busy callback if the lock is currently not available. Repeat
36539** until the busy callback returns false or until the attempt to
36540** obtain the lock succeeds.
36541**
36542** Return SQLITE_OK on success and an error code if we cannot obtain
36543** the lock. If the lock is obtained successfully, set the Pager.state
36544** variable to locktype before returning.
36545*/
36546static int pager_wait_on_lock(Pager *pPager, int locktype){
36547  int rc;                              /* Return code */
36548
36549  /* The OS lock values must be the same as the Pager lock values */
36550  assert( PAGER_SHARED==SHARED_LOCK );
36551  assert( PAGER_RESERVED==RESERVED_LOCK );
36552  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
36553
36554  /* If the file is currently unlocked then the size must be unknown. It
36555  ** must not have been modified at this point.
36556  */
36557  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
36558  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
36559
36560  /* Check that this is either a no-op (because the requested lock is
36561  ** already held, or one of the transistions that the busy-handler
36562  ** may be invoked during, according to the comment above
36563  ** sqlite3PagerSetBusyhandler().
36564  */
36565  assert( (pPager->state>=locktype)
36566       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
36567       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
36568  );
36569
36570  if( pPager->state>=locktype ){
36571    rc = SQLITE_OK;
36572  }else{
36573    do {
36574      rc = sqlite3OsLock(pPager->fd, locktype);
36575    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
36576    if( rc==SQLITE_OK ){
36577      pPager->state = (u8)locktype;
36578      IOTRACE(("LOCK %p %d\n", pPager, locktype))
36579    }
36580  }
36581  return rc;
36582}
36583
36584/*
36585** Function assertTruncateConstraint(pPager) checks that one of the
36586** following is true for all dirty pages currently in the page-cache:
36587**
36588**   a) The page number is less than or equal to the size of the
36589**      current database image, in pages, OR
36590**
36591**   b) if the page content were written at this time, it would not
36592**      be necessary to write the current content out to the sub-journal
36593**      (as determined by function subjRequiresPage()).
36594**
36595** If the condition asserted by this function were not true, and the
36596** dirty page were to be discarded from the cache via the pagerStress()
36597** routine, pagerStress() would not write the current page content to
36598** the database file. If a savepoint transaction were rolled back after
36599** this happened, the correct behaviour would be to restore the current
36600** content of the page. However, since this content is not present in either
36601** the database file or the portion of the rollback journal and
36602** sub-journal rolled back the content could not be restored and the
36603** database image would become corrupt. It is therefore fortunate that
36604** this circumstance cannot arise.
36605*/
36606#if defined(SQLITE_DEBUG)
36607static void assertTruncateConstraintCb(PgHdr *pPg){
36608  assert( pPg->flags&PGHDR_DIRTY );
36609  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
36610}
36611static void assertTruncateConstraint(Pager *pPager){
36612  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
36613}
36614#else
36615# define assertTruncateConstraint(pPager)
36616#endif
36617
36618/*
36619** Truncate the in-memory database file image to nPage pages. This
36620** function does not actually modify the database file on disk. It
36621** just sets the internal state of the pager object so that the
36622** truncation will be done when the current transaction is committed.
36623*/
36624SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
36625  assert( pPager->dbSizeValid );
36626  assert( pPager->dbSize>=nPage );
36627  assert( pPager->state>=PAGER_RESERVED );
36628  pPager->dbSize = nPage;
36629  assertTruncateConstraint(pPager);
36630}
36631
36632
36633/*
36634** This function is called before attempting a hot-journal rollback. It
36635** syncs the journal file to disk, then sets pPager->journalHdr to the
36636** size of the journal file so that the pager_playback() routine knows
36637** that the entire journal file has been synced.
36638**
36639** Syncing a hot-journal to disk before attempting to roll it back ensures
36640** that if a power-failure occurs during the rollback, the process that
36641** attempts rollback following system recovery sees the same journal
36642** content as this process.
36643**
36644** If everything goes as planned, SQLITE_OK is returned. Otherwise,
36645** an SQLite error code.
36646*/
36647static int pagerSyncHotJournal(Pager *pPager){
36648  int rc = SQLITE_OK;
36649  if( !pPager->noSync ){
36650    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
36651  }
36652  if( rc==SQLITE_OK ){
36653    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
36654  }
36655  return rc;
36656}
36657
36658/*
36659** Shutdown the page cache.  Free all memory and close all files.
36660**
36661** If a transaction was in progress when this routine is called, that
36662** transaction is rolled back.  All outstanding pages are invalidated
36663** and their memory is freed.  Any attempt to use a page associated
36664** with this page cache after this function returns will likely
36665** result in a coredump.
36666**
36667** This function always succeeds. If a transaction is active an attempt
36668** is made to roll it back. If an error occurs during the rollback
36669** a hot journal may be left in the filesystem but no error is returned
36670** to the caller.
36671*/
36672SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
36673  u8 *pTmp = (u8 *)pPager->pTmpSpace;
36674
36675  disable_simulated_io_errors();
36676  sqlite3BeginBenignMalloc();
36677  pPager->errCode = 0;
36678  pPager->exclusiveMode = 0;
36679#ifndef SQLITE_OMIT_WAL
36680  sqlite3WalClose(pPager->pWal,
36681    (pPager->noSync ? 0 : pPager->sync_flags),
36682    pPager->pageSize, pTmp
36683  );
36684  pPager->pWal = 0;
36685#endif
36686  pager_reset(pPager);
36687  if( MEMDB ){
36688    pager_unlock(pPager);
36689  }else{
36690    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
36691    ** call which may be made from within pagerUnlockAndRollback(). If it
36692    ** is not -1, then the unsynced portion of an open journal file may
36693    ** be played back into the database. If a power failure occurs while
36694    ** this is happening, the database may become corrupt.
36695    */
36696    if( isOpen(pPager->jfd) ){
36697      pPager->errCode = pagerSyncHotJournal(pPager);
36698    }
36699    pagerUnlockAndRollback(pPager);
36700  }
36701  sqlite3EndBenignMalloc();
36702  enable_simulated_io_errors();
36703  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
36704  IOTRACE(("CLOSE %p\n", pPager))
36705  sqlite3OsClose(pPager->jfd);
36706  sqlite3OsClose(pPager->fd);
36707  sqlite3PageFree(pTmp);
36708  sqlite3PcacheClose(pPager->pPCache);
36709
36710#ifdef SQLITE_HAS_CODEC
36711  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36712#endif
36713
36714  assert( !pPager->aSavepoint && !pPager->pInJournal );
36715  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
36716
36717  sqlite3_free(pPager);
36718  return SQLITE_OK;
36719}
36720
36721#if !defined(NDEBUG) || defined(SQLITE_TEST)
36722/*
36723** Return the page number for page pPg.
36724*/
36725SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
36726  return pPg->pgno;
36727}
36728#endif
36729
36730/*
36731** Increment the reference count for page pPg.
36732*/
36733SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
36734  sqlite3PcacheRef(pPg);
36735}
36736
36737/*
36738** Sync the journal. In other words, make sure all the pages that have
36739** been written to the journal have actually reached the surface of the
36740** disk and can be restored in the event of a hot-journal rollback.
36741**
36742** If the Pager.needSync flag is not set, then this function is a
36743** no-op. Otherwise, the actions required depend on the journal-mode
36744** and the device characteristics of the the file-system, as follows:
36745**
36746**   * If the journal file is an in-memory journal file, no action need
36747**     be taken.
36748**
36749**   * Otherwise, if the device does not support the SAFE_APPEND property,
36750**     then the nRec field of the most recently written journal header
36751**     is updated to contain the number of journal records that have
36752**     been written following it. If the pager is operating in full-sync
36753**     mode, then the journal file is synced before this field is updated.
36754**
36755**   * If the device does not support the SEQUENTIAL property, then
36756**     journal file is synced.
36757**
36758** Or, in pseudo-code:
36759**
36760**   if( NOT <in-memory journal> ){
36761**     if( NOT SAFE_APPEND ){
36762**       if( <full-sync mode> ) xSync(<journal file>);
36763**       <update nRec field>
36764**     }
36765**     if( NOT SEQUENTIAL ) xSync(<journal file>);
36766**   }
36767**
36768** The Pager.needSync flag is never be set for temporary files, or any
36769** file operating in no-sync mode (Pager.noSync set to non-zero).
36770**
36771** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
36772** page currently held in memory before returning SQLITE_OK. If an IO
36773** error is encountered, then the IO error code is returned to the caller.
36774*/
36775static int syncJournal(Pager *pPager){
36776  if( pPager->needSync ){
36777    assert( !pPager->tempFile );
36778    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
36779      int rc;                              /* Return code */
36780      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
36781      assert( isOpen(pPager->jfd) );
36782
36783      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
36784        /* This block deals with an obscure problem. If the last connection
36785        ** that wrote to this database was operating in persistent-journal
36786        ** mode, then the journal file may at this point actually be larger
36787        ** than Pager.journalOff bytes. If the next thing in the journal
36788        ** file happens to be a journal-header (written as part of the
36789        ** previous connection's transaction), and a crash or power-failure
36790        ** occurs after nRec is updated but before this connection writes
36791        ** anything else to the journal file (or commits/rolls back its
36792        ** transaction), then SQLite may become confused when doing the
36793        ** hot-journal rollback following recovery. It may roll back all
36794        ** of this connections data, then proceed to rolling back the old,
36795        ** out-of-date data that follows it. Database corruption.
36796        **
36797        ** To work around this, if the journal file does appear to contain
36798        ** a valid header following Pager.journalOff, then write a 0x00
36799        ** byte to the start of it to prevent it from being recognized.
36800        **
36801        ** Variable iNextHdrOffset is set to the offset at which this
36802        ** problematic header will occur, if it exists. aMagic is used
36803        ** as a temporary buffer to inspect the first couple of bytes of
36804        ** the potential journal header.
36805        */
36806        i64 iNextHdrOffset;
36807        u8 aMagic[8];
36808        u8 zHeader[sizeof(aJournalMagic)+4];
36809
36810        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
36811        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
36812
36813        iNextHdrOffset = journalHdrOffset(pPager);
36814        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
36815        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
36816          static const u8 zerobyte = 0;
36817          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
36818        }
36819        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
36820          return rc;
36821        }
36822
36823        /* Write the nRec value into the journal file header. If in
36824        ** full-synchronous mode, sync the journal first. This ensures that
36825        ** all data has really hit the disk before nRec is updated to mark
36826        ** it as a candidate for rollback.
36827        **
36828        ** This is not required if the persistent media supports the
36829        ** SAFE_APPEND property. Because in this case it is not possible
36830        ** for garbage data to be appended to the file, the nRec field
36831        ** is populated with 0xFFFFFFFF when the journal header is written
36832        ** and never needs to be updated.
36833        */
36834        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
36835          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
36836          IOTRACE(("JSYNC %p\n", pPager))
36837          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
36838          if( rc!=SQLITE_OK ) return rc;
36839        }
36840        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
36841        rc = sqlite3OsWrite(
36842            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
36843        );
36844        if( rc!=SQLITE_OK ) return rc;
36845      }
36846      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
36847        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
36848        IOTRACE(("JSYNC %p\n", pPager))
36849        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
36850          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
36851        );
36852        if( rc!=SQLITE_OK ) return rc;
36853      }
36854    }
36855
36856    /* The journal file was just successfully synced. Set Pager.needSync
36857    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
36858    */
36859    pPager->needSync = 0;
36860    pPager->journalStarted = 1;
36861    pPager->journalHdr = pPager->journalOff;
36862    sqlite3PcacheClearSyncFlags(pPager->pPCache);
36863  }
36864
36865  return SQLITE_OK;
36866}
36867
36868/*
36869** The argument is the first in a linked list of dirty pages connected
36870** by the PgHdr.pDirty pointer. This function writes each one of the
36871** in-memory pages in the list to the database file. The argument may
36872** be NULL, representing an empty list. In this case this function is
36873** a no-op.
36874**
36875** The pager must hold at least a RESERVED lock when this function
36876** is called. Before writing anything to the database file, this lock
36877** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
36878** SQLITE_BUSY is returned and no data is written to the database file.
36879**
36880** If the pager is a temp-file pager and the actual file-system file
36881** is not yet open, it is created and opened before any data is
36882** written out.
36883**
36884** Once the lock has been upgraded and, if necessary, the file opened,
36885** the pages are written out to the database file in list order. Writing
36886** a page is skipped if it meets either of the following criteria:
36887**
36888**   * The page number is greater than Pager.dbSize, or
36889**   * The PGHDR_DONT_WRITE flag is set on the page.
36890**
36891** If writing out a page causes the database file to grow, Pager.dbFileSize
36892** is updated accordingly. If page 1 is written out, then the value cached
36893** in Pager.dbFileVers[] is updated to match the new value stored in
36894** the database file.
36895**
36896** If everything is successful, SQLITE_OK is returned. If an IO error
36897** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
36898** be obtained, SQLITE_BUSY is returned.
36899*/
36900static int pager_write_pagelist(PgHdr *pList){
36901  Pager *pPager;                       /* Pager object */
36902  int rc;                              /* Return code */
36903
36904  if( NEVER(pList==0) ) return SQLITE_OK;
36905  pPager = pList->pPager;
36906
36907  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
36908  ** database file. If there is already an EXCLUSIVE lock, the following
36909  ** call is a no-op.
36910  **
36911  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
36912  ** through an intermediate state PENDING.   A PENDING lock prevents new
36913  ** readers from attaching to the database but is unsufficient for us to
36914  ** write.  The idea of a PENDING lock is to prevent new readers from
36915  ** coming in while we wait for existing readers to clear.
36916  **
36917  ** While the pager is in the RESERVED state, the original database file
36918  ** is unchanged and we can rollback without having to playback the
36919  ** journal into the original database file.  Once we transition to
36920  ** EXCLUSIVE, it means the database file has been changed and any rollback
36921  ** will require a journal playback.
36922  */
36923  assert( !pagerUseWal(pList->pPager) );
36924  assert( pPager->state>=PAGER_RESERVED );
36925  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
36926
36927  /* If the file is a temp-file has not yet been opened, open it now. It
36928  ** is not possible for rc to be other than SQLITE_OK if this branch
36929  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
36930  */
36931  if( !isOpen(pPager->fd) ){
36932    assert( pPager->tempFile && rc==SQLITE_OK );
36933    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
36934  }
36935
36936  /* Before the first write, give the VFS a hint of what the final
36937  ** file size will be.
36938  */
36939  if( pPager->dbSize > (pPager->dbOrigSize+1) && isOpen(pPager->fd) ){
36940    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
36941    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
36942  }
36943
36944  while( rc==SQLITE_OK && pList ){
36945    Pgno pgno = pList->pgno;
36946
36947    /* If there are dirty pages in the page cache with page numbers greater
36948    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
36949    ** make the file smaller (presumably by auto-vacuum code). Do not write
36950    ** any such pages to the file.
36951    **
36952    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
36953    ** set (set by sqlite3PagerDontWrite()).
36954    */
36955    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
36956      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
36957      char *pData;                                   /* Data to write */
36958
36959      /* Encode the database */
36960      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
36961
36962      /* Write out the page data. */
36963      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
36964
36965      /* If page 1 was just written, update Pager.dbFileVers to match
36966      ** the value now stored in the database file. If writing this
36967      ** page caused the database file to grow, update dbFileSize.
36968      */
36969      if( pgno==1 ){
36970        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
36971      }
36972      if( pgno>pPager->dbFileSize ){
36973        pPager->dbFileSize = pgno;
36974      }
36975
36976      /* Update any backup objects copying the contents of this pager. */
36977      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
36978
36979      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
36980                   PAGERID(pPager), pgno, pager_pagehash(pList)));
36981      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
36982      PAGER_INCR(sqlite3_pager_writedb_count);
36983      PAGER_INCR(pPager->nWrite);
36984    }else{
36985      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
36986    }
36987#ifdef SQLITE_CHECK_PAGES
36988    pList->pageHash = pager_pagehash(pList);
36989#endif
36990    pList = pList->pDirty;
36991  }
36992
36993  return rc;
36994}
36995
36996/*
36997** Ensure that the sub-journal file is open. If it is already open, this
36998** function is a no-op.
36999**
37000** SQLITE_OK is returned if everything goes according to plan. An
37001** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
37002** fails.
37003*/
37004static int openSubJournal(Pager *pPager){
37005  int rc = SQLITE_OK;
37006  if( !isOpen(pPager->sjfd) ){
37007    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
37008      sqlite3MemJournalOpen(pPager->sjfd);
37009    }else{
37010      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
37011    }
37012  }
37013  return rc;
37014}
37015
37016/*
37017** Append a record of the current state of page pPg to the sub-journal.
37018** It is the callers responsibility to use subjRequiresPage() to check
37019** that it is really required before calling this function.
37020**
37021** If successful, set the bit corresponding to pPg->pgno in the bitvecs
37022** for all open savepoints before returning.
37023**
37024** This function returns SQLITE_OK if everything is successful, an IO
37025** error code if the attempt to write to the sub-journal fails, or
37026** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
37027** bitvec.
37028*/
37029static int subjournalPage(PgHdr *pPg){
37030  int rc = SQLITE_OK;
37031  Pager *pPager = pPg->pPager;
37032  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
37033
37034    /* Open the sub-journal, if it has not already been opened */
37035    assert( pPager->useJournal );
37036    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
37037    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
37038    assert( pagerUseWal(pPager)
37039         || pageInJournal(pPg)
37040         || pPg->pgno>pPager->dbOrigSize
37041    );
37042    rc = openSubJournal(pPager);
37043
37044    /* If the sub-journal was opened successfully (or was already open),
37045    ** write the journal record into the file.  */
37046    if( rc==SQLITE_OK ){
37047      void *pData = pPg->pData;
37048      i64 offset = pPager->nSubRec*(4+pPager->pageSize);
37049      char *pData2;
37050
37051      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
37052      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
37053      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
37054      if( rc==SQLITE_OK ){
37055        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
37056      }
37057    }
37058  }
37059  if( rc==SQLITE_OK ){
37060    pPager->nSubRec++;
37061    assert( pPager->nSavepoint>0 );
37062    rc = addToSavepointBitvecs(pPager, pPg->pgno);
37063  }
37064  return rc;
37065}
37066
37067/*
37068** This function is called by the pcache layer when it has reached some
37069** soft memory limit. The first argument is a pointer to a Pager object
37070** (cast as a void*). The pager is always 'purgeable' (not an in-memory
37071** database). The second argument is a reference to a page that is
37072** currently dirty but has no outstanding references. The page
37073** is always associated with the Pager object passed as the first
37074** argument.
37075**
37076** The job of this function is to make pPg clean by writing its contents
37077** out to the database file, if possible. This may involve syncing the
37078** journal file.
37079**
37080** If successful, sqlite3PcacheMakeClean() is called on the page and
37081** SQLITE_OK returned. If an IO error occurs while trying to make the
37082** page clean, the IO error code is returned. If the page cannot be
37083** made clean for some other reason, but no error occurs, then SQLITE_OK
37084** is returned by sqlite3PcacheMakeClean() is not called.
37085*/
37086static int pagerStress(void *p, PgHdr *pPg){
37087  Pager *pPager = (Pager *)p;
37088  int rc = SQLITE_OK;
37089
37090  assert( pPg->pPager==pPager );
37091  assert( pPg->flags&PGHDR_DIRTY );
37092
37093  /* The doNotSyncSpill flag is set during times when doing a sync of
37094  ** journal (and adding a new header) is not allowed.  This occurs
37095  ** during calls to sqlite3PagerWrite() while trying to journal multiple
37096  ** pages belonging to the same sector.
37097  **
37098  ** The doNotSpill flag inhibits all cache spilling regardless of whether
37099  ** or not a sync is required.  This is set during a rollback.
37100  **
37101  ** Spilling is also inhibited when in an error state.
37102  */
37103  if( pPager->errCode ) return SQLITE_OK;
37104  if( pPager->doNotSpill ) return SQLITE_OK;
37105  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
37106    return SQLITE_OK;
37107  }
37108
37109  pPg->pDirty = 0;
37110  if( pagerUseWal(pPager) ){
37111    /* Write a single frame for this page to the log. */
37112    if( subjRequiresPage(pPg) ){
37113      rc = subjournalPage(pPg);
37114    }
37115    if( rc==SQLITE_OK ){
37116      rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
37117    }
37118  }else{
37119
37120    /* Sync the journal file if required. */
37121    if( pPg->flags&PGHDR_NEED_SYNC ){
37122      assert( !pPager->noSync );
37123      rc = syncJournal(pPager);
37124      if( rc==SQLITE_OK &&
37125        !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
37126        !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37127      ){
37128        pPager->nRec = 0;
37129        rc = writeJournalHdr(pPager);
37130      }
37131    }
37132
37133    /* If the page number of this page is larger than the current size of
37134    ** the database image, it may need to be written to the sub-journal.
37135    ** This is because the call to pager_write_pagelist() below will not
37136    ** actually write data to the file in this case.
37137    **
37138    ** Consider the following sequence of events:
37139    **
37140    **   BEGIN;
37141    **     <journal page X>
37142    **     <modify page X>
37143    **     SAVEPOINT sp;
37144    **       <shrink database file to Y pages>
37145    **       pagerStress(page X)
37146    **     ROLLBACK TO sp;
37147    **
37148    ** If (X>Y), then when pagerStress is called page X will not be written
37149    ** out to the database file, but will be dropped from the cache. Then,
37150    ** following the "ROLLBACK TO sp" statement, reading page X will read
37151    ** data from the database file. This will be the copy of page X as it
37152    ** was when the transaction started, not as it was when "SAVEPOINT sp"
37153    ** was executed.
37154    **
37155    ** The solution is to write the current data for page X into the
37156    ** sub-journal file now (if it is not already there), so that it will
37157    ** be restored to its current value when the "ROLLBACK TO sp" is
37158    ** executed.
37159    */
37160    if( NEVER(
37161        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
37162    ) ){
37163      rc = subjournalPage(pPg);
37164    }
37165
37166    /* Write the contents of the page out to the database file. */
37167    if( rc==SQLITE_OK ){
37168      rc = pager_write_pagelist(pPg);
37169    }
37170  }
37171
37172  /* Mark the page as clean. */
37173  if( rc==SQLITE_OK ){
37174    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
37175    sqlite3PcacheMakeClean(pPg);
37176  }
37177
37178  return pager_error(pPager, rc);
37179}
37180
37181
37182/*
37183** Allocate and initialize a new Pager object and put a pointer to it
37184** in *ppPager. The pager should eventually be freed by passing it
37185** to sqlite3PagerClose().
37186**
37187** The zFilename argument is the path to the database file to open.
37188** If zFilename is NULL then a randomly-named temporary file is created
37189** and used as the file to be cached. Temporary files are be deleted
37190** automatically when they are closed. If zFilename is ":memory:" then
37191** all information is held in cache. It is never written to disk.
37192** This can be used to implement an in-memory database.
37193**
37194** The nExtra parameter specifies the number of bytes of space allocated
37195** along with each page reference. This space is available to the user
37196** via the sqlite3PagerGetExtra() API.
37197**
37198** The flags argument is used to specify properties that affect the
37199** operation of the pager. It should be passed some bitwise combination
37200** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
37201**
37202** The vfsFlags parameter is a bitmask to pass to the flags parameter
37203** of the xOpen() method of the supplied VFS when opening files.
37204**
37205** If the pager object is allocated and the specified file opened
37206** successfully, SQLITE_OK is returned and *ppPager set to point to
37207** the new pager object. If an error occurs, *ppPager is set to NULL
37208** and error code returned. This function may return SQLITE_NOMEM
37209** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
37210** various SQLITE_IO_XXX errors.
37211*/
37212SQLITE_PRIVATE int sqlite3PagerOpen(
37213  sqlite3_vfs *pVfs,       /* The virtual file system to use */
37214  Pager **ppPager,         /* OUT: Return the Pager structure here */
37215  const char *zFilename,   /* Name of the database file to open */
37216  int nExtra,              /* Extra bytes append to each in-memory page */
37217  int flags,               /* flags controlling this file */
37218  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
37219  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
37220){
37221  u8 *pPtr;
37222  Pager *pPager = 0;       /* Pager object to allocate and return */
37223  int rc = SQLITE_OK;      /* Return code */
37224  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
37225  int memDb = 0;           /* True if this is an in-memory file */
37226  int readOnly = 0;        /* True if this is a read-only file */
37227  int journalFileSize;     /* Bytes to allocate for each journal fd */
37228  char *zPathname = 0;     /* Full path to database file */
37229  int nPathname = 0;       /* Number of bytes in zPathname */
37230  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
37231  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
37232  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
37233  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
37234
37235  /* Figure out how much space is required for each journal file-handle
37236  ** (there are two of them, the main journal and the sub-journal). This
37237  ** is the maximum space required for an in-memory journal file handle
37238  ** and a regular journal file-handle. Note that a "regular journal-handle"
37239  ** may be a wrapper capable of caching the first portion of the journal
37240  ** file in memory to implement the atomic-write optimization (see
37241  ** source file journal.c).
37242  */
37243  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
37244    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
37245  }else{
37246    journalFileSize = ROUND8(sqlite3MemJournalSize());
37247  }
37248
37249  /* Set the output variable to NULL in case an error occurs. */
37250  *ppPager = 0;
37251
37252  /* Compute and store the full pathname in an allocated buffer pointed
37253  ** to by zPathname, length nPathname. Or, if this is a temporary file,
37254  ** leave both nPathname and zPathname set to 0.
37255  */
37256  if( zFilename && zFilename[0] ){
37257    nPathname = pVfs->mxPathname+1;
37258    zPathname = sqlite3Malloc(nPathname*2);
37259    if( zPathname==0 ){
37260      return SQLITE_NOMEM;
37261    }
37262#ifndef SQLITE_OMIT_MEMORYDB
37263    if( strcmp(zFilename,":memory:")==0 ){
37264      memDb = 1;
37265      zPathname[0] = 0;
37266    }else
37267#endif
37268    {
37269      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
37270      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
37271    }
37272
37273    nPathname = sqlite3Strlen30(zPathname);
37274    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
37275      /* This branch is taken when the journal path required by
37276      ** the database being opened will be more than pVfs->mxPathname
37277      ** bytes in length. This means the database cannot be opened,
37278      ** as it will not be possible to open the journal file or even
37279      ** check for a hot-journal before reading.
37280      */
37281      rc = SQLITE_CANTOPEN_BKPT;
37282    }
37283    if( rc!=SQLITE_OK ){
37284      sqlite3_free(zPathname);
37285      return rc;
37286    }
37287  }
37288
37289  /* Allocate memory for the Pager structure, PCache object, the
37290  ** three file descriptors, the database file name and the journal
37291  ** file name. The layout in memory is as follows:
37292  **
37293  **     Pager object                    (sizeof(Pager) bytes)
37294  **     PCache object                   (sqlite3PcacheSize() bytes)
37295  **     Database file handle            (pVfs->szOsFile bytes)
37296  **     Sub-journal file handle         (journalFileSize bytes)
37297  **     Main journal file handle        (journalFileSize bytes)
37298  **     Database file name              (nPathname+1 bytes)
37299  **     Journal file name               (nPathname+8+1 bytes)
37300  */
37301  pPtr = (u8 *)sqlite3MallocZero(
37302    ROUND8(sizeof(*pPager)) +      /* Pager structure */
37303    ROUND8(pcacheSize) +           /* PCache object */
37304    ROUND8(pVfs->szOsFile) +       /* The main db file */
37305    journalFileSize * 2 +          /* The two journal files */
37306    nPathname + 1 +                /* zFilename */
37307    nPathname + 8 + 1              /* zJournal */
37308  );
37309  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
37310  if( !pPtr ){
37311    sqlite3_free(zPathname);
37312    return SQLITE_NOMEM;
37313  }
37314  pPager =              (Pager*)(pPtr);
37315  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
37316  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
37317  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
37318  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
37319  pPager->zFilename =    (char*)(pPtr += journalFileSize);
37320  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
37321
37322  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
37323  if( zPathname ){
37324    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
37325    memcpy(pPager->zFilename, zPathname, nPathname);
37326    memcpy(pPager->zJournal, zPathname, nPathname);
37327    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
37328    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
37329    sqlite3_free(zPathname);
37330  }
37331  pPager->pVfs = pVfs;
37332  pPager->vfsFlags = vfsFlags;
37333
37334  /* Open the pager file.
37335  */
37336  if( zFilename && zFilename[0] && !memDb ){
37337    int fout = 0;                    /* VFS flags returned by xOpen() */
37338    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
37339    readOnly = (fout&SQLITE_OPEN_READONLY);
37340
37341    /* If the file was successfully opened for read/write access,
37342    ** choose a default page size in case we have to create the
37343    ** database file. The default page size is the maximum of:
37344    **
37345    **    + SQLITE_DEFAULT_PAGE_SIZE,
37346    **    + The value returned by sqlite3OsSectorSize()
37347    **    + The largest page size that can be written atomically.
37348    */
37349    if( rc==SQLITE_OK && !readOnly ){
37350      setSectorSize(pPager);
37351      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
37352      if( szPageDflt<pPager->sectorSize ){
37353        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
37354          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
37355        }else{
37356          szPageDflt = (u16)pPager->sectorSize;
37357        }
37358      }
37359#ifdef SQLITE_ENABLE_ATOMIC_WRITE
37360      {
37361        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37362        int ii;
37363        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37364        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37365        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
37366        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
37367          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
37368            szPageDflt = ii;
37369          }
37370        }
37371      }
37372#endif
37373    }
37374  }else{
37375    /* If a temporary file is requested, it is not opened immediately.
37376    ** In this case we accept the default page size and delay actually
37377    ** opening the file until the first call to OsWrite().
37378    **
37379    ** This branch is also run for an in-memory database. An in-memory
37380    ** database is the same as a temp-file that is never written out to
37381    ** disk and uses an in-memory rollback journal.
37382    */
37383    tempFile = 1;
37384    pPager->state = PAGER_EXCLUSIVE;
37385    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
37386  }
37387
37388  /* The following call to PagerSetPagesize() serves to set the value of
37389  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
37390  */
37391  if( rc==SQLITE_OK ){
37392    assert( pPager->memDb==0 );
37393    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
37394    testcase( rc!=SQLITE_OK );
37395  }
37396
37397  /* If an error occurred in either of the blocks above, free the
37398  ** Pager structure and close the file.
37399  */
37400  if( rc!=SQLITE_OK ){
37401    assert( !pPager->pTmpSpace );
37402    sqlite3OsClose(pPager->fd);
37403    sqlite3_free(pPager);
37404    return rc;
37405  }
37406
37407  /* Initialize the PCache object. */
37408  assert( nExtra<1000 );
37409  nExtra = ROUND8(nExtra);
37410  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
37411                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
37412
37413  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
37414  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
37415
37416  pPager->useJournal = (u8)useJournal;
37417  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
37418  /* pPager->stmtOpen = 0; */
37419  /* pPager->stmtInUse = 0; */
37420  /* pPager->nRef = 0; */
37421  pPager->dbSizeValid = (u8)memDb;
37422  /* pPager->stmtSize = 0; */
37423  /* pPager->stmtJSize = 0; */
37424  /* pPager->nPage = 0; */
37425  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
37426  /* pPager->state = PAGER_UNLOCK; */
37427  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
37428  /* pPager->errMask = 0; */
37429  pPager->tempFile = (u8)tempFile;
37430  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
37431          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
37432  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
37433  pPager->exclusiveMode = (u8)tempFile;
37434  pPager->changeCountDone = pPager->tempFile;
37435  pPager->memDb = (u8)memDb;
37436  pPager->readOnly = (u8)readOnly;
37437  /* pPager->needSync = 0; */
37438  assert( useJournal || pPager->tempFile );
37439  pPager->noSync = pPager->tempFile;
37440  pPager->fullSync = pPager->noSync ?0:1;
37441  pPager->sync_flags = SQLITE_SYNC_NORMAL;
37442  /* pPager->pFirst = 0; */
37443  /* pPager->pFirstSynced = 0; */
37444  /* pPager->pLast = 0; */
37445  pPager->nExtra = (u16)nExtra;
37446  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
37447  assert( isOpen(pPager->fd) || tempFile );
37448  setSectorSize(pPager);
37449  if( !useJournal ){
37450    pPager->journalMode = PAGER_JOURNALMODE_OFF;
37451  }else if( memDb ){
37452    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
37453  }
37454  /* pPager->xBusyHandler = 0; */
37455  /* pPager->pBusyHandlerArg = 0; */
37456  pPager->xReiniter = xReinit;
37457  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
37458
37459  *ppPager = pPager;
37460  return SQLITE_OK;
37461}
37462
37463
37464
37465/*
37466** This function is called after transitioning from PAGER_UNLOCK to
37467** PAGER_SHARED state. It tests if there is a hot journal present in
37468** the file-system for the given pager. A hot journal is one that
37469** needs to be played back. According to this function, a hot-journal
37470** file exists if the following criteria are met:
37471**
37472**   * The journal file exists in the file system, and
37473**   * No process holds a RESERVED or greater lock on the database file, and
37474**   * The database file itself is greater than 0 bytes in size, and
37475**   * The first byte of the journal file exists and is not 0x00.
37476**
37477** If the current size of the database file is 0 but a journal file
37478** exists, that is probably an old journal left over from a prior
37479** database with the same name. In this case the journal file is
37480** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
37481** is returned.
37482**
37483** This routine does not check if there is a master journal filename
37484** at the end of the file. If there is, and that master journal file
37485** does not exist, then the journal file is not really hot. In this
37486** case this routine will return a false-positive. The pager_playback()
37487** routine will discover that the journal file is not really hot and
37488** will not roll it back.
37489**
37490** If a hot-journal file is found to exist, *pExists is set to 1 and
37491** SQLITE_OK returned. If no hot-journal file is present, *pExists is
37492** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
37493** to determine whether or not a hot-journal file exists, the IO error
37494** code is returned and the value of *pExists is undefined.
37495*/
37496static int hasHotJournal(Pager *pPager, int *pExists){
37497  sqlite3_vfs * const pVfs = pPager->pVfs;
37498  int rc = SQLITE_OK;           /* Return code */
37499  int exists = 1;               /* True if a journal file is present */
37500  int jrnlOpen = !!isOpen(pPager->jfd);
37501
37502  assert( pPager!=0 );
37503  assert( pPager->useJournal );
37504  assert( isOpen(pPager->fd) );
37505  assert( pPager->state <= PAGER_SHARED );
37506  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
37507    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
37508  ));
37509
37510  *pExists = 0;
37511  if( !jrnlOpen ){
37512    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
37513  }
37514  if( rc==SQLITE_OK && exists ){
37515    int locked;                 /* True if some process holds a RESERVED lock */
37516
37517    /* Race condition here:  Another process might have been holding the
37518    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
37519    ** call above, but then delete the journal and drop the lock before
37520    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
37521    ** is the case, this routine might think there is a hot journal when
37522    ** in fact there is none.  This results in a false-positive which will
37523    ** be dealt with by the playback routine.  Ticket #3883.
37524    */
37525    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
37526    if( rc==SQLITE_OK && !locked ){
37527      int nPage;
37528
37529      /* Check the size of the database file. If it consists of 0 pages,
37530      ** then delete the journal file. See the header comment above for
37531      ** the reasoning here.  Delete the obsolete journal file under
37532      ** a RESERVED lock to avoid race conditions and to avoid violating
37533      ** [H33020].
37534      */
37535      rc = sqlite3PagerPagecount(pPager, &nPage);
37536      if( rc==SQLITE_OK ){
37537        if( nPage==0 ){
37538          sqlite3BeginBenignMalloc();
37539          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
37540            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
37541            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
37542          }
37543          sqlite3EndBenignMalloc();
37544        }else{
37545          /* The journal file exists and no other connection has a reserved
37546          ** or greater lock on the database file. Now check that there is
37547          ** at least one non-zero bytes at the start of the journal file.
37548          ** If there is, then we consider this journal to be hot. If not,
37549          ** it can be ignored.
37550          */
37551          if( !jrnlOpen ){
37552            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
37553            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
37554          }
37555          if( rc==SQLITE_OK ){
37556            u8 first = 0;
37557            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
37558            if( rc==SQLITE_IOERR_SHORT_READ ){
37559              rc = SQLITE_OK;
37560            }
37561            if( !jrnlOpen ){
37562              sqlite3OsClose(pPager->jfd);
37563            }
37564            *pExists = (first!=0);
37565          }else if( rc==SQLITE_CANTOPEN ){
37566            /* If we cannot open the rollback journal file in order to see if
37567            ** its has a zero header, that might be due to an I/O error, or
37568            ** it might be due to the race condition described above and in
37569            ** ticket #3883.  Either way, assume that the journal is hot.
37570            ** This might be a false positive.  But if it is, then the
37571            ** automatic journal playback and recovery mechanism will deal
37572            ** with it under an EXCLUSIVE lock where we do not need to
37573            ** worry so much with race conditions.
37574            */
37575            *pExists = 1;
37576            rc = SQLITE_OK;
37577          }
37578        }
37579      }
37580    }
37581  }
37582
37583  return rc;
37584}
37585
37586/*
37587** This function is called to obtain a shared lock on the database file.
37588** It is illegal to call sqlite3PagerAcquire() until after this function
37589** has been successfully called. If a shared-lock is already held when
37590** this function is called, it is a no-op.
37591**
37592** The following operations are also performed by this function.
37593**
37594**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
37595**      on the database file), then an attempt is made to obtain a
37596**      SHARED lock on the database file. Immediately after obtaining
37597**      the SHARED lock, the file-system is checked for a hot-journal,
37598**      which is played back if present. Following any hot-journal
37599**      rollback, the contents of the cache are validated by checking
37600**      the 'change-counter' field of the database file header and
37601**      discarded if they are found to be invalid.
37602**
37603**   2) If the pager is running in exclusive-mode, and there are currently
37604**      no outstanding references to any pages, and is in the error state,
37605**      then an attempt is made to clear the error state by discarding
37606**      the contents of the page cache and rolling back any open journal
37607**      file.
37608**
37609** If the operation described by (2) above is not attempted, and if the
37610** pager is in an error state other than SQLITE_FULL when this is called,
37611** the error state error code is returned. It is permitted to read the
37612** database when in SQLITE_FULL error state.
37613**
37614** Otherwise, if everything is successful, SQLITE_OK is returned. If an
37615** IO error occurs while locking the database, checking for a hot-journal
37616** file or rolling back a journal file, the IO error code is returned.
37617*/
37618SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
37619  int rc = SQLITE_OK;                /* Return code */
37620  int isErrorReset = 0;              /* True if recovering from error state */
37621
37622  /* This routine is only called from b-tree and only when there are no
37623  ** outstanding pages */
37624  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37625  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
37626
37627  /* If this database is in an error-state, now is a chance to clear
37628  ** the error. Discard the contents of the pager-cache and rollback
37629  ** any hot journal in the file-system.
37630  */
37631  if( pPager->errCode ){
37632    if( isOpen(pPager->jfd) || pPager->zJournal ){
37633      isErrorReset = 1;
37634    }
37635    pPager->errCode = SQLITE_OK;
37636    pager_reset(pPager);
37637  }
37638
37639  if( pagerUseWal(pPager) ){
37640    rc = pagerBeginReadTransaction(pPager);
37641  }else if( pPager->state==PAGER_UNLOCK || isErrorReset ){
37642    sqlite3_vfs * const pVfs = pPager->pVfs;
37643    int isHotJournal = 0;
37644    assert( !MEMDB );
37645    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37646    if( pPager->noReadlock ){
37647      assert( pPager->readOnly );
37648      pPager->state = PAGER_SHARED;
37649    }else{
37650      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
37651      if( rc!=SQLITE_OK ){
37652        assert( pPager->state==PAGER_UNLOCK );
37653        return pager_error(pPager, rc);
37654      }
37655    }
37656    assert( pPager->state>=SHARED_LOCK );
37657
37658    /* If a journal file exists, and there is no RESERVED lock on the
37659    ** database file, then it either needs to be played back or deleted.
37660    */
37661    if( !isErrorReset ){
37662      assert( pPager->state <= PAGER_SHARED );
37663      rc = hasHotJournal(pPager, &isHotJournal);
37664      if( rc!=SQLITE_OK ){
37665        goto failed;
37666      }
37667    }
37668    if( isErrorReset || isHotJournal ){
37669      /* Get an EXCLUSIVE lock on the database file. At this point it is
37670      ** important that a RESERVED lock is not obtained on the way to the
37671      ** EXCLUSIVE lock. If it were, another process might open the
37672      ** database file, detect the RESERVED lock, and conclude that the
37673      ** database is safe to read while this process is still rolling the
37674      ** hot-journal back.
37675      **
37676      ** Because the intermediate RESERVED lock is not requested, any
37677      ** other process attempting to access the database file will get to
37678      ** this point in the code and fail to obtain its own EXCLUSIVE lock
37679      ** on the database file.
37680      */
37681      if( pPager->state<EXCLUSIVE_LOCK ){
37682        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
37683        if( rc!=SQLITE_OK ){
37684          rc = pager_error(pPager, rc);
37685          goto failed;
37686        }
37687        pPager->state = PAGER_EXCLUSIVE;
37688      }
37689
37690      /* Open the journal for read/write access. This is because in
37691      ** exclusive-access mode the file descriptor will be kept open and
37692      ** possibly used for a transaction later on. On some systems, the
37693      ** OsTruncate() call used in exclusive-access mode also requires
37694      ** a read/write file handle.
37695      */
37696      if( !isOpen(pPager->jfd) ){
37697        int res;
37698        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
37699        if( rc==SQLITE_OK ){
37700          if( res ){
37701            int fout = 0;
37702            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
37703            assert( !pPager->tempFile );
37704            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
37705            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
37706            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
37707              rc = SQLITE_CANTOPEN_BKPT;
37708              sqlite3OsClose(pPager->jfd);
37709            }
37710          }else{
37711            /* If the journal does not exist, it usually means that some
37712            ** other connection managed to get in and roll it back before
37713            ** this connection obtained the exclusive lock above. Or, it
37714            ** may mean that the pager was in the error-state when this
37715            ** function was called and the journal file does not exist.  */
37716            rc = pager_end_transaction(pPager, 0);
37717          }
37718        }
37719      }
37720      if( rc!=SQLITE_OK ){
37721        goto failed;
37722      }
37723
37724      /* Reset the journal status fields to indicates that we have no
37725      ** rollback journal at this time. */
37726      pPager->journalStarted = 0;
37727      pPager->journalOff = 0;
37728      pPager->setMaster = 0;
37729      pPager->journalHdr = 0;
37730
37731      /* Make sure the journal file has been synced to disk. */
37732
37733      /* Playback and delete the journal.  Drop the database write
37734      ** lock and reacquire the read lock. Purge the cache before
37735      ** playing back the hot-journal so that we don't end up with
37736      ** an inconsistent cache.  Sync the hot journal before playing
37737      ** it back since the process that crashed and left the hot journal
37738      ** probably did not sync it and we are required to always sync
37739      ** the journal before playing it back.
37740      */
37741      if( isOpen(pPager->jfd) ){
37742        rc = pagerSyncHotJournal(pPager);
37743        if( rc==SQLITE_OK ){
37744          rc = pager_playback(pPager, 1);
37745        }
37746        if( rc!=SQLITE_OK ){
37747          rc = pager_error(pPager, rc);
37748          goto failed;
37749        }
37750      }
37751      assert( (pPager->state==PAGER_SHARED)
37752           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
37753      );
37754    }
37755
37756    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
37757      /* The shared-lock has just been acquired on the database file
37758      ** and there are already pages in the cache (from a previous
37759      ** read or write transaction).  Check to see if the database
37760      ** has been modified.  If the database has changed, flush the
37761      ** cache.
37762      **
37763      ** Database changes is detected by looking at 15 bytes beginning
37764      ** at offset 24 into the file.  The first 4 of these 16 bytes are
37765      ** a 32-bit counter that is incremented with each change.  The
37766      ** other bytes change randomly with each file change when
37767      ** a codec is in use.
37768      **
37769      ** There is a vanishingly small chance that a change will not be
37770      ** detected.  The chance of an undetected change is so small that
37771      ** it can be neglected.
37772      */
37773      int nPage = 0;
37774      char dbFileVers[sizeof(pPager->dbFileVers)];
37775      sqlite3PagerPagecount(pPager, &nPage);
37776
37777      if( pPager->errCode ){
37778        rc = pPager->errCode;
37779        goto failed;
37780      }
37781
37782      if( nPage>0 ){
37783        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
37784        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
37785        if( rc!=SQLITE_OK ){
37786          goto failed;
37787        }
37788      }else{
37789        memset(dbFileVers, 0, sizeof(dbFileVers));
37790      }
37791
37792      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
37793        pager_reset(pPager);
37794      }
37795    }
37796    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
37797
37798    /* If there is a WAL file in the file-system, open this database in WAL
37799    ** mode. Otherwise, the following function call is a no-op.
37800    */
37801    rc = pagerOpenWalIfPresent(pPager);
37802  }
37803
37804 failed:
37805  if( rc!=SQLITE_OK ){
37806    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
37807    pager_unlock(pPager);
37808  }
37809  return rc;
37810}
37811
37812/*
37813** If the reference count has reached zero, rollback any active
37814** transaction and unlock the pager.
37815**
37816** Except, in locking_mode=EXCLUSIVE when there is nothing to in
37817** the rollback journal, the unlock is not performed and there is
37818** nothing to rollback, so this routine is a no-op.
37819*/
37820static void pagerUnlockIfUnused(Pager *pPager){
37821  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
37822   && (!pPager->exclusiveMode || pPager->journalOff>0)
37823  ){
37824    pagerUnlockAndRollback(pPager);
37825  }
37826}
37827
37828/*
37829** Acquire a reference to page number pgno in pager pPager (a page
37830** reference has type DbPage*). If the requested reference is
37831** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
37832**
37833** If the requested page is already in the cache, it is returned.
37834** Otherwise, a new page object is allocated and populated with data
37835** read from the database file. In some cases, the pcache module may
37836** choose not to allocate a new page object and may reuse an existing
37837** object with no outstanding references.
37838**
37839** The extra data appended to a page is always initialized to zeros the
37840** first time a page is loaded into memory. If the page requested is
37841** already in the cache when this function is called, then the extra
37842** data is left as it was when the page object was last used.
37843**
37844** If the database image is smaller than the requested page or if a
37845** non-zero value is passed as the noContent parameter and the
37846** requested page is not already stored in the cache, then no
37847** actual disk read occurs. In this case the memory image of the
37848** page is initialized to all zeros.
37849**
37850** If noContent is true, it means that we do not care about the contents
37851** of the page. This occurs in two seperate scenarios:
37852**
37853**   a) When reading a free-list leaf page from the database, and
37854**
37855**   b) When a savepoint is being rolled back and we need to load
37856**      a new page into the cache to be filled with the data read
37857**      from the savepoint journal.
37858**
37859** If noContent is true, then the data returned is zeroed instead of
37860** being read from the database. Additionally, the bits corresponding
37861** to pgno in Pager.pInJournal (bitvec of pages already written to the
37862** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
37863** savepoints are set. This means if the page is made writable at any
37864** point in the future, using a call to sqlite3PagerWrite(), its contents
37865** will not be journaled. This saves IO.
37866**
37867** The acquisition might fail for several reasons.  In all cases,
37868** an appropriate error code is returned and *ppPage is set to NULL.
37869**
37870** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
37871** to find a page in the in-memory cache first.  If the page is not already
37872** in memory, this routine goes to disk to read it in whereas Lookup()
37873** just returns 0.  This routine acquires a read-lock the first time it
37874** has to go to disk, and could also playback an old journal if necessary.
37875** Since Lookup() never goes to disk, it never has to deal with locks
37876** or journal files.
37877*/
37878SQLITE_PRIVATE int sqlite3PagerAcquire(
37879  Pager *pPager,      /* The pager open on the database file */
37880  Pgno pgno,          /* Page number to fetch */
37881  DbPage **ppPage,    /* Write a pointer to the page here */
37882  int noContent       /* Do not bother reading content from disk if true */
37883){
37884  int rc;
37885  PgHdr *pPg;
37886
37887  assert( assert_pager_state(pPager) );
37888  assert( pPager->state>PAGER_UNLOCK );
37889
37890  if( pgno==0 ){
37891    return SQLITE_CORRUPT_BKPT;
37892  }
37893
37894  /* If the pager is in the error state, return an error immediately.
37895  ** Otherwise, request the page from the PCache layer. */
37896  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
37897    rc = pPager->errCode;
37898  }else{
37899    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
37900  }
37901
37902  if( rc!=SQLITE_OK ){
37903    /* Either the call to sqlite3PcacheFetch() returned an error or the
37904    ** pager was already in the error-state when this function was called.
37905    ** Set pPg to 0 and jump to the exception handler.  */
37906    pPg = 0;
37907    goto pager_acquire_err;
37908  }
37909  assert( (*ppPage)->pgno==pgno );
37910  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
37911
37912  if( (*ppPage)->pPager && !noContent ){
37913    /* In this case the pcache already contains an initialized copy of
37914    ** the page. Return without further ado.  */
37915    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
37916    PAGER_INCR(pPager->nHit);
37917    return SQLITE_OK;
37918
37919  }else{
37920    /* The pager cache has created a new page. Its content needs to
37921    ** be initialized.  */
37922    int nMax;
37923
37924    PAGER_INCR(pPager->nMiss);
37925    pPg = *ppPage;
37926    pPg->pPager = pPager;
37927
37928    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
37929    ** number greater than this, or the unused locking-page, is requested. */
37930    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
37931      rc = SQLITE_CORRUPT_BKPT;
37932      goto pager_acquire_err;
37933    }
37934
37935    rc = sqlite3PagerPagecount(pPager, &nMax);
37936    if( rc!=SQLITE_OK ){
37937      goto pager_acquire_err;
37938    }
37939
37940    if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
37941      if( pgno>pPager->mxPgno ){
37942        rc = SQLITE_FULL;
37943        goto pager_acquire_err;
37944      }
37945      if( noContent ){
37946        /* Failure to set the bits in the InJournal bit-vectors is benign.
37947        ** It merely means that we might do some extra work to journal a
37948        ** page that does not need to be journaled.  Nevertheless, be sure
37949        ** to test the case where a malloc error occurs while trying to set
37950        ** a bit in a bit vector.
37951        */
37952        sqlite3BeginBenignMalloc();
37953        if( pgno<=pPager->dbOrigSize ){
37954          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
37955          testcase( rc==SQLITE_NOMEM );
37956        }
37957        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
37958        testcase( rc==SQLITE_NOMEM );
37959        sqlite3EndBenignMalloc();
37960      }
37961      memset(pPg->pData, 0, pPager->pageSize);
37962      IOTRACE(("ZERO %p %d\n", pPager, pgno));
37963    }else{
37964      assert( pPg->pPager==pPager );
37965      rc = readDbPage(pPg);
37966      if( rc!=SQLITE_OK ){
37967        goto pager_acquire_err;
37968      }
37969    }
37970#ifdef SQLITE_CHECK_PAGES
37971    pPg->pageHash = pager_pagehash(pPg);
37972#endif
37973  }
37974
37975  return SQLITE_OK;
37976
37977pager_acquire_err:
37978  assert( rc!=SQLITE_OK );
37979  if( pPg ){
37980    sqlite3PcacheDrop(pPg);
37981  }
37982  pagerUnlockIfUnused(pPager);
37983
37984  *ppPage = 0;
37985  return rc;
37986}
37987
37988/*
37989** Acquire a page if it is already in the in-memory cache.  Do
37990** not read the page from disk.  Return a pointer to the page,
37991** or 0 if the page is not in cache. Also, return 0 if the
37992** pager is in PAGER_UNLOCK state when this function is called,
37993** or if the pager is in an error state other than SQLITE_FULL.
37994**
37995** See also sqlite3PagerGet().  The difference between this routine
37996** and sqlite3PagerGet() is that _get() will go to the disk and read
37997** in the page if the page is not already in cache.  This routine
37998** returns NULL if the page is not in cache or if a disk I/O error
37999** has ever happened.
38000*/
38001SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
38002  PgHdr *pPg = 0;
38003  assert( pPager!=0 );
38004  assert( pgno!=0 );
38005  assert( pPager->pPCache!=0 );
38006  assert( pPager->state > PAGER_UNLOCK );
38007  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
38008  return pPg;
38009}
38010
38011/*
38012** Release a page reference.
38013**
38014** If the number of references to the page drop to zero, then the
38015** page is added to the LRU list.  When all references to all pages
38016** are released, a rollback occurs and the lock on the database is
38017** removed.
38018*/
38019SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
38020  if( pPg ){
38021    Pager *pPager = pPg->pPager;
38022    sqlite3PcacheRelease(pPg);
38023    pagerUnlockIfUnused(pPager);
38024  }
38025}
38026
38027/*
38028** This function is called at the start of every write transaction.
38029** There must already be a RESERVED or EXCLUSIVE lock on the database
38030** file when this routine is called.
38031**
38032** Open the journal file for pager pPager and write a journal header
38033** to the start of it. If there are active savepoints, open the sub-journal
38034** as well. This function is only used when the journal file is being
38035** opened to write a rollback log for a transaction. It is not used
38036** when opening a hot journal file to roll it back.
38037**
38038** If the journal file is already open (as it may be in exclusive mode),
38039** then this function just writes a journal header to the start of the
38040** already open file.
38041**
38042** Whether or not the journal file is opened by this function, the
38043** Pager.pInJournal bitvec structure is allocated.
38044**
38045** Return SQLITE_OK if everything is successful. Otherwise, return
38046** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
38047** an IO error code if opening or writing the journal file fails.
38048*/
38049static int pager_open_journal(Pager *pPager){
38050  int rc = SQLITE_OK;                        /* Return code */
38051  int nPage;                                 /* Size of database file */
38052  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
38053
38054  assert( pPager->state>=PAGER_RESERVED );
38055  assert( pPager->useJournal );
38056  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
38057  assert( pPager->pInJournal==0 );
38058
38059  /* If already in the error state, this function is a no-op.  But on
38060  ** the other hand, this routine is never called if we are already in
38061  ** an error state. */
38062  if( NEVER(pPager->errCode) ) return pPager->errCode;
38063
38064  testcase( pPager->dbSizeValid==0 );
38065  rc = sqlite3PagerPagecount(pPager, &nPage);
38066  if( rc ) return rc;
38067  pPager->pInJournal = sqlite3BitvecCreate(nPage);
38068  if( pPager->pInJournal==0 ){
38069    return SQLITE_NOMEM;
38070  }
38071
38072  /* Open the journal file if it is not already open. */
38073  if( !isOpen(pPager->jfd) ){
38074    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
38075      sqlite3MemJournalOpen(pPager->jfd);
38076    }else{
38077      const int flags =                   /* VFS flags to open journal file */
38078        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
38079        (pPager->tempFile ?
38080          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
38081          (SQLITE_OPEN_MAIN_JOURNAL)
38082        );
38083#ifdef SQLITE_ENABLE_ATOMIC_WRITE
38084      rc = sqlite3JournalOpen(
38085          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
38086      );
38087#else
38088      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
38089#endif
38090    }
38091    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38092  }
38093
38094
38095  /* Write the first journal header to the journal file and open
38096  ** the sub-journal if necessary.
38097  */
38098  if( rc==SQLITE_OK ){
38099    /* TODO: Check if all of these are really required. */
38100    pPager->dbOrigSize = pPager->dbSize;
38101    pPager->journalStarted = 0;
38102    pPager->needSync = 0;
38103    pPager->nRec = 0;
38104    pPager->journalOff = 0;
38105    pPager->setMaster = 0;
38106    pPager->journalHdr = 0;
38107    rc = writeJournalHdr(pPager);
38108  }
38109
38110  if( rc!=SQLITE_OK ){
38111    sqlite3BitvecDestroy(pPager->pInJournal);
38112    pPager->pInJournal = 0;
38113  }
38114  return rc;
38115}
38116
38117/*
38118** Begin a write-transaction on the specified pager object. If a
38119** write-transaction has already been opened, this function is a no-op.
38120**
38121** If the exFlag argument is false, then acquire at least a RESERVED
38122** lock on the database file. If exFlag is true, then acquire at least
38123** an EXCLUSIVE lock. If such a lock is already held, no locking
38124** functions need be called.
38125**
38126** If this is not a temporary or in-memory file and, the journal file is
38127** opened if it has not been already. For a temporary file, the opening
38128** of the journal file is deferred until there is an actual need to
38129** write to the journal. TODO: Why handle temporary files differently?
38130**
38131** If the journal file is opened (or if it is already open), then a
38132** journal-header is written to the start of it.
38133**
38134** If the subjInMemory argument is non-zero, then any sub-journal opened
38135** within this transaction will be opened as an in-memory file. This
38136** has no effect if the sub-journal is already opened (as it may be when
38137** running in exclusive mode) or if the transaction does not require a
38138** sub-journal. If the subjInMemory argument is zero, then any required
38139** sub-journal is implemented in-memory if pPager is an in-memory database,
38140** or using a temporary file otherwise.
38141*/
38142SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
38143  int rc = SQLITE_OK;
38144  assert( pPager->state!=PAGER_UNLOCK );
38145  pPager->subjInMemory = (u8)subjInMemory;
38146
38147  if( pPager->state==PAGER_SHARED ){
38148    assert( pPager->pInJournal==0 );
38149    assert( !MEMDB && !pPager->tempFile );
38150
38151    if( pagerUseWal(pPager) ){
38152      /* If the pager is configured to use locking_mode=exclusive, and an
38153      ** exclusive lock on the database is not already held, obtain it now.
38154      */
38155      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
38156        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
38157        pPager->state = PAGER_SHARED;
38158        if( rc!=SQLITE_OK ){
38159          return rc;
38160        }
38161        sqlite3WalExclusiveMode(pPager->pWal, 1);
38162      }
38163
38164      /* Grab the write lock on the log file. If successful, upgrade to
38165      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
38166      ** The busy-handler is not invoked if another connection already
38167      ** holds the write-lock. If possible, the upper layer will call it.
38168      **
38169      ** WAL mode sets Pager.state to PAGER_RESERVED when it has an open
38170      ** transaction, but never to PAGER_EXCLUSIVE. This is because in
38171      ** PAGER_EXCLUSIVE state the code to roll back savepoint transactions
38172      ** may copy data from the sub-journal into the database file as well
38173      ** as into the page cache. Which would be incorrect in WAL mode.
38174      */
38175      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
38176      if( rc==SQLITE_OK ){
38177        pPager->dbOrigSize = pPager->dbSize;
38178        pPager->state = PAGER_RESERVED;
38179        pPager->journalOff = 0;
38180      }
38181
38182      assert( rc!=SQLITE_OK || pPager->state==PAGER_RESERVED );
38183      assert( rc==SQLITE_OK || pPager->state==PAGER_SHARED );
38184    }else{
38185      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
38186      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
38187      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
38188      ** lock, but not when obtaining the RESERVED lock.
38189      */
38190      rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
38191      if( rc==SQLITE_OK ){
38192        pPager->state = PAGER_RESERVED;
38193        if( exFlag ){
38194          rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
38195        }
38196      }
38197    }
38198
38199    /* No need to open the journal file at this time.  It will be
38200    ** opened before it is written to.  If we defer opening the journal,
38201    ** we might save the work of creating a file if the transaction
38202    ** ends up being a no-op.
38203    */
38204  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
38205    /* This happens when the pager was in exclusive-access mode the last
38206    ** time a (read or write) transaction was successfully concluded
38207    ** by this connection. Instead of deleting the journal file it was
38208    ** kept open and either was truncated to 0 bytes or its header was
38209    ** overwritten with zeros.
38210    */
38211    assert( pagerUseWal(pPager)==0 );
38212    assert( pPager->nRec==0 );
38213    assert( pPager->dbOrigSize==0 );
38214    assert( pPager->pInJournal==0 );
38215    rc = pager_open_journal(pPager);
38216  }
38217
38218  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
38219  if( rc!=SQLITE_OK ){
38220    assert( !pPager->dbModified );
38221    /* Ignore any IO error that occurs within pager_end_transaction(). The
38222    ** purpose of this call is to reset the internal state of the pager
38223    ** sub-system. It doesn't matter if the journal-file is not properly
38224    ** finalized at this point (since it is not a valid journal file anyway).
38225    */
38226    pager_end_transaction(pPager, 0);
38227  }
38228  return rc;
38229}
38230
38231/*
38232** Mark a single data page as writeable. The page is written into the
38233** main journal or sub-journal as required. If the page is written into
38234** one of the journals, the corresponding bit is set in the
38235** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
38236** of any open savepoints as appropriate.
38237*/
38238static int pager_write(PgHdr *pPg){
38239  void *pData = pPg->pData;
38240  Pager *pPager = pPg->pPager;
38241  int rc = SQLITE_OK;
38242
38243  /* This routine is not called unless a transaction has already been
38244  ** started.
38245  */
38246  assert( pPager->state>=PAGER_RESERVED );
38247
38248  /* If an error has been previously detected, report the same error
38249  ** again.
38250  */
38251  if( NEVER(pPager->errCode) )  return pPager->errCode;
38252
38253  /* Higher-level routines never call this function if database is not
38254  ** writable.  But check anyway, just for robustness. */
38255  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
38256
38257  assert( !pPager->setMaster );
38258
38259  CHECK_PAGE(pPg);
38260
38261  /* Mark the page as dirty.  If the page has already been written
38262  ** to the journal then we can return right away.
38263  */
38264  sqlite3PcacheMakeDirty(pPg);
38265  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
38266    assert( !pagerUseWal(pPager) );
38267    pPager->dbModified = 1;
38268  }else{
38269
38270    /* If we get this far, it means that the page needs to be
38271    ** written to the transaction journal or the ckeckpoint journal
38272    ** or both.
38273    **
38274    ** Higher level routines should have already started a transaction,
38275    ** which means they have acquired the necessary locks but the rollback
38276    ** journal might not yet be open.
38277    */
38278    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
38279    if( rc!=SQLITE_OK ){
38280      return rc;
38281    }
38282    if( pPager->pInJournal==0
38283     && pPager->journalMode!=PAGER_JOURNALMODE_OFF
38284     && !pagerUseWal(pPager)
38285    ){
38286      assert( pPager->useJournal );
38287      rc = pager_open_journal(pPager);
38288      if( rc!=SQLITE_OK ) return rc;
38289    }
38290    pPager->dbModified = 1;
38291
38292    /* The transaction journal now exists and we have a RESERVED or an
38293    ** EXCLUSIVE lock on the main database file.  Write the current page to
38294    ** the transaction journal if it is not there already.
38295    */
38296    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
38297      assert( !pagerUseWal(pPager) );
38298      if( pPg->pgno<=pPager->dbOrigSize ){
38299        u32 cksum;
38300        char *pData2;
38301
38302        /* We should never write to the journal file the page that
38303        ** contains the database locks.  The following assert verifies
38304        ** that we do not. */
38305        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
38306
38307        assert( pPager->journalHdr <= pPager->journalOff );
38308        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38309        cksum = pager_cksum(pPager, (u8*)pData2);
38310        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
38311        if( rc==SQLITE_OK ){
38312          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
38313                              pPager->journalOff + 4);
38314          pPager->journalOff += pPager->pageSize+4;
38315        }
38316        if( rc==SQLITE_OK ){
38317          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
38318          pPager->journalOff += 4;
38319        }
38320        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
38321                 pPager->journalOff, pPager->pageSize));
38322        PAGER_INCR(sqlite3_pager_writej_count);
38323        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
38324             PAGERID(pPager), pPg->pgno,
38325             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
38326
38327        /* Even if an IO or diskfull error occurred while journalling the
38328        ** page in the block above, set the need-sync flag for the page.
38329        ** Otherwise, when the transaction is rolled back, the logic in
38330        ** playback_one_page() will think that the page needs to be restored
38331        ** in the database file. And if an IO error occurs while doing so,
38332        ** then corruption may follow.
38333        */
38334        if( !pPager->noSync ){
38335          pPg->flags |= PGHDR_NEED_SYNC;
38336          pPager->needSync = 1;
38337        }
38338
38339        /* An error has occurred writing to the journal file. The
38340        ** transaction will be rolled back by the layer above.
38341        */
38342        if( rc!=SQLITE_OK ){
38343          return rc;
38344        }
38345
38346        pPager->nRec++;
38347        assert( pPager->pInJournal!=0 );
38348        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
38349        testcase( rc==SQLITE_NOMEM );
38350        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38351        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
38352        if( rc!=SQLITE_OK ){
38353          assert( rc==SQLITE_NOMEM );
38354          return rc;
38355        }
38356      }else{
38357        if( !pPager->journalStarted && !pPager->noSync ){
38358          pPg->flags |= PGHDR_NEED_SYNC;
38359          pPager->needSync = 1;
38360        }
38361        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
38362                PAGERID(pPager), pPg->pgno,
38363               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
38364      }
38365    }
38366
38367    /* If the statement journal is open and the page is not in it,
38368    ** then write the current page to the statement journal.  Note that
38369    ** the statement journal format differs from the standard journal format
38370    ** in that it omits the checksums and the header.
38371    */
38372    if( subjRequiresPage(pPg) ){
38373      rc = subjournalPage(pPg);
38374    }
38375  }
38376
38377  /* Update the database size and return.
38378  */
38379  assert( pPager->state>=PAGER_SHARED );
38380  if( pPager->dbSize<pPg->pgno ){
38381    pPager->dbSize = pPg->pgno;
38382  }
38383  return rc;
38384}
38385
38386/*
38387** Mark a data page as writeable. This routine must be called before
38388** making changes to a page. The caller must check the return value
38389** of this function and be careful not to change any page data unless
38390** this routine returns SQLITE_OK.
38391**
38392** The difference between this function and pager_write() is that this
38393** function also deals with the special case where 2 or more pages
38394** fit on a single disk sector. In this case all co-resident pages
38395** must have been written to the journal file before returning.
38396**
38397** If an error occurs, SQLITE_NOMEM or an IO error code is returned
38398** as appropriate. Otherwise, SQLITE_OK.
38399*/
38400SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
38401  int rc = SQLITE_OK;
38402
38403  PgHdr *pPg = pDbPage;
38404  Pager *pPager = pPg->pPager;
38405  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
38406
38407  if( nPagePerSector>1 ){
38408    Pgno nPageCount;          /* Total number of pages in database file */
38409    Pgno pg1;                 /* First page of the sector pPg is located on. */
38410    int nPage = 0;            /* Number of pages starting at pg1 to journal */
38411    int ii;                   /* Loop counter */
38412    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
38413
38414    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
38415    ** a journal header to be written between the pages journaled by
38416    ** this function.
38417    */
38418    assert( !MEMDB );
38419    assert( pPager->doNotSyncSpill==0 );
38420    pPager->doNotSyncSpill++;
38421
38422    /* This trick assumes that both the page-size and sector-size are
38423    ** an integer power of 2. It sets variable pg1 to the identifier
38424    ** of the first page of the sector pPg is located on.
38425    */
38426    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
38427
38428    rc = sqlite3PagerPagecount(pPager, (int *)&nPageCount);
38429    if( rc==SQLITE_OK ){
38430      if( pPg->pgno>nPageCount ){
38431        nPage = (pPg->pgno - pg1)+1;
38432      }else if( (pg1+nPagePerSector-1)>nPageCount ){
38433        nPage = nPageCount+1-pg1;
38434      }else{
38435        nPage = nPagePerSector;
38436      }
38437      assert(nPage>0);
38438      assert(pg1<=pPg->pgno);
38439      assert((pg1+nPage)>pPg->pgno);
38440    }
38441
38442    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
38443      Pgno pg = pg1+ii;
38444      PgHdr *pPage;
38445      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
38446        if( pg!=PAGER_MJ_PGNO(pPager) ){
38447          rc = sqlite3PagerGet(pPager, pg, &pPage);
38448          if( rc==SQLITE_OK ){
38449            rc = pager_write(pPage);
38450            if( pPage->flags&PGHDR_NEED_SYNC ){
38451              needSync = 1;
38452              assert(pPager->needSync);
38453            }
38454            sqlite3PagerUnref(pPage);
38455          }
38456        }
38457      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
38458        if( pPage->flags&PGHDR_NEED_SYNC ){
38459          needSync = 1;
38460        }
38461        sqlite3PagerUnref(pPage);
38462      }
38463    }
38464
38465    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
38466    ** starting at pg1, then it needs to be set for all of them. Because
38467    ** writing to any of these nPage pages may damage the others, the
38468    ** journal file must contain sync()ed copies of all of them
38469    ** before any of them can be written out to the database file.
38470    */
38471    if( rc==SQLITE_OK && needSync ){
38472      assert( !MEMDB && pPager->noSync==0 );
38473      for(ii=0; ii<nPage; ii++){
38474        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
38475        if( pPage ){
38476          pPage->flags |= PGHDR_NEED_SYNC;
38477          sqlite3PagerUnref(pPage);
38478        }
38479      }
38480      assert(pPager->needSync);
38481    }
38482
38483    assert( pPager->doNotSyncSpill==1 );
38484    pPager->doNotSyncSpill--;
38485  }else{
38486    rc = pager_write(pDbPage);
38487  }
38488  return rc;
38489}
38490
38491/*
38492** Return TRUE if the page given in the argument was previously passed
38493** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
38494** to change the content of the page.
38495*/
38496#ifndef NDEBUG
38497SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
38498  return pPg->flags&PGHDR_DIRTY;
38499}
38500#endif
38501
38502/*
38503** A call to this routine tells the pager that it is not necessary to
38504** write the information on page pPg back to the disk, even though
38505** that page might be marked as dirty.  This happens, for example, when
38506** the page has been added as a leaf of the freelist and so its
38507** content no longer matters.
38508**
38509** The overlying software layer calls this routine when all of the data
38510** on the given page is unused. The pager marks the page as clean so
38511** that it does not get written to disk.
38512**
38513** Tests show that this optimization can quadruple the speed of large
38514** DELETE operations.
38515*/
38516SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
38517  Pager *pPager = pPg->pPager;
38518  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
38519    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
38520    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
38521    pPg->flags |= PGHDR_DONT_WRITE;
38522#ifdef SQLITE_CHECK_PAGES
38523    pPg->pageHash = pager_pagehash(pPg);
38524#endif
38525  }
38526}
38527
38528/*
38529** This routine is called to increment the value of the database file
38530** change-counter, stored as a 4-byte big-endian integer starting at
38531** byte offset 24 of the pager file.
38532**
38533** If the isDirectMode flag is zero, then this is done by calling
38534** sqlite3PagerWrite() on page 1, then modifying the contents of the
38535** page data. In this case the file will be updated when the current
38536** transaction is committed.
38537**
38538** The isDirectMode flag may only be non-zero if the library was compiled
38539** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
38540** if isDirect is non-zero, then the database file is updated directly
38541** by writing an updated version of page 1 using a call to the
38542** sqlite3OsWrite() function.
38543*/
38544static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
38545  int rc = SQLITE_OK;
38546
38547  /* Declare and initialize constant integer 'isDirect'. If the
38548  ** atomic-write optimization is enabled in this build, then isDirect
38549  ** is initialized to the value passed as the isDirectMode parameter
38550  ** to this function. Otherwise, it is always set to zero.
38551  **
38552  ** The idea is that if the atomic-write optimization is not
38553  ** enabled at compile time, the compiler can omit the tests of
38554  ** 'isDirect' below, as well as the block enclosed in the
38555  ** "if( isDirect )" condition.
38556  */
38557#ifndef SQLITE_ENABLE_ATOMIC_WRITE
38558# define DIRECT_MODE 0
38559  assert( isDirectMode==0 );
38560  UNUSED_PARAMETER(isDirectMode);
38561#else
38562# define DIRECT_MODE isDirectMode
38563#endif
38564
38565  assert( pPager->state>=PAGER_RESERVED );
38566  if( !pPager->changeCountDone && pPager->dbSize>0 ){
38567    PgHdr *pPgHdr;                /* Reference to page 1 */
38568    u32 change_counter;           /* Initial value of change-counter field */
38569
38570    assert( !pPager->tempFile && isOpen(pPager->fd) );
38571
38572    /* Open page 1 of the file for writing. */
38573    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
38574    assert( pPgHdr==0 || rc==SQLITE_OK );
38575
38576    /* If page one was fetched successfully, and this function is not
38577    ** operating in direct-mode, make page 1 writable.  When not in
38578    ** direct mode, page 1 is always held in cache and hence the PagerGet()
38579    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
38580    */
38581    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
38582      rc = sqlite3PagerWrite(pPgHdr);
38583    }
38584
38585    if( rc==SQLITE_OK ){
38586      /* Increment the value just read and write it back to byte 24. */
38587      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
38588      change_counter++;
38589      put32bits(((char*)pPgHdr->pData)+24, change_counter);
38590
38591      /* Also store the SQLite version number in bytes 96..99 and in
38592      ** bytes 92..95 store the change counter for which the version number
38593      ** is valid. */
38594      put32bits(((char*)pPgHdr->pData)+92, change_counter);
38595      put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
38596
38597      /* If running in direct mode, write the contents of page 1 to the file. */
38598      if( DIRECT_MODE ){
38599        const void *zBuf;
38600        assert( pPager->dbFileSize>0 );
38601        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
38602        if( rc==SQLITE_OK ){
38603          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
38604        }
38605        if( rc==SQLITE_OK ){
38606          pPager->changeCountDone = 1;
38607        }
38608      }else{
38609        pPager->changeCountDone = 1;
38610      }
38611    }
38612
38613    /* Release the page reference. */
38614    sqlite3PagerUnref(pPgHdr);
38615  }
38616  return rc;
38617}
38618
38619/*
38620** Sync the pager file to disk. This is a no-op for in-memory files
38621** or pages with the Pager.noSync flag set.
38622**
38623** If successful, or called on a pager for which it is a no-op, this
38624** function returns SQLITE_OK. Otherwise, an IO error code is returned.
38625*/
38626SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
38627  int rc;                              /* Return code */
38628  assert( !MEMDB );
38629  if( pPager->noSync ){
38630    rc = SQLITE_OK;
38631  }else{
38632    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
38633  }
38634  return rc;
38635}
38636
38637/*
38638** Sync the database file for the pager pPager. zMaster points to the name
38639** of a master journal file that should be written into the individual
38640** journal file. zMaster may be NULL, which is interpreted as no master
38641** journal (a single database transaction).
38642**
38643** This routine ensures that:
38644**
38645**   * The database file change-counter is updated,
38646**   * the journal is synced (unless the atomic-write optimization is used),
38647**   * all dirty pages are written to the database file,
38648**   * the database file is truncated (if required), and
38649**   * the database file synced.
38650**
38651** The only thing that remains to commit the transaction is to finalize
38652** (delete, truncate or zero the first part of) the journal file (or
38653** delete the master journal file if specified).
38654**
38655** Note that if zMaster==NULL, this does not overwrite a previous value
38656** passed to an sqlite3PagerCommitPhaseOne() call.
38657**
38658** If the final parameter - noSync - is true, then the database file itself
38659** is not synced. The caller must call sqlite3PagerSync() directly to
38660** sync the database file before calling CommitPhaseTwo() to delete the
38661** journal file in this case.
38662*/
38663SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
38664  Pager *pPager,                  /* Pager object */
38665  const char *zMaster,            /* If not NULL, the master journal name */
38666  int noSync                      /* True to omit the xSync on the db file */
38667){
38668  int rc = SQLITE_OK;             /* Return code */
38669
38670  /* The dbOrigSize is never set if journal_mode=OFF */
38671  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
38672
38673  /* If a prior error occurred, report that error again. */
38674  if( pPager->errCode ) return pPager->errCode;
38675
38676  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
38677      pPager->zFilename, zMaster, pPager->dbSize));
38678
38679  if( MEMDB && pPager->dbModified ){
38680    /* If this is an in-memory db, or no pages have been written to, or this
38681    ** function has already been called, it is mostly a no-op.  However, any
38682    ** backup in progress needs to be restarted.
38683    */
38684    sqlite3BackupRestart(pPager->pBackup);
38685  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
38686    if( pagerUseWal(pPager) ){
38687      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
38688      if( pList ){
38689        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
38690            (pPager->fullSync ? pPager->sync_flags : 0)
38691        );
38692      }
38693      if( rc==SQLITE_OK ){
38694        sqlite3PcacheCleanAll(pPager->pPCache);
38695      }
38696    }else{
38697      /* The following block updates the change-counter. Exactly how it
38698      ** does this depends on whether or not the atomic-update optimization
38699      ** was enabled at compile time, and if this transaction meets the
38700      ** runtime criteria to use the operation:
38701      **
38702      **    * The file-system supports the atomic-write property for
38703      **      blocks of size page-size, and
38704      **    * This commit is not part of a multi-file transaction, and
38705      **    * Exactly one page has been modified and store in the journal file.
38706      **
38707      ** If the optimization was not enabled at compile time, then the
38708      ** pager_incr_changecounter() function is called to update the change
38709      ** counter in 'indirect-mode'. If the optimization is compiled in but
38710      ** is not applicable to this transaction, call sqlite3JournalCreate()
38711      ** to make sure the journal file has actually been created, then call
38712      ** pager_incr_changecounter() to update the change-counter in indirect
38713      ** mode.
38714      **
38715      ** Otherwise, if the optimization is both enabled and applicable,
38716      ** then call pager_incr_changecounter() to update the change-counter
38717      ** in 'direct' mode. In this case the journal file will never be
38718      ** created for this transaction.
38719      */
38720  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38721      PgHdr *pPg;
38722      assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
38723      if( !zMaster && isOpen(pPager->jfd)
38724       && pPager->journalOff==jrnlBufferSize(pPager)
38725       && pPager->dbSize>=pPager->dbFileSize
38726       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
38727      ){
38728        /* Update the db file change counter via the direct-write method. The
38729        ** following call will modify the in-memory representation of page 1
38730        ** to include the updated change counter and then write page 1
38731        ** directly to the database file. Because of the atomic-write
38732        ** property of the host file-system, this is safe.
38733        */
38734        rc = pager_incr_changecounter(pPager, 1);
38735      }else{
38736        rc = sqlite3JournalCreate(pPager->jfd);
38737        if( rc==SQLITE_OK ){
38738          rc = pager_incr_changecounter(pPager, 0);
38739        }
38740      }
38741  #else
38742      rc = pager_incr_changecounter(pPager, 0);
38743  #endif
38744      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38745
38746      /* If this transaction has made the database smaller, then all pages
38747      ** being discarded by the truncation must be written to the journal
38748      ** file. This can only happen in auto-vacuum mode.
38749      **
38750      ** Before reading the pages with page numbers larger than the
38751      ** current value of Pager.dbSize, set dbSize back to the value
38752      ** that it took at the start of the transaction. Otherwise, the
38753      ** calls to sqlite3PagerGet() return zeroed pages instead of
38754      ** reading data from the database file.
38755      **
38756      ** When journal_mode==OFF the dbOrigSize is always zero, so this
38757      ** block never runs if journal_mode=OFF.
38758      */
38759  #ifndef SQLITE_OMIT_AUTOVACUUM
38760      if( pPager->dbSize<pPager->dbOrigSize
38761       && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
38762      ){
38763        Pgno i;                                   /* Iterator variable */
38764        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
38765        const Pgno dbSize = pPager->dbSize;       /* Database image size */
38766        pPager->dbSize = pPager->dbOrigSize;
38767        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
38768          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
38769            PgHdr *pPage;             /* Page to journal */
38770            rc = sqlite3PagerGet(pPager, i, &pPage);
38771            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38772            rc = sqlite3PagerWrite(pPage);
38773            sqlite3PagerUnref(pPage);
38774            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38775          }
38776        }
38777        pPager->dbSize = dbSize;
38778      }
38779  #endif
38780
38781      /* Write the master journal name into the journal file. If a master
38782      ** journal file name has already been written to the journal file,
38783      ** or if zMaster is NULL (no master journal), then this call is a no-op.
38784      */
38785      rc = writeMasterJournal(pPager, zMaster);
38786      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38787
38788      /* Sync the journal file. If the atomic-update optimization is being
38789      ** used, this call will not create the journal file or perform any
38790      ** real IO.
38791      */
38792      rc = syncJournal(pPager);
38793      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38794
38795      /* Write all dirty pages to the database file. */
38796      rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
38797      if( rc!=SQLITE_OK ){
38798        assert( rc!=SQLITE_IOERR_BLOCKED );
38799        goto commit_phase_one_exit;
38800      }
38801      sqlite3PcacheCleanAll(pPager->pPCache);
38802
38803      /* If the file on disk is not the same size as the database image,
38804      ** then use pager_truncate to grow or shrink the file here.
38805      */
38806      if( pPager->dbSize!=pPager->dbFileSize ){
38807        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
38808        assert( pPager->state>=PAGER_EXCLUSIVE );
38809        rc = pager_truncate(pPager, nNew);
38810        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
38811      }
38812
38813      /* Finally, sync the database file. */
38814      if( !pPager->noSync && !noSync ){
38815        rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
38816      }
38817      IOTRACE(("DBSYNC %p\n", pPager))
38818    }
38819
38820    pPager->state = PAGER_SYNCED;
38821  }
38822
38823commit_phase_one_exit:
38824  return rc;
38825}
38826
38827
38828/*
38829** When this function is called, the database file has been completely
38830** updated to reflect the changes made by the current transaction and
38831** synced to disk. The journal file still exists in the file-system
38832** though, and if a failure occurs at this point it will eventually
38833** be used as a hot-journal and the current transaction rolled back.
38834**
38835** This function finalizes the journal file, either by deleting,
38836** truncating or partially zeroing it, so that it cannot be used
38837** for hot-journal rollback. Once this is done the transaction is
38838** irrevocably committed.
38839**
38840** If an error occurs, an IO error code is returned and the pager
38841** moves into the error state. Otherwise, SQLITE_OK is returned.
38842*/
38843SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
38844  int rc = SQLITE_OK;                  /* Return code */
38845
38846  /* This routine should not be called if a prior error has occurred.
38847  ** But if (due to a coding error elsewhere in the system) it does get
38848  ** called, just return the same error code without doing anything. */
38849  if( NEVER(pPager->errCode) ) return pPager->errCode;
38850
38851  /* This function should not be called if the pager is not in at least
38852  ** PAGER_RESERVED state. **FIXME**: Make it so that this test always
38853  ** fails - make it so that we never reach this point if we do not hold
38854  ** all necessary locks.
38855  */
38856  if( pPager->state<PAGER_RESERVED ) return SQLITE_ERROR;
38857
38858  /* An optimization. If the database was not actually modified during
38859  ** this transaction, the pager is running in exclusive-mode and is
38860  ** using persistent journals, then this function is a no-op.
38861  **
38862  ** The start of the journal file currently contains a single journal
38863  ** header with the nRec field set to 0. If such a journal is used as
38864  ** a hot-journal during hot-journal rollback, 0 changes will be made
38865  ** to the database file. So there is no need to zero the journal
38866  ** header. Since the pager is in exclusive mode, there is no need
38867  ** to drop any locks either.
38868  */
38869  if( pPager->dbModified==0 && pPager->exclusiveMode
38870   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38871  ){
38872    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
38873    return SQLITE_OK;
38874  }
38875
38876  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
38877  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
38878  rc = pager_end_transaction(pPager, pPager->setMaster);
38879  return pager_error(pPager, rc);
38880}
38881
38882/*
38883** Rollback all changes. The database falls back to PAGER_SHARED mode.
38884**
38885** This function performs two tasks:
38886**
38887**   1) It rolls back the journal file, restoring all database file and
38888**      in-memory cache pages to the state they were in when the transaction
38889**      was opened, and
38890**   2) It finalizes the journal file, so that it is not used for hot
38891**      rollback at any point in the future.
38892**
38893** subject to the following qualifications:
38894**
38895** * If the journal file is not yet open when this function is called,
38896**   then only (2) is performed. In this case there is no journal file
38897**   to roll back.
38898**
38899** * If in an error state other than SQLITE_FULL, then task (1) is
38900**   performed. If successful, task (2). Regardless of the outcome
38901**   of either, the error state error code is returned to the caller
38902**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
38903**
38904** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
38905**   or not (1) is successful, also attempt (2). If successful, return
38906**   SQLITE_OK. Otherwise, enter the error state and return the first
38907**   error code encountered.
38908**
38909**   In this case there is no chance that the database was written to.
38910**   So is safe to finalize the journal file even if the playback
38911**   (operation 1) failed. However the pager must enter the error state
38912**   as the contents of the in-memory cache are now suspect.
38913**
38914** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
38915**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
38916**   otherwise enter the error state and return the error code from the
38917**   failing operation.
38918**
38919**   In this case the database file may have been written to. So if the
38920**   playback operation did not succeed it would not be safe to finalize
38921**   the journal file. It needs to be left in the file-system so that
38922**   some other process can use it to restore the database state (by
38923**   hot-journal rollback).
38924*/
38925SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
38926  int rc = SQLITE_OK;                  /* Return code */
38927  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
38928  if( pagerUseWal(pPager) ){
38929    int rc2;
38930
38931    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
38932    rc2 = pager_end_transaction(pPager, pPager->setMaster);
38933    if( rc==SQLITE_OK ) rc = rc2;
38934    rc = pager_error(pPager, rc);
38935  }else if( !pPager->dbModified || !isOpen(pPager->jfd) ){
38936    rc = pager_end_transaction(pPager, pPager->setMaster);
38937  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
38938    if( pPager->state>=PAGER_EXCLUSIVE ){
38939      pager_playback(pPager, 0);
38940    }
38941    rc = pPager->errCode;
38942  }else{
38943    if( pPager->state==PAGER_RESERVED ){
38944      int rc2;
38945      rc = pager_playback(pPager, 0);
38946      rc2 = pager_end_transaction(pPager, pPager->setMaster);
38947      if( rc==SQLITE_OK ){
38948        rc = rc2;
38949      }
38950    }else{
38951      rc = pager_playback(pPager, 0);
38952    }
38953
38954    if( !MEMDB ){
38955      pPager->dbSizeValid = 0;
38956    }
38957
38958    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
38959    ** cache. So call pager_error() on the way out to make any error
38960    ** persistent.
38961    */
38962    rc = pager_error(pPager, rc);
38963  }
38964  return rc;
38965}
38966
38967/*
38968** Return TRUE if the database file is opened read-only.  Return FALSE
38969** if the database is (in theory) writable.
38970*/
38971SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
38972  return pPager->readOnly;
38973}
38974
38975/*
38976** Return the number of references to the pager.
38977*/
38978SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
38979  return sqlite3PcacheRefCount(pPager->pPCache);
38980}
38981
38982/*
38983** Return the approximate number of bytes of memory currently
38984** used by the pager and its associated cache.
38985*/
38986SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
38987  int perPageSize = pPager->pageSize + pPager->nExtra + 20;
38988  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
38989           + sqlite3MallocSize(pPager);
38990}
38991
38992/*
38993** Return the number of references to the specified page.
38994*/
38995SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
38996  return sqlite3PcachePageRefcount(pPage);
38997}
38998
38999#ifdef SQLITE_TEST
39000/*
39001** This routine is used for testing and analysis only.
39002*/
39003SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
39004  static int a[11];
39005  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
39006  a[1] = sqlite3PcachePagecount(pPager->pPCache);
39007  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
39008  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
39009  a[4] = pPager->state;
39010  a[5] = pPager->errCode;
39011  a[6] = pPager->nHit;
39012  a[7] = pPager->nMiss;
39013  a[8] = 0;  /* Used to be pPager->nOvfl */
39014  a[9] = pPager->nRead;
39015  a[10] = pPager->nWrite;
39016  return a;
39017}
39018#endif
39019
39020/*
39021** Return true if this is an in-memory pager.
39022*/
39023SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
39024  return MEMDB;
39025}
39026
39027/*
39028** Check that there are at least nSavepoint savepoints open. If there are
39029** currently less than nSavepoints open, then open one or more savepoints
39030** to make up the difference. If the number of savepoints is already
39031** equal to nSavepoint, then this function is a no-op.
39032**
39033** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
39034** occurs while opening the sub-journal file, then an IO error code is
39035** returned. Otherwise, SQLITE_OK.
39036*/
39037SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
39038  int rc = SQLITE_OK;                       /* Return code */
39039  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
39040
39041  if( nSavepoint>nCurrent && pPager->useJournal ){
39042    int ii;                                 /* Iterator variable */
39043    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
39044    int nPage;                              /* Size of database file */
39045
39046    rc = sqlite3PagerPagecount(pPager, &nPage);
39047    if( rc ) return rc;
39048
39049    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
39050    ** if the allocation fails. Otherwise, zero the new portion in case a
39051    ** malloc failure occurs while populating it in the for(...) loop below.
39052    */
39053    aNew = (PagerSavepoint *)sqlite3Realloc(
39054        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
39055    );
39056    if( !aNew ){
39057      return SQLITE_NOMEM;
39058    }
39059    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
39060    pPager->aSavepoint = aNew;
39061
39062    /* Populate the PagerSavepoint structures just allocated. */
39063    for(ii=nCurrent; ii<nSavepoint; ii++){
39064      aNew[ii].nOrig = nPage;
39065      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
39066        aNew[ii].iOffset = pPager->journalOff;
39067      }else{
39068        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
39069      }
39070      aNew[ii].iSubRec = pPager->nSubRec;
39071      aNew[ii].pInSavepoint = sqlite3BitvecCreate(nPage);
39072      if( !aNew[ii].pInSavepoint ){
39073        return SQLITE_NOMEM;
39074      }
39075      if( pagerUseWal(pPager) ){
39076        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
39077      }
39078      pPager->nSavepoint = ii+1;
39079    }
39080    assert( pPager->nSavepoint==nSavepoint );
39081    assertTruncateConstraint(pPager);
39082  }
39083
39084  return rc;
39085}
39086
39087/*
39088** This function is called to rollback or release (commit) a savepoint.
39089** The savepoint to release or rollback need not be the most recently
39090** created savepoint.
39091**
39092** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
39093** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
39094** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
39095** that have occurred since the specified savepoint was created.
39096**
39097** The savepoint to rollback or release is identified by parameter
39098** iSavepoint. A value of 0 means to operate on the outermost savepoint
39099** (the first created). A value of (Pager.nSavepoint-1) means operate
39100** on the most recently created savepoint. If iSavepoint is greater than
39101** (Pager.nSavepoint-1), then this function is a no-op.
39102**
39103** If a negative value is passed to this function, then the current
39104** transaction is rolled back. This is different to calling
39105** sqlite3PagerRollback() because this function does not terminate
39106** the transaction or unlock the database, it just restores the
39107** contents of the database to its original state.
39108**
39109** In any case, all savepoints with an index greater than iSavepoint
39110** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
39111** then savepoint iSavepoint is also destroyed.
39112**
39113** This function may return SQLITE_NOMEM if a memory allocation fails,
39114** or an IO error code if an IO error occurs while rolling back a
39115** savepoint. If no errors occur, SQLITE_OK is returned.
39116*/
39117SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
39118  int rc = SQLITE_OK;
39119
39120  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
39121  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
39122
39123  if( iSavepoint<pPager->nSavepoint ){
39124    int ii;            /* Iterator variable */
39125    int nNew;          /* Number of remaining savepoints after this op. */
39126
39127    /* Figure out how many savepoints will still be active after this
39128    ** operation. Store this value in nNew. Then free resources associated
39129    ** with any savepoints that are destroyed by this operation.
39130    */
39131    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
39132    for(ii=nNew; ii<pPager->nSavepoint; ii++){
39133      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39134    }
39135    pPager->nSavepoint = nNew;
39136
39137    /* If this is a release of the outermost savepoint, truncate
39138    ** the sub-journal to zero bytes in size. */
39139    if( op==SAVEPOINT_RELEASE ){
39140      if( nNew==0 && isOpen(pPager->sjfd) ){
39141        /* Only truncate if it is an in-memory sub-journal. */
39142        if( sqlite3IsMemJournal(pPager->sjfd) ){
39143          rc = sqlite3OsTruncate(pPager->sjfd, 0);
39144          assert( rc==SQLITE_OK );
39145        }
39146        pPager->nSubRec = 0;
39147      }
39148    }
39149    /* Else this is a rollback operation, playback the specified savepoint.
39150    ** If this is a temp-file, it is possible that the journal file has
39151    ** not yet been opened. In this case there have been no changes to
39152    ** the database file, so the playback operation can be skipped.
39153    */
39154    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
39155      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
39156      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
39157      assert(rc!=SQLITE_DONE);
39158    }
39159
39160  }
39161  return rc;
39162}
39163
39164/*
39165** Return the full pathname of the database file.
39166*/
39167SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
39168  return pPager->zFilename;
39169}
39170
39171/*
39172** Return the VFS structure for the pager.
39173*/
39174SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
39175  return pPager->pVfs;
39176}
39177
39178/*
39179** Return the file handle for the database file associated
39180** with the pager.  This might return NULL if the file has
39181** not yet been opened.
39182*/
39183SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
39184  return pPager->fd;
39185}
39186
39187/*
39188** Return the full pathname of the journal file.
39189*/
39190SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
39191  return pPager->zJournal;
39192}
39193
39194/*
39195** Return true if fsync() calls are disabled for this pager.  Return FALSE
39196** if fsync()s are executed normally.
39197*/
39198SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
39199  return pPager->noSync;
39200}
39201
39202#ifdef SQLITE_HAS_CODEC
39203/*
39204** Set or retrieve the codec for this pager
39205*/
39206static void sqlite3PagerSetCodec(
39207  Pager *pPager,
39208  void *(*xCodec)(void*,void*,Pgno,int),
39209  void (*xCodecSizeChng)(void*,int,int),
39210  void (*xCodecFree)(void*),
39211  void *pCodec
39212){
39213  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
39214  pPager->xCodec = pPager->memDb ? 0 : xCodec;
39215  pPager->xCodecSizeChng = xCodecSizeChng;
39216  pPager->xCodecFree = xCodecFree;
39217  pPager->pCodec = pCodec;
39218  pagerReportSize(pPager);
39219}
39220static void *sqlite3PagerGetCodec(Pager *pPager){
39221  return pPager->pCodec;
39222}
39223#endif
39224
39225#ifndef SQLITE_OMIT_AUTOVACUUM
39226/*
39227** Move the page pPg to location pgno in the file.
39228**
39229** There must be no references to the page previously located at
39230** pgno (which we call pPgOld) though that page is allowed to be
39231** in cache.  If the page previously located at pgno is not already
39232** in the rollback journal, it is not put there by by this routine.
39233**
39234** References to the page pPg remain valid. Updating any
39235** meta-data associated with pPg (i.e. data stored in the nExtra bytes
39236** allocated along with the page) is the responsibility of the caller.
39237**
39238** A transaction must be active when this routine is called. It used to be
39239** required that a statement transaction was not active, but this restriction
39240** has been removed (CREATE INDEX needs to move a page when a statement
39241** transaction is active).
39242**
39243** If the fourth argument, isCommit, is non-zero, then this page is being
39244** moved as part of a database reorganization just before the transaction
39245** is being committed. In this case, it is guaranteed that the database page
39246** pPg refers to will not be written to again within this transaction.
39247**
39248** This function may return SQLITE_NOMEM or an IO error code if an error
39249** occurs. Otherwise, it returns SQLITE_OK.
39250*/
39251SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
39252  PgHdr *pPgOld;               /* The page being overwritten. */
39253  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
39254  int rc;                      /* Return code */
39255  Pgno origPgno;               /* The original page number */
39256
39257  assert( pPg->nRef>0 );
39258
39259  /* In order to be able to rollback, an in-memory database must journal
39260  ** the page we are moving from.
39261  */
39262  if( MEMDB ){
39263    rc = sqlite3PagerWrite(pPg);
39264    if( rc ) return rc;
39265  }
39266
39267  /* If the page being moved is dirty and has not been saved by the latest
39268  ** savepoint, then save the current contents of the page into the
39269  ** sub-journal now. This is required to handle the following scenario:
39270  **
39271  **   BEGIN;
39272  **     <journal page X, then modify it in memory>
39273  **     SAVEPOINT one;
39274  **       <Move page X to location Y>
39275  **     ROLLBACK TO one;
39276  **
39277  ** If page X were not written to the sub-journal here, it would not
39278  ** be possible to restore its contents when the "ROLLBACK TO one"
39279  ** statement were is processed.
39280  **
39281  ** subjournalPage() may need to allocate space to store pPg->pgno into
39282  ** one or more savepoint bitvecs. This is the reason this function
39283  ** may return SQLITE_NOMEM.
39284  */
39285  if( pPg->flags&PGHDR_DIRTY
39286   && subjRequiresPage(pPg)
39287   && SQLITE_OK!=(rc = subjournalPage(pPg))
39288  ){
39289    return rc;
39290  }
39291
39292  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
39293      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
39294  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
39295
39296  /* If the journal needs to be sync()ed before page pPg->pgno can
39297  ** be written to, store pPg->pgno in local variable needSyncPgno.
39298  **
39299  ** If the isCommit flag is set, there is no need to remember that
39300  ** the journal needs to be sync()ed before database page pPg->pgno
39301  ** can be written to. The caller has already promised not to write to it.
39302  */
39303  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
39304    needSyncPgno = pPg->pgno;
39305    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
39306    assert( pPg->flags&PGHDR_DIRTY );
39307    assert( pPager->needSync );
39308  }
39309
39310  /* If the cache contains a page with page-number pgno, remove it
39311  ** from its hash chain. Also, if the PgHdr.needSync was set for
39312  ** page pgno before the 'move' operation, it needs to be retained
39313  ** for the page moved there.
39314  */
39315  pPg->flags &= ~PGHDR_NEED_SYNC;
39316  pPgOld = pager_lookup(pPager, pgno);
39317  assert( !pPgOld || pPgOld->nRef==1 );
39318  if( pPgOld ){
39319    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
39320    if( MEMDB ){
39321      /* Do not discard pages from an in-memory database since we might
39322      ** need to rollback later.  Just move the page out of the way. */
39323      assert( pPager->dbSizeValid );
39324      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
39325    }else{
39326      sqlite3PcacheDrop(pPgOld);
39327    }
39328  }
39329
39330  origPgno = pPg->pgno;
39331  sqlite3PcacheMove(pPg, pgno);
39332  sqlite3PcacheMakeDirty(pPg);
39333  pPager->dbModified = 1;
39334
39335  if( needSyncPgno ){
39336    /* If needSyncPgno is non-zero, then the journal file needs to be
39337    ** sync()ed before any data is written to database file page needSyncPgno.
39338    ** Currently, no such page exists in the page-cache and the
39339    ** "is journaled" bitvec flag has been set. This needs to be remedied by
39340    ** loading the page into the pager-cache and setting the PgHdr.needSync
39341    ** flag.
39342    **
39343    ** If the attempt to load the page into the page-cache fails, (due
39344    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
39345    ** array. Otherwise, if the page is loaded and written again in
39346    ** this transaction, it may be written to the database file before
39347    ** it is synced into the journal file. This way, it may end up in
39348    ** the journal file twice, but that is not a problem.
39349    **
39350    ** The sqlite3PagerGet() call may cause the journal to sync. So make
39351    ** sure the Pager.needSync flag is set too.
39352    */
39353    PgHdr *pPgHdr;
39354    assert( pPager->needSync );
39355    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
39356    if( rc!=SQLITE_OK ){
39357      if( needSyncPgno<=pPager->dbOrigSize ){
39358        assert( pPager->pTmpSpace!=0 );
39359        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
39360      }
39361      return rc;
39362    }
39363    pPager->needSync = 1;
39364    assert( pPager->noSync==0 && !MEMDB );
39365    pPgHdr->flags |= PGHDR_NEED_SYNC;
39366    sqlite3PcacheMakeDirty(pPgHdr);
39367    sqlite3PagerUnref(pPgHdr);
39368  }
39369
39370  /*
39371  ** For an in-memory database, make sure the original page continues
39372  ** to exist, in case the transaction needs to roll back.  Use pPgOld
39373  ** as the original page since it has already been allocated.
39374  */
39375  if( MEMDB ){
39376    sqlite3PcacheMove(pPgOld, origPgno);
39377    sqlite3PagerUnref(pPgOld);
39378  }
39379
39380  return SQLITE_OK;
39381}
39382#endif
39383
39384/*
39385** Return a pointer to the data for the specified page.
39386*/
39387SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
39388  assert( pPg->nRef>0 || pPg->pPager->memDb );
39389  return pPg->pData;
39390}
39391
39392/*
39393** Return a pointer to the Pager.nExtra bytes of "extra" space
39394** allocated along with the specified page.
39395*/
39396SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
39397  return pPg->pExtra;
39398}
39399
39400/*
39401** Get/set the locking-mode for this pager. Parameter eMode must be one
39402** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
39403** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
39404** the locking-mode is set to the value specified.
39405**
39406** The returned value is either PAGER_LOCKINGMODE_NORMAL or
39407** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
39408** locking-mode.
39409*/
39410SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
39411  assert( eMode==PAGER_LOCKINGMODE_QUERY
39412            || eMode==PAGER_LOCKINGMODE_NORMAL
39413            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
39414  assert( PAGER_LOCKINGMODE_QUERY<0 );
39415  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
39416  if( eMode>=0 && !pPager->tempFile ){
39417    pPager->exclusiveMode = (u8)eMode;
39418  }
39419  return (int)pPager->exclusiveMode;
39420}
39421
39422/*
39423** Set the journal-mode for this pager. Parameter eMode must be one of:
39424**
39425**    PAGER_JOURNALMODE_DELETE
39426**    PAGER_JOURNALMODE_TRUNCATE
39427**    PAGER_JOURNALMODE_PERSIST
39428**    PAGER_JOURNALMODE_OFF
39429**    PAGER_JOURNALMODE_MEMORY
39430**    PAGER_JOURNALMODE_WAL
39431**
39432** The journalmode is set to the value specified if the change is allowed.
39433** The change may be disallowed for the following reasons:
39434**
39435**   *  An in-memory database can only have its journal_mode set to _OFF
39436**      or _MEMORY.
39437**
39438**   *  Temporary databases cannot have _WAL journalmode.
39439**
39440** The returned indicate the current (possibly updated) journal-mode.
39441*/
39442SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
39443  u8 eOld = pPager->journalMode;    /* Prior journalmode */
39444
39445  /* The eMode parameter is always valid */
39446  assert(      eMode==PAGER_JOURNALMODE_DELETE
39447            || eMode==PAGER_JOURNALMODE_TRUNCATE
39448            || eMode==PAGER_JOURNALMODE_PERSIST
39449            || eMode==PAGER_JOURNALMODE_OFF
39450            || eMode==PAGER_JOURNALMODE_WAL
39451            || eMode==PAGER_JOURNALMODE_MEMORY );
39452
39453  /* Do not allow the journalmode of a TEMP database to be changed to WAL
39454  */
39455  if( pPager->tempFile && eMode==PAGER_JOURNALMODE_WAL ){
39456    assert( eOld!=PAGER_JOURNALMODE_WAL );
39457    eMode = eOld;
39458  }
39459
39460  /* Do allow the journalmode of an in-memory database to be set to
39461  ** anything other than MEMORY or OFF
39462  */
39463  if( MEMDB ){
39464    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
39465    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
39466      eMode = eOld;
39467    }
39468  }
39469
39470  if( eMode!=eOld ){
39471    /* When changing between rollback modes, close the journal file prior
39472    ** to the change.  But when changing from a rollback mode to WAL, keep
39473    ** the journal open since there is a rollback-style transaction in play
39474    ** used to convert the version numbers in the btree header.
39475    */
39476    if( isOpen(pPager->jfd) && eMode!=PAGER_JOURNALMODE_WAL ){
39477      sqlite3OsClose(pPager->jfd);
39478    }
39479
39480    /* Change the journal mode. */
39481    pPager->journalMode = (u8)eMode;
39482
39483    /* When transistioning from TRUNCATE or PERSIST to any other journal
39484    ** mode except WAL (and we are not in locking_mode=EXCLUSIVE) then
39485    ** delete the journal file.
39486    */
39487    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39488    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
39489    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
39490    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
39491    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
39492    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
39493
39494    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
39495    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
39496
39497      /* In this case we would like to delete the journal file. If it is
39498      ** not possible, then that is not a problem. Deleting the journal file
39499      ** here is an optimization only.
39500      **
39501      ** Before deleting the journal file, obtain a RESERVED lock on the
39502      ** database file. This ensures that the journal file is not deleted
39503      ** while it is in use by some other client.
39504      */
39505      int rc = SQLITE_OK;
39506      int state = pPager->state;
39507      if( state<PAGER_SHARED ){
39508        rc = sqlite3PagerSharedLock(pPager);
39509      }
39510      if( pPager->state==PAGER_SHARED ){
39511        assert( rc==SQLITE_OK );
39512        rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
39513      }
39514      if( rc==SQLITE_OK ){
39515        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39516      }
39517      if( rc==SQLITE_OK && state==PAGER_SHARED ){
39518        sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
39519      }else if( state==PAGER_UNLOCK ){
39520        pager_unlock(pPager);
39521      }
39522      assert( state==pPager->state );
39523    }
39524  }
39525
39526  /* Return the new journal mode */
39527  return (int)pPager->journalMode;
39528}
39529
39530/*
39531** Return the current journal mode.
39532*/
39533SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
39534  return (int)pPager->journalMode;
39535}
39536
39537/*
39538** Return TRUE if the pager is in a state where it is OK to change the
39539** journalmode.  Journalmode changes can only happen when the database
39540** is unmodified.
39541*/
39542SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
39543  if( pPager->dbModified ) return 0;
39544  if( isOpen(pPager->jfd) && pPager->journalOff>0 ) return 0;
39545  return 1;
39546}
39547
39548/*
39549** Get/set the size-limit used for persistent journal files.
39550**
39551** Setting the size limit to -1 means no limit is enforced.
39552** An attempt to set a limit smaller than -1 is a no-op.
39553*/
39554SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
39555  if( iLimit>=-1 ){
39556    pPager->journalSizeLimit = iLimit;
39557  }
39558  return pPager->journalSizeLimit;
39559}
39560
39561/*
39562** Return a pointer to the pPager->pBackup variable. The backup module
39563** in backup.c maintains the content of this variable. This module
39564** uses it opaquely as an argument to sqlite3BackupRestart() and
39565** sqlite3BackupUpdate() only.
39566*/
39567SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
39568  return &pPager->pBackup;
39569}
39570
39571#ifndef SQLITE_OMIT_WAL
39572/*
39573** This function is called when the user invokes "PRAGMA checkpoint".
39574*/
39575SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
39576  int rc = SQLITE_OK;
39577  if( pPager->pWal ){
39578    u8 *zBuf = (u8 *)pPager->pTmpSpace;
39579    rc = sqlite3WalCheckpoint(pPager->pWal,
39580        (pPager->noSync ? 0 : pPager->sync_flags),
39581        pPager->pageSize, zBuf
39582    );
39583  }
39584  return rc;
39585}
39586
39587SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
39588  return sqlite3WalCallback(pPager->pWal);
39589}
39590
39591/*
39592** Return true if the underlying VFS for the given pager supports the
39593** primitives necessary for write-ahead logging.
39594*/
39595SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
39596  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
39597  return pMethods->iVersion>=2 && pMethods->xShmOpen!=0;
39598}
39599
39600/*
39601** Open a connection to the write-ahead log file for pager pPager. If
39602** the log connection is already open, this function is a no-op.
39603**
39604** The caller must be holding a SHARED lock on the database file to call
39605** this function.
39606*/
39607SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen){
39608  int rc = SQLITE_OK;             /* Return code */
39609
39610  assert( pPager->state>=PAGER_SHARED );
39611  if( !pPager->pWal ){
39612    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
39613
39614    /* Open the connection to the log file. If this operation fails,
39615    ** (e.g. due to malloc() failure), unlock the database file and
39616    ** return an error code.
39617    */
39618    rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
39619                        pPager->zFilename, &pPager->pWal);
39620    if( rc==SQLITE_OK ){
39621      pPager->journalMode = PAGER_JOURNALMODE_WAL;
39622    }
39623  }else{
39624    *pisOpen = 1;
39625  }
39626
39627  return rc;
39628}
39629
39630/*
39631** This function is called to close the connection to the log file prior
39632** to switching from WAL to rollback mode.
39633**
39634** Before closing the log file, this function attempts to take an
39635** EXCLUSIVE lock on the database file. If this cannot be obtained, an
39636** error (SQLITE_BUSY) is returned and the log connection is not closed.
39637** If successful, the EXCLUSIVE lock is not released before returning.
39638*/
39639SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
39640  int rc = SQLITE_OK;
39641
39642  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
39643
39644  /* If the log file is not already open, but does exist in the file-system,
39645  ** it may need to be checkpointed before the connection can switch to
39646  ** rollback mode. Open it now so this can happen.
39647  */
39648  if( !pPager->pWal ){
39649    int logexists = 0;
39650    rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_SHARED);
39651    if( rc==SQLITE_OK ){
39652      rc = pagerHasWAL(pPager, &logexists);
39653    }
39654    if( rc==SQLITE_OK && logexists ){
39655      rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
39656                          pPager->zFilename, &pPager->pWal);
39657    }
39658  }
39659
39660  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
39661  ** the database file, the log and log-summary files will be deleted.
39662  */
39663  if( rc==SQLITE_OK && pPager->pWal ){
39664    rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_EXCLUSIVE);
39665    if( rc==SQLITE_OK ){
39666      rc = sqlite3WalClose(pPager->pWal,
39667                           (pPager->noSync ? 0 : pPager->sync_flags),
39668        pPager->pageSize, (u8*)pPager->pTmpSpace
39669      );
39670      pPager->pWal = 0;
39671    }else{
39672      /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
39673      ** that we did get back to SHARED. */
39674      sqlite3OsUnlock(pPager->fd, SQLITE_LOCK_SHARED);
39675    }
39676  }
39677  return rc;
39678}
39679
39680#ifdef SQLITE_HAS_CODEC
39681/*
39682** This function is called by the wal module when writing page content
39683** into the log file.
39684**
39685** This function returns a pointer to a buffer containing the encrypted
39686** page content. If a malloc fails, this function may return NULL.
39687*/
39688SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
39689  void *aData = 0;
39690  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
39691  return aData;
39692}
39693#endif /* SQLITE_HAS_CODEC */
39694
39695#endif /* !SQLITE_OMIT_WAL */
39696
39697#endif /* SQLITE_OMIT_DISKIO */
39698
39699/************** End of pager.c ***********************************************/
39700/************** Begin file wal.c *********************************************/
39701/*
39702** 2010 February 1
39703**
39704** The author disclaims copyright to this source code.  In place of
39705** a legal notice, here is a blessing:
39706**
39707**    May you do good and not evil.
39708**    May you find forgiveness for yourself and forgive others.
39709**    May you share freely, never taking more than you give.
39710**
39711*************************************************************************
39712**
39713** This file contains the implementation of a write-ahead log (WAL) used in
39714** "journal_mode=WAL" mode.
39715**
39716** WRITE-AHEAD LOG (WAL) FILE FORMAT
39717**
39718** A WAL file consists of a header followed by zero or more "frames".
39719** Each frame records the revised content of a single page from the
39720** database file.  All changes to the database are recorded by writing
39721** frames into the WAL.  Transactions commit when a frame is written that
39722** contains a commit marker.  A single WAL can and usually does record
39723** multiple transactions.  Periodically, the content of the WAL is
39724** transferred back into the database file in an operation called a
39725** "checkpoint".
39726**
39727** A single WAL file can be used multiple times.  In other words, the
39728** WAL can fill up with frames and then be checkpointed and then new
39729** frames can overwrite the old ones.  A WAL always grows from beginning
39730** toward the end.  Checksums and counters attached to each frame are
39731** used to determine which frames within the WAL are valid and which
39732** are leftovers from prior checkpoints.
39733**
39734** The WAL header is 32 bytes in size and consists of the following eight
39735** big-endian 32-bit unsigned integer values:
39736**
39737**     0: Magic number.  0x377f0682 or 0x377f0683
39738**     4: File format version.  Currently 3007000
39739**     8: Database page size.  Example: 1024
39740**    12: Checkpoint sequence number
39741**    16: Salt-1, random integer incremented with each checkpoint
39742**    20: Salt-2, a different random integer changing with each ckpt
39743**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
39744**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
39745**
39746** Immediately following the wal-header are zero or more frames. Each
39747** frame consists of a 24-byte frame-header followed by a <page-size> bytes
39748** of page data. The frame-header is six big-endian 32-bit unsigned
39749** integer values, as follows:
39750**
39751**     0: Page number.
39752**     4: For commit records, the size of the database image in pages
39753**        after the commit. For all other records, zero.
39754**     8: Salt-1 (copied from the header)
39755**    12: Salt-2 (copied from the header)
39756**    16: Checksum-1.
39757**    20: Checksum-2.
39758**
39759** A frame is considered valid if and only if the following conditions are
39760** true:
39761**
39762**    (1) The salt-1 and salt-2 values in the frame-header match
39763**        salt values in the wal-header
39764**
39765**    (2) The checksum values in the final 8 bytes of the frame-header
39766**        exactly match the checksum computed consecutively on the
39767**        WAL header and the first 8 bytes and the content of all frames
39768**        up to and including the current frame.
39769**
39770** The checksum is computed using 32-bit big-endian integers if the
39771** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
39772** is computed using little-endian if the magic number is 0x377f0682.
39773** The checksum values are always stored in the frame header in a
39774** big-endian format regardless of which byte order is used to compute
39775** the checksum.  The checksum is computed by interpreting the input as
39776** an even number of unsigned 32-bit integers: x[0] through x[N].  The
39777** algorithm used for the checksum is as follows:
39778**
39779**   for i from 0 to n-1 step 2:
39780**     s0 += x[i] + s1;
39781**     s1 += x[i+1] + s0;
39782**   endfor
39783**
39784** Note that s0 and s1 are both weighted checksums using fibonacci weights
39785** in reverse order (the largest fibonacci weight occurs on the first element
39786** of the sequence being summed.)  The s1 value spans all 32-bit
39787** terms of the sequence whereas s0 omits the final term.
39788**
39789** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
39790** WAL is transferred into the database, then the database is VFS.xSync-ed.
39791** The VFS.xSync operations serve as write barriers - all writes launched
39792** before the xSync must complete before any write that launches after the
39793** xSync begins.
39794**
39795** After each checkpoint, the salt-1 value is incremented and the salt-2
39796** value is randomized.  This prevents old and new frames in the WAL from
39797** being considered valid at the same time and being checkpointing together
39798** following a crash.
39799**
39800** READER ALGORITHM
39801**
39802** To read a page from the database (call it page number P), a reader
39803** first checks the WAL to see if it contains page P.  If so, then the
39804** last valid instance of page P that is a followed by a commit frame
39805** or is a commit frame itself becomes the value read.  If the WAL
39806** contains no copies of page P that are valid and which are a commit
39807** frame or are followed by a commit frame, then page P is read from
39808** the database file.
39809**
39810** To start a read transaction, the reader records the index of the last
39811** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
39812** for all subsequent read operations.  New transactions can be appended
39813** to the WAL, but as long as the reader uses its original mxFrame value
39814** and ignores the newly appended content, it will see a consistent snapshot
39815** of the database from a single point in time.  This technique allows
39816** multiple concurrent readers to view different versions of the database
39817** content simultaneously.
39818**
39819** The reader algorithm in the previous paragraphs works correctly, but
39820** because frames for page P can appear anywhere within the WAL, the
39821** reader has to scan the entire WAL looking for page P frames.  If the
39822** WAL is large (multiple megabytes is typical) that scan can be slow,
39823** and read performance suffers.  To overcome this problem, a separate
39824** data structure called the wal-index is maintained to expedite the
39825** search for frames of a particular page.
39826**
39827** WAL-INDEX FORMAT
39828**
39829** Conceptually, the wal-index is shared memory, though VFS implementations
39830** might choose to implement the wal-index using a mmapped file.  Because
39831** the wal-index is shared memory, SQLite does not support journal_mode=WAL
39832** on a network filesystem.  All users of the database must be able to
39833** share memory.
39834**
39835** The wal-index is transient.  After a crash, the wal-index can (and should
39836** be) reconstructed from the original WAL file.  In fact, the VFS is required
39837** to either truncate or zero the header of the wal-index when the last
39838** connection to it closes.  Because the wal-index is transient, it can
39839** use an architecture-specific format; it does not have to be cross-platform.
39840** Hence, unlike the database and WAL file formats which store all values
39841** as big endian, the wal-index can store multi-byte values in the native
39842** byte order of the host computer.
39843**
39844** The purpose of the wal-index is to answer this question quickly:  Given
39845** a page number P, return the index of the last frame for page P in the WAL,
39846** or return NULL if there are no frames for page P in the WAL.
39847**
39848** The wal-index consists of a header region, followed by an one or
39849** more index blocks.
39850**
39851** The wal-index header contains the total number of frames within the WAL
39852** in the the mxFrame field.
39853**
39854** Each index block except for the first contains information on
39855** HASHTABLE_NPAGE frames. The first index block contains information on
39856** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
39857** HASHTABLE_NPAGE are selected so that together the wal-index header and
39858** first index block are the same size as all other index blocks in the
39859** wal-index.
39860**
39861** Each index block contains two sections, a page-mapping that contains the
39862** database page number associated with each wal frame, and a hash-table
39863** that allows readers to query an index block for a specific page number.
39864** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
39865** for the first index block) 32-bit page numbers. The first entry in the
39866** first index-block contains the database page number corresponding to the
39867** first frame in the WAL file. The first entry in the second index block
39868** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
39869** the log, and so on.
39870**
39871** The last index block in a wal-index usually contains less than the full
39872** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
39873** depending on the contents of the WAL file. This does not change the
39874** allocated size of the page-mapping array - the page-mapping array merely
39875** contains unused entries.
39876**
39877** Even without using the hash table, the last frame for page P
39878** can be found by scanning the page-mapping sections of each index block
39879** starting with the last index block and moving toward the first, and
39880** within each index block, starting at the end and moving toward the
39881** beginning.  The first entry that equals P corresponds to the frame
39882** holding the content for that page.
39883**
39884** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
39885** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
39886** hash table for each page number in the mapping section, so the hash
39887** table is never more than half full.  The expected number of collisions
39888** prior to finding a match is 1.  Each entry of the hash table is an
39889** 1-based index of an entry in the mapping section of the same
39890** index block.   Let K be the 1-based index of the largest entry in
39891** the mapping section.  (For index blocks other than the last, K will
39892** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
39893** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
39894** contain a value of 0.
39895**
39896** To look for page P in the hash table, first compute a hash iKey on
39897** P as follows:
39898**
39899**      iKey = (P * 383) % HASHTABLE_NSLOT
39900**
39901** Then start scanning entries of the hash table, starting with iKey
39902** (wrapping around to the beginning when the end of the hash table is
39903** reached) until an unused hash slot is found. Let the first unused slot
39904** be at index iUnused.  (iUnused might be less than iKey if there was
39905** wrap-around.) Because the hash table is never more than half full,
39906** the search is guaranteed to eventually hit an unused entry.  Let
39907** iMax be the value between iKey and iUnused, closest to iUnused,
39908** where aHash[iMax]==P.  If there is no iMax entry (if there exists
39909** no hash slot such that aHash[i]==p) then page P is not in the
39910** current index block.  Otherwise the iMax-th mapping entry of the
39911** current index block corresponds to the last entry that references
39912** page P.
39913**
39914** A hash search begins with the last index block and moves toward the
39915** first index block, looking for entries corresponding to page P.  On
39916** average, only two or three slots in each index block need to be
39917** examined in order to either find the last entry for page P, or to
39918** establish that no such entry exists in the block.  Each index block
39919** holds over 4000 entries.  So two or three index blocks are sufficient
39920** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
39921** comparisons (on average) suffice to either locate a frame in the
39922** WAL or to establish that the frame does not exist in the WAL.  This
39923** is much faster than scanning the entire 10MB WAL.
39924**
39925** Note that entries are added in order of increasing K.  Hence, one
39926** reader might be using some value K0 and a second reader that started
39927** at a later time (after additional transactions were added to the WAL
39928** and to the wal-index) might be using a different value K1, where K1>K0.
39929** Both readers can use the same hash table and mapping section to get
39930** the correct result.  There may be entries in the hash table with
39931** K>K0 but to the first reader, those entries will appear to be unused
39932** slots in the hash table and so the first reader will get an answer as
39933** if no values greater than K0 had ever been inserted into the hash table
39934** in the first place - which is what reader one wants.  Meanwhile, the
39935** second reader using K1 will see additional values that were inserted
39936** later, which is exactly what reader two wants.
39937**
39938** When a rollback occurs, the value of K is decreased. Hash table entries
39939** that correspond to frames greater than the new K value are removed
39940** from the hash table at this point.
39941*/
39942#ifndef SQLITE_OMIT_WAL
39943
39944
39945/*
39946** Trace output macros
39947*/
39948#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
39949SQLITE_PRIVATE int sqlite3WalTrace = 0;
39950# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
39951#else
39952# define WALTRACE(X)
39953#endif
39954
39955/*
39956** The maximum (and only) versions of the wal and wal-index formats
39957** that may be interpreted by this version of SQLite.
39958**
39959** If a client begins recovering a WAL file and finds that (a) the checksum
39960** values in the wal-header are correct and (b) the version field is not
39961** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
39962**
39963** Similarly, if a client successfully reads a wal-index header (i.e. the
39964** checksum test is successful) and finds that the version field is not
39965** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
39966** returns SQLITE_CANTOPEN.
39967*/
39968#define WAL_MAX_VERSION      3007000
39969#define WALINDEX_MAX_VERSION 3007000
39970
39971/*
39972** Indices of various locking bytes.   WAL_NREADER is the number
39973** of available reader locks and should be at least 3.
39974*/
39975#define WAL_WRITE_LOCK         0
39976#define WAL_ALL_BUT_WRITE      1
39977#define WAL_CKPT_LOCK          1
39978#define WAL_RECOVER_LOCK       2
39979#define WAL_READ_LOCK(I)       (3+(I))
39980#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
39981
39982
39983/* Object declarations */
39984typedef struct WalIndexHdr WalIndexHdr;
39985typedef struct WalIterator WalIterator;
39986typedef struct WalCkptInfo WalCkptInfo;
39987
39988
39989/*
39990** The following object holds a copy of the wal-index header content.
39991**
39992** The actual header in the wal-index consists of two copies of this
39993** object.
39994*/
39995struct WalIndexHdr {
39996  u32 iVersion;                   /* Wal-index version */
39997  u32 unused;                     /* Unused (padding) field */
39998  u32 iChange;                    /* Counter incremented each transaction */
39999  u8 isInit;                      /* 1 when initialized */
40000  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
40001  u16 szPage;                     /* Database page size in bytes */
40002  u32 mxFrame;                    /* Index of last valid frame in the WAL */
40003  u32 nPage;                      /* Size of database in pages */
40004  u32 aFrameCksum[2];             /* Checksum of last frame in log */
40005  u32 aSalt[2];                   /* Two salt values copied from WAL header */
40006  u32 aCksum[2];                  /* Checksum over all prior fields */
40007};
40008
40009/*
40010** A copy of the following object occurs in the wal-index immediately
40011** following the second copy of the WalIndexHdr.  This object stores
40012** information used by checkpoint.
40013**
40014** nBackfill is the number of frames in the WAL that have been written
40015** back into the database. (We call the act of moving content from WAL to
40016** database "backfilling".)  The nBackfill number is never greater than
40017** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
40018** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
40019** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
40020** mxFrame back to zero when the WAL is reset.
40021**
40022** There is one entry in aReadMark[] for each reader lock.  If a reader
40023** holds read-lock K, then the value in aReadMark[K] is no greater than
40024** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
40025** for any aReadMark[] means that entry is unused.  aReadMark[0] is
40026** a special case; its value is never used and it exists as a place-holder
40027** to avoid having to offset aReadMark[] indexs by one.  Readers holding
40028** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
40029** directly from the database.
40030**
40031** The value of aReadMark[K] may only be changed by a thread that
40032** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
40033** aReadMark[K] cannot changed while there is a reader is using that mark
40034** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
40035**
40036** The checkpointer may only transfer frames from WAL to database where
40037** the frame numbers are less than or equal to every aReadMark[] that is
40038** in use (that is, every aReadMark[j] for which there is a corresponding
40039** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
40040** largest value and will increase an unused aReadMark[] to mxFrame if there
40041** is not already an aReadMark[] equal to mxFrame.  The exception to the
40042** previous sentence is when nBackfill equals mxFrame (meaning that everything
40043** in the WAL has been backfilled into the database) then new readers
40044** will choose aReadMark[0] which has value 0 and hence such reader will
40045** get all their all content directly from the database file and ignore
40046** the WAL.
40047**
40048** Writers normally append new frames to the end of the WAL.  However,
40049** if nBackfill equals mxFrame (meaning that all WAL content has been
40050** written back into the database) and if no readers are using the WAL
40051** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
40052** the writer will first "reset" the WAL back to the beginning and start
40053** writing new content beginning at frame 1.
40054**
40055** We assume that 32-bit loads are atomic and so no locks are needed in
40056** order to read from any aReadMark[] entries.
40057*/
40058struct WalCkptInfo {
40059  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
40060  u32 aReadMark[WAL_NREADER];     /* Reader marks */
40061};
40062#define READMARK_NOT_USED  0xffffffff
40063
40064
40065/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
40066** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
40067** only support mandatory file-locks, we do not read or write data
40068** from the region of the file on which locks are applied.
40069*/
40070#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
40071#define WALINDEX_LOCK_RESERVED 16
40072#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
40073
40074/* Size of header before each frame in wal */
40075#define WAL_FRAME_HDRSIZE 24
40076
40077/* Size of write ahead log header, including checksum. */
40078/* #define WAL_HDRSIZE 24 */
40079#define WAL_HDRSIZE 32
40080
40081/* WAL magic value. Either this value, or the same value with the least
40082** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
40083** big-endian format in the first 4 bytes of a WAL file.
40084**
40085** If the LSB is set, then the checksums for each frame within the WAL
40086** file are calculated by treating all data as an array of 32-bit
40087** big-endian words. Otherwise, they are calculated by interpreting
40088** all data as 32-bit little-endian words.
40089*/
40090#define WAL_MAGIC 0x377f0682
40091
40092/*
40093** Return the offset of frame iFrame in the write-ahead log file,
40094** assuming a database page size of szPage bytes. The offset returned
40095** is to the start of the write-ahead log frame-header.
40096*/
40097#define walFrameOffset(iFrame, szPage) (                               \
40098  WAL_HDRSIZE + ((iFrame)-1)*((szPage)+WAL_FRAME_HDRSIZE)        \
40099)
40100
40101/*
40102** An open write-ahead log file is represented by an instance of the
40103** following object.
40104*/
40105struct Wal {
40106  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
40107  sqlite3_file *pDbFd;       /* File handle for the database file */
40108  sqlite3_file *pWalFd;      /* File handle for WAL file */
40109  u32 iCallback;             /* Value to pass to log callback (or 0) */
40110  int nWiData;               /* Size of array apWiData */
40111  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
40112  u16 szPage;                /* Database page size */
40113  i16 readLock;              /* Which read lock is being held.  -1 for none */
40114  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
40115  u8 isWIndexOpen;           /* True if ShmOpen() called on pDbFd */
40116  u8 writeLock;              /* True if in a write transaction */
40117  u8 ckptLock;               /* True if holding a checkpoint lock */
40118  WalIndexHdr hdr;           /* Wal-index header for current transaction */
40119  char *zWalName;            /* Name of WAL file */
40120  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
40121#ifdef SQLITE_DEBUG
40122  u8 lockError;              /* True if a locking error has occurred */
40123#endif
40124};
40125
40126/*
40127** Each page of the wal-index mapping contains a hash-table made up of
40128** an array of HASHTABLE_NSLOT elements of the following type.
40129*/
40130typedef u16 ht_slot;
40131
40132/*
40133** This structure is used to implement an iterator that loops through
40134** all frames in the WAL in database page order. Where two or more frames
40135** correspond to the same database page, the iterator visits only the
40136** frame most recently written to the WAL (in other words, the frame with
40137** the largest index).
40138**
40139** The internals of this structure are only accessed by:
40140**
40141**   walIteratorInit() - Create a new iterator,
40142**   walIteratorNext() - Step an iterator,
40143**   walIteratorFree() - Free an iterator.
40144**
40145** This functionality is used by the checkpoint code (see walCheckpoint()).
40146*/
40147struct WalIterator {
40148  int iPrior;                     /* Last result returned from the iterator */
40149  int nSegment;                   /* Size of the aSegment[] array */
40150  struct WalSegment {
40151    int iNext;                    /* Next slot in aIndex[] not yet returned */
40152    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
40153    u32 *aPgno;                   /* Array of page numbers. */
40154    int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
40155    int iZero;                    /* Frame number associated with aPgno[0] */
40156  } aSegment[1];                  /* One for every 32KB page in the WAL */
40157};
40158
40159/*
40160** Define the parameters of the hash tables in the wal-index file. There
40161** is a hash-table following every HASHTABLE_NPAGE page numbers in the
40162** wal-index.
40163**
40164** Changing any of these constants will alter the wal-index format and
40165** create incompatibilities.
40166*/
40167#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
40168#define HASHTABLE_HASH_1     383                  /* Should be prime */
40169#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
40170
40171/*
40172** The block of page numbers associated with the first hash-table in a
40173** wal-index is smaller than usual. This is so that there is a complete
40174** hash-table on each aligned 32KB page of the wal-index.
40175*/
40176#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
40177
40178/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
40179#define WALINDEX_PGSZ   (                                         \
40180    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
40181)
40182
40183/*
40184** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
40185** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
40186** numbered from zero.
40187**
40188** If this call is successful, *ppPage is set to point to the wal-index
40189** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
40190** then an SQLite error code is returned and *ppPage is set to 0.
40191*/
40192static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
40193  int rc = SQLITE_OK;
40194
40195  /* Enlarge the pWal->apWiData[] array if required */
40196  if( pWal->nWiData<=iPage ){
40197    int nByte = sizeof(u32 *)*(iPage+1);
40198    volatile u32 **apNew;
40199    apNew = (volatile u32 **)sqlite3_realloc(pWal->apWiData, nByte);
40200    if( !apNew ){
40201      *ppPage = 0;
40202      return SQLITE_NOMEM;
40203    }
40204    memset(&apNew[pWal->nWiData], 0, sizeof(u32 *)*(iPage+1-pWal->nWiData));
40205    pWal->apWiData = apNew;
40206    pWal->nWiData = iPage+1;
40207  }
40208
40209  /* Request a pointer to the required page from the VFS */
40210  if( pWal->apWiData[iPage]==0 ){
40211    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
40212        pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
40213    );
40214  }
40215
40216  *ppPage = pWal->apWiData[iPage];
40217  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
40218  return rc;
40219}
40220
40221/*
40222** Return a pointer to the WalCkptInfo structure in the wal-index.
40223*/
40224static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
40225  assert( pWal->nWiData>0 && pWal->apWiData[0] );
40226  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
40227}
40228
40229/*
40230** Return a pointer to the WalIndexHdr structure in the wal-index.
40231*/
40232static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
40233  assert( pWal->nWiData>0 && pWal->apWiData[0] );
40234  return (volatile WalIndexHdr*)pWal->apWiData[0];
40235}
40236
40237/*
40238** The argument to this macro must be of type u32. On a little-endian
40239** architecture, it returns the u32 value that results from interpreting
40240** the 4 bytes as a big-endian value. On a big-endian architecture, it
40241** returns the value that would be produced by intepreting the 4 bytes
40242** of the input value as a little-endian integer.
40243*/
40244#define BYTESWAP32(x) ( \
40245    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
40246  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
40247)
40248
40249/*
40250** Generate or extend an 8 byte checksum based on the data in
40251** array aByte[] and the initial values of aIn[0] and aIn[1] (or
40252** initial values of 0 and 0 if aIn==NULL).
40253**
40254** The checksum is written back into aOut[] before returning.
40255**
40256** nByte must be a positive multiple of 8.
40257*/
40258static void walChecksumBytes(
40259  int nativeCksum, /* True for native byte-order, false for non-native */
40260  u8 *a,           /* Content to be checksummed */
40261  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
40262  const u32 *aIn,  /* Initial checksum value input */
40263  u32 *aOut        /* OUT: Final checksum value output */
40264){
40265  u32 s1, s2;
40266  u32 *aData = (u32 *)a;
40267  u32 *aEnd = (u32 *)&a[nByte];
40268
40269  if( aIn ){
40270    s1 = aIn[0];
40271    s2 = aIn[1];
40272  }else{
40273    s1 = s2 = 0;
40274  }
40275
40276  assert( nByte>=8 );
40277  assert( (nByte&0x00000007)==0 );
40278
40279  if( nativeCksum ){
40280    do {
40281      s1 += *aData++ + s2;
40282      s2 += *aData++ + s1;
40283    }while( aData<aEnd );
40284  }else{
40285    do {
40286      s1 += BYTESWAP32(aData[0]) + s2;
40287      s2 += BYTESWAP32(aData[1]) + s1;
40288      aData += 2;
40289    }while( aData<aEnd );
40290  }
40291
40292  aOut[0] = s1;
40293  aOut[1] = s2;
40294}
40295
40296/*
40297** Write the header information in pWal->hdr into the wal-index.
40298**
40299** The checksum on pWal->hdr is updated before it is written.
40300*/
40301static void walIndexWriteHdr(Wal *pWal){
40302  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
40303  const int nCksum = offsetof(WalIndexHdr, aCksum);
40304
40305  assert( pWal->writeLock );
40306  pWal->hdr.isInit = 1;
40307  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
40308  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
40309  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40310  sqlite3OsShmBarrier(pWal->pDbFd);
40311  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40312}
40313
40314/*
40315** This function encodes a single frame header and writes it to a buffer
40316** supplied by the caller. A frame-header is made up of a series of
40317** 4-byte big-endian integers, as follows:
40318**
40319**     0: Page number.
40320**     4: For commit records, the size of the database image in pages
40321**        after the commit. For all other records, zero.
40322**     8: Salt-1 (copied from the wal-header)
40323**    12: Salt-2 (copied from the wal-header)
40324**    16: Checksum-1.
40325**    20: Checksum-2.
40326*/
40327static void walEncodeFrame(
40328  Wal *pWal,                      /* The write-ahead log */
40329  u32 iPage,                      /* Database page number for frame */
40330  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
40331  u8 *aData,                      /* Pointer to page data */
40332  u8 *aFrame                      /* OUT: Write encoded frame here */
40333){
40334  int nativeCksum;                /* True for native byte-order checksums */
40335  u32 *aCksum = pWal->hdr.aFrameCksum;
40336  assert( WAL_FRAME_HDRSIZE==24 );
40337  sqlite3Put4byte(&aFrame[0], iPage);
40338  sqlite3Put4byte(&aFrame[4], nTruncate);
40339  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
40340
40341  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40342  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40343  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40344
40345  sqlite3Put4byte(&aFrame[16], aCksum[0]);
40346  sqlite3Put4byte(&aFrame[20], aCksum[1]);
40347}
40348
40349/*
40350** Check to see if the frame with header in aFrame[] and content
40351** in aData[] is valid.  If it is a valid frame, fill *piPage and
40352** *pnTruncate and return true.  Return if the frame is not valid.
40353*/
40354static int walDecodeFrame(
40355  Wal *pWal,                      /* The write-ahead log */
40356  u32 *piPage,                    /* OUT: Database page number for frame */
40357  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
40358  u8 *aData,                      /* Pointer to page data (for checksum) */
40359  u8 *aFrame                      /* Frame data */
40360){
40361  int nativeCksum;                /* True for native byte-order checksums */
40362  u32 *aCksum = pWal->hdr.aFrameCksum;
40363  u32 pgno;                       /* Page number of the frame */
40364  assert( WAL_FRAME_HDRSIZE==24 );
40365
40366  /* A frame is only valid if the salt values in the frame-header
40367  ** match the salt values in the wal-header.
40368  */
40369  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
40370    return 0;
40371  }
40372
40373  /* A frame is only valid if the page number is creater than zero.
40374  */
40375  pgno = sqlite3Get4byte(&aFrame[0]);
40376  if( pgno==0 ){
40377    return 0;
40378  }
40379
40380  /* A frame is only valid if a checksum of the first 16 bytes
40381  ** of the frame-header, and the frame-data matches
40382  ** the checksum in the last 8 bytes of the frame-header.
40383  */
40384  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40385  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40386  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40387  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
40388   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
40389  ){
40390    /* Checksum failed. */
40391    return 0;
40392  }
40393
40394  /* If we reach this point, the frame is valid.  Return the page number
40395  ** and the new database size.
40396  */
40397  *piPage = pgno;
40398  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
40399  return 1;
40400}
40401
40402
40403#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
40404/*
40405** Names of locks.  This routine is used to provide debugging output and is not
40406** a part of an ordinary build.
40407*/
40408static const char *walLockName(int lockIdx){
40409  if( lockIdx==WAL_WRITE_LOCK ){
40410    return "WRITE-LOCK";
40411  }else if( lockIdx==WAL_CKPT_LOCK ){
40412    return "CKPT-LOCK";
40413  }else if( lockIdx==WAL_RECOVER_LOCK ){
40414    return "RECOVER-LOCK";
40415  }else{
40416    static char zName[15];
40417    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
40418                     lockIdx-WAL_READ_LOCK(0));
40419    return zName;
40420  }
40421}
40422#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
40423
40424
40425/*
40426** Set or release locks on the WAL.  Locks are either shared or exclusive.
40427** A lock cannot be moved directly between shared and exclusive - it must go
40428** through the unlocked state first.
40429**
40430** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
40431*/
40432static int walLockShared(Wal *pWal, int lockIdx){
40433  int rc;
40434  if( pWal->exclusiveMode ) return SQLITE_OK;
40435  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40436                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
40437  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
40438            walLockName(lockIdx), rc ? "failed" : "ok"));
40439  VVA_ONLY( pWal->lockError = (rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40440  return rc;
40441}
40442static void walUnlockShared(Wal *pWal, int lockIdx){
40443  if( pWal->exclusiveMode ) return;
40444  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40445                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
40446  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
40447}
40448static int walLockExclusive(Wal *pWal, int lockIdx, int n){
40449  int rc;
40450  if( pWal->exclusiveMode ) return SQLITE_OK;
40451  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40452                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
40453  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
40454            walLockName(lockIdx), n, rc ? "failed" : "ok"));
40455  VVA_ONLY( pWal->lockError = (rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40456  return rc;
40457}
40458static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
40459  if( pWal->exclusiveMode ) return;
40460  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40461                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
40462  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
40463             walLockName(lockIdx), n));
40464}
40465
40466/*
40467** Compute a hash on a page number.  The resulting hash value must land
40468** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
40469** the hash to the next value in the event of a collision.
40470*/
40471static int walHash(u32 iPage){
40472  assert( iPage>0 );
40473  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
40474  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
40475}
40476static int walNextHash(int iPriorHash){
40477  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
40478}
40479
40480/*
40481** Return pointers to the hash table and page number array stored on
40482** page iHash of the wal-index. The wal-index is broken into 32KB pages
40483** numbered starting from 0.
40484**
40485** Set output variable *paHash to point to the start of the hash table
40486** in the wal-index file. Set *piZero to one less than the frame
40487** number of the first frame indexed by this hash table. If a
40488** slot in the hash table is set to N, it refers to frame number
40489** (*piZero+N) in the log.
40490**
40491** Finally, set *paPgno so that *paPgno[1] is the page number of the
40492** first frame indexed by the hash table, frame (*piZero+1).
40493*/
40494static int walHashGet(
40495  Wal *pWal,                      /* WAL handle */
40496  int iHash,                      /* Find the iHash'th table */
40497  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
40498  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
40499  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
40500){
40501  int rc;                         /* Return code */
40502  volatile u32 *aPgno;
40503
40504  rc = walIndexPage(pWal, iHash, &aPgno);
40505  assert( rc==SQLITE_OK || iHash>0 );
40506
40507  if( rc==SQLITE_OK ){
40508    u32 iZero;
40509    volatile ht_slot *aHash;
40510
40511    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
40512    if( iHash==0 ){
40513      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
40514      iZero = 0;
40515    }else{
40516      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
40517    }
40518
40519    *paPgno = &aPgno[-1];
40520    *paHash = aHash;
40521    *piZero = iZero;
40522  }
40523  return rc;
40524}
40525
40526/*
40527** Return the number of the wal-index page that contains the hash-table
40528** and page-number array that contain entries corresponding to WAL frame
40529** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
40530** are numbered starting from 0.
40531*/
40532static int walFramePage(u32 iFrame){
40533  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
40534  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
40535       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
40536       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
40537       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
40538       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
40539  );
40540  return iHash;
40541}
40542
40543/*
40544** Return the page number associated with frame iFrame in this WAL.
40545*/
40546static u32 walFramePgno(Wal *pWal, u32 iFrame){
40547  int iHash = walFramePage(iFrame);
40548  if( iHash==0 ){
40549    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
40550  }
40551  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
40552}
40553
40554/*
40555** Remove entries from the hash table that point to WAL slots greater
40556** than pWal->hdr.mxFrame.
40557**
40558** This function is called whenever pWal->hdr.mxFrame is decreased due
40559** to a rollback or savepoint.
40560**
40561** At most only the hash table containing pWal->hdr.mxFrame needs to be
40562** updated.  Any later hash tables will be automatically cleared when
40563** pWal->hdr.mxFrame advances to the point where those hash tables are
40564** actually needed.
40565*/
40566static void walCleanupHash(Wal *pWal){
40567  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
40568  volatile u32 *aPgno = 0;        /* Page number array for hash table */
40569  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
40570  int iLimit = 0;                 /* Zero values greater than this */
40571  int nByte;                      /* Number of bytes to zero in aPgno[] */
40572  int i;                          /* Used to iterate through aHash[] */
40573
40574  assert( pWal->writeLock );
40575  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
40576  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
40577  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
40578
40579  if( pWal->hdr.mxFrame==0 ) return;
40580
40581  /* Obtain pointers to the hash-table and page-number array containing
40582  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
40583  ** that the page said hash-table and array reside on is already mapped.
40584  */
40585  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
40586  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
40587  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
40588
40589  /* Zero all hash-table entries that correspond to frame numbers greater
40590  ** than pWal->hdr.mxFrame.
40591  */
40592  iLimit = pWal->hdr.mxFrame - iZero;
40593  assert( iLimit>0 );
40594  for(i=0; i<HASHTABLE_NSLOT; i++){
40595    if( aHash[i]>iLimit ){
40596      aHash[i] = 0;
40597    }
40598  }
40599
40600  /* Zero the entries in the aPgno array that correspond to frames with
40601  ** frame numbers greater than pWal->hdr.mxFrame.
40602  */
40603  nByte = ((char *)aHash - (char *)&aPgno[iLimit+1]);
40604  memset((void *)&aPgno[iLimit+1], 0, nByte);
40605
40606#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40607  /* Verify that the every entry in the mapping region is still reachable
40608  ** via the hash table even after the cleanup.
40609  */
40610  if( iLimit ){
40611    int i;           /* Loop counter */
40612    int iKey;        /* Hash key */
40613    for(i=1; i<=iLimit; i++){
40614      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
40615        if( aHash[iKey]==i ) break;
40616      }
40617      assert( aHash[iKey]==i );
40618    }
40619  }
40620#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
40621}
40622
40623
40624/*
40625** Set an entry in the wal-index that will map database page number
40626** pPage into WAL frame iFrame.
40627*/
40628static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
40629  int rc;                         /* Return code */
40630  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
40631  volatile u32 *aPgno = 0;        /* Page number array */
40632  volatile ht_slot *aHash = 0;    /* Hash table */
40633
40634  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
40635
40636  /* Assuming the wal-index file was successfully mapped, populate the
40637  ** page number array and hash table entry.
40638  */
40639  if( rc==SQLITE_OK ){
40640    int iKey;                     /* Hash table key */
40641    int idx;                      /* Value to write to hash-table slot */
40642    TESTONLY( int nCollide = 0;   /* Number of hash collisions */ )
40643
40644    idx = iFrame - iZero;
40645    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
40646
40647    /* If this is the first entry to be added to this hash-table, zero the
40648    ** entire hash table and aPgno[] array before proceding.
40649    */
40650    if( idx==1 ){
40651      int nByte = (u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1];
40652      memset((void*)&aPgno[1], 0, nByte);
40653    }
40654
40655    /* If the entry in aPgno[] is already set, then the previous writer
40656    ** must have exited unexpectedly in the middle of a transaction (after
40657    ** writing one or more dirty pages to the WAL to free up memory).
40658    ** Remove the remnants of that writers uncommitted transaction from
40659    ** the hash-table before writing any new entries.
40660    */
40661    if( aPgno[idx] ){
40662      walCleanupHash(pWal);
40663      assert( !aPgno[idx] );
40664    }
40665
40666    /* Write the aPgno[] array entry and the hash-table slot. */
40667    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
40668      assert( nCollide++ < idx );
40669    }
40670    aPgno[idx] = iPage;
40671    aHash[iKey] = idx;
40672
40673#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40674    /* Verify that the number of entries in the hash table exactly equals
40675    ** the number of entries in the mapping region.
40676    */
40677    {
40678      int i;           /* Loop counter */
40679      int nEntry = 0;  /* Number of entries in the hash table */
40680      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
40681      assert( nEntry==idx );
40682    }
40683
40684    /* Verify that the every entry in the mapping region is reachable
40685    ** via the hash table.  This turns out to be a really, really expensive
40686    ** thing to check, so only do this occasionally - not on every
40687    ** iteration.
40688    */
40689    if( (idx&0x3ff)==0 ){
40690      int i;           /* Loop counter */
40691      for(i=1; i<=idx; i++){
40692        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
40693          if( aHash[iKey]==i ) break;
40694        }
40695        assert( aHash[iKey]==i );
40696      }
40697    }
40698#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
40699  }
40700
40701
40702  return rc;
40703}
40704
40705
40706/*
40707** Recover the wal-index by reading the write-ahead log file.
40708**
40709** This routine first tries to establish an exclusive lock on the
40710** wal-index to prevent other threads/processes from doing anything
40711** with the WAL or wal-index while recovery is running.  The
40712** WAL_RECOVER_LOCK is also held so that other threads will know
40713** that this thread is running recovery.  If unable to establish
40714** the necessary locks, this routine returns SQLITE_BUSY.
40715*/
40716static int walIndexRecover(Wal *pWal){
40717  int rc;                         /* Return Code */
40718  i64 nSize;                      /* Size of log file */
40719  u32 aFrameCksum[2] = {0, 0};
40720  int iLock;                      /* Lock offset to lock for checkpoint */
40721  int nLock;                      /* Number of locks to hold */
40722
40723  /* Obtain an exclusive lock on all byte in the locking range not already
40724  ** locked by the caller. The caller is guaranteed to have locked the
40725  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
40726  ** If successful, the same bytes that are locked here are unlocked before
40727  ** this function returns.
40728  */
40729  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
40730  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
40731  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
40732  assert( pWal->writeLock );
40733  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
40734  nLock = SQLITE_SHM_NLOCK - iLock;
40735  rc = walLockExclusive(pWal, iLock, nLock);
40736  if( rc ){
40737    return rc;
40738  }
40739  WALTRACE(("WAL%p: recovery begin...\n", pWal));
40740
40741  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
40742
40743  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
40744  if( rc!=SQLITE_OK ){
40745    goto recovery_error;
40746  }
40747
40748  if( nSize>WAL_HDRSIZE ){
40749    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
40750    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
40751    int szFrame;                  /* Number of bytes in buffer aFrame[] */
40752    u8 *aData;                    /* Pointer to data part of aFrame buffer */
40753    int iFrame;                   /* Index of last frame read */
40754    i64 iOffset;                  /* Next offset to read from log file */
40755    int szPage;                   /* Page size according to the log */
40756    u32 magic;                    /* Magic value read from WAL header */
40757    u32 version;                  /* Magic value read from WAL header */
40758
40759    /* Read in the WAL header. */
40760    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
40761    if( rc!=SQLITE_OK ){
40762      goto recovery_error;
40763    }
40764
40765    /* If the database page size is not a power of two, or is greater than
40766    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
40767    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
40768    ** WAL file.
40769    */
40770    magic = sqlite3Get4byte(&aBuf[0]);
40771    szPage = sqlite3Get4byte(&aBuf[8]);
40772    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
40773     || szPage&(szPage-1)
40774     || szPage>SQLITE_MAX_PAGE_SIZE
40775     || szPage<512
40776    ){
40777      goto finished;
40778    }
40779    pWal->hdr.bigEndCksum = (magic&0x00000001);
40780    pWal->szPage = szPage;
40781    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
40782    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
40783
40784    /* Verify that the WAL header checksum is correct */
40785    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
40786        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
40787    );
40788    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
40789     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
40790    ){
40791      goto finished;
40792    }
40793
40794    /* Verify that the version number on the WAL format is one that
40795    ** are able to understand */
40796    version = sqlite3Get4byte(&aBuf[4]);
40797    if( version!=WAL_MAX_VERSION ){
40798      rc = SQLITE_CANTOPEN_BKPT;
40799      goto finished;
40800    }
40801
40802    /* Malloc a buffer to read frames into. */
40803    szFrame = szPage + WAL_FRAME_HDRSIZE;
40804    aFrame = (u8 *)sqlite3_malloc(szFrame);
40805    if( !aFrame ){
40806      rc = SQLITE_NOMEM;
40807      goto recovery_error;
40808    }
40809    aData = &aFrame[WAL_FRAME_HDRSIZE];
40810
40811    /* Read all frames from the log file. */
40812    iFrame = 0;
40813    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
40814      u32 pgno;                   /* Database page number for frame */
40815      u32 nTruncate;              /* dbsize field from frame header */
40816      int isValid;                /* True if this frame is valid */
40817
40818      /* Read and decode the next log frame. */
40819      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
40820      if( rc!=SQLITE_OK ) break;
40821      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
40822      if( !isValid ) break;
40823      rc = walIndexAppend(pWal, ++iFrame, pgno);
40824      if( rc!=SQLITE_OK ) break;
40825
40826      /* If nTruncate is non-zero, this is a commit record. */
40827      if( nTruncate ){
40828        pWal->hdr.mxFrame = iFrame;
40829        pWal->hdr.nPage = nTruncate;
40830        pWal->hdr.szPage = szPage;
40831        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
40832        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
40833      }
40834    }
40835
40836    sqlite3_free(aFrame);
40837  }
40838
40839finished:
40840  if( rc==SQLITE_OK ){
40841    volatile WalCkptInfo *pInfo;
40842    int i;
40843    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
40844    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
40845    walIndexWriteHdr(pWal);
40846
40847    /* Reset the checkpoint-header. This is safe because this thread is
40848    ** currently holding locks that exclude all other readers, writers and
40849    ** checkpointers.
40850    */
40851    pInfo = walCkptInfo(pWal);
40852    pInfo->nBackfill = 0;
40853    pInfo->aReadMark[0] = 0;
40854    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
40855  }
40856
40857recovery_error:
40858  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
40859  walUnlockExclusive(pWal, iLock, nLock);
40860  return rc;
40861}
40862
40863/*
40864** Close an open wal-index.
40865*/
40866static void walIndexClose(Wal *pWal, int isDelete){
40867  if( pWal->isWIndexOpen ){
40868    sqlite3OsShmClose(pWal->pDbFd, isDelete);
40869    pWal->isWIndexOpen = 0;
40870  }
40871}
40872
40873/*
40874** Open a connection to the WAL file associated with database zDbName.
40875** The database file must already be opened on connection pDbFd.
40876**
40877** A SHARED lock should be held on the database file when this function
40878** is called. The purpose of this SHARED lock is to prevent any other
40879** client from unlinking the WAL or wal-index file. If another process
40880** were to do this just after this client opened one of these files, the
40881** system would be badly broken.
40882**
40883** If the log file is successfully opened, SQLITE_OK is returned and
40884** *ppWal is set to point to a new WAL handle. If an error occurs,
40885** an SQLite error code is returned and *ppWal is left unmodified.
40886*/
40887SQLITE_PRIVATE int sqlite3WalOpen(
40888  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
40889  sqlite3_file *pDbFd,            /* The open database file */
40890  const char *zDbName,            /* Name of the database file */
40891  Wal **ppWal                     /* OUT: Allocated Wal handle */
40892){
40893  int rc;                         /* Return Code */
40894  Wal *pRet;                      /* Object to allocate and return */
40895  int flags;                      /* Flags passed to OsOpen() */
40896  char *zWal;                     /* Name of write-ahead log file */
40897  int nWal;                       /* Length of zWal in bytes */
40898
40899  assert( zDbName && zDbName[0] );
40900  assert( pDbFd );
40901
40902  /* In the amalgamation, the os_unix.c and os_win.c source files come before
40903  ** this source file.  Verify that the #defines of the locking byte offsets
40904  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
40905  */
40906#ifdef WIN_SHM_BASE
40907  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
40908#endif
40909#ifdef UNIX_SHM_BASE
40910  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
40911#endif
40912
40913
40914  /* Allocate an instance of struct Wal to return. */
40915  *ppWal = 0;
40916  nWal = sqlite3Strlen30(zDbName) + 5;
40917  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile + nWal);
40918  if( !pRet ){
40919    return SQLITE_NOMEM;
40920  }
40921
40922  pRet->pVfs = pVfs;
40923  pRet->pWalFd = (sqlite3_file *)&pRet[1];
40924  pRet->pDbFd = pDbFd;
40925  pRet->readLock = -1;
40926  sqlite3_randomness(8, &pRet->hdr.aSalt);
40927  pRet->zWalName = zWal = pVfs->szOsFile + (char*)pRet->pWalFd;
40928  sqlite3_snprintf(nWal, zWal, "%s-wal", zDbName);
40929  rc = sqlite3OsShmOpen(pDbFd);
40930
40931  /* Open file handle on the write-ahead log file. */
40932  if( rc==SQLITE_OK ){
40933    pRet->isWIndexOpen = 1;
40934    flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_JOURNAL);
40935    rc = sqlite3OsOpen(pVfs, zWal, pRet->pWalFd, flags, &flags);
40936  }
40937
40938  if( rc!=SQLITE_OK ){
40939    walIndexClose(pRet, 0);
40940    sqlite3OsClose(pRet->pWalFd);
40941    sqlite3_free(pRet);
40942  }else{
40943    *ppWal = pRet;
40944    WALTRACE(("WAL%d: opened\n", pRet));
40945  }
40946  return rc;
40947}
40948
40949/*
40950** Find the smallest page number out of all pages held in the WAL that
40951** has not been returned by any prior invocation of this method on the
40952** same WalIterator object.   Write into *piFrame the frame index where
40953** that page was last written into the WAL.  Write into *piPage the page
40954** number.
40955**
40956** Return 0 on success.  If there are no pages in the WAL with a page
40957** number larger than *piPage, then return 1.
40958*/
40959static int walIteratorNext(
40960  WalIterator *p,               /* Iterator */
40961  u32 *piPage,                  /* OUT: The page number of the next page */
40962  u32 *piFrame                  /* OUT: Wal frame index of next page */
40963){
40964  u32 iMin;                     /* Result pgno must be greater than iMin */
40965  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
40966  int i;                        /* For looping through segments */
40967
40968  iMin = p->iPrior;
40969  assert( iMin<0xffffffff );
40970  for(i=p->nSegment-1; i>=0; i--){
40971    struct WalSegment *pSegment = &p->aSegment[i];
40972    while( pSegment->iNext<pSegment->nEntry ){
40973      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
40974      if( iPg>iMin ){
40975        if( iPg<iRet ){
40976          iRet = iPg;
40977          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
40978        }
40979        break;
40980      }
40981      pSegment->iNext++;
40982    }
40983  }
40984
40985  *piPage = p->iPrior = iRet;
40986  return (iRet==0xFFFFFFFF);
40987}
40988
40989/*
40990** This function merges two sorted lists into a single sorted list.
40991*/
40992static void walMerge(
40993  u32 *aContent,                  /* Pages in wal */
40994  ht_slot *aLeft,                 /* IN: Left hand input list */
40995  int nLeft,                      /* IN: Elements in array *paLeft */
40996  ht_slot **paRight,              /* IN/OUT: Right hand input list */
40997  int *pnRight,                   /* IN/OUT: Elements in *paRight */
40998  ht_slot *aTmp                   /* Temporary buffer */
40999){
41000  int iLeft = 0;                  /* Current index in aLeft */
41001  int iRight = 0;                 /* Current index in aRight */
41002  int iOut = 0;                   /* Current index in output buffer */
41003  int nRight = *pnRight;
41004  ht_slot *aRight = *paRight;
41005
41006  assert( nLeft>0 && nRight>0 );
41007  while( iRight<nRight || iLeft<nLeft ){
41008    ht_slot logpage;
41009    Pgno dbpage;
41010
41011    if( (iLeft<nLeft)
41012     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
41013    ){
41014      logpage = aLeft[iLeft++];
41015    }else{
41016      logpage = aRight[iRight++];
41017    }
41018    dbpage = aContent[logpage];
41019
41020    aTmp[iOut++] = logpage;
41021    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
41022
41023    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
41024    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
41025  }
41026
41027  *paRight = aLeft;
41028  *pnRight = iOut;
41029  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
41030}
41031
41032/*
41033** Sort the elements in list aList, removing any duplicates.
41034*/
41035static void walMergesort(
41036  u32 *aContent,                  /* Pages in wal */
41037  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
41038  ht_slot *aList,                 /* IN/OUT: List to sort */
41039  int *pnList                     /* IN/OUT: Number of elements in aList[] */
41040){
41041  struct Sublist {
41042    int nList;                    /* Number of elements in aList */
41043    ht_slot *aList;               /* Pointer to sub-list content */
41044  };
41045
41046  const int nList = *pnList;      /* Size of input list */
41047  int nMerge = 0;                 /* Number of elements in list aMerge */
41048  ht_slot *aMerge = 0;            /* List to be merged */
41049  int iList;                      /* Index into input list */
41050  int iSub = 0;                   /* Index into aSub array */
41051  struct Sublist aSub[13];        /* Array of sub-lists */
41052
41053  memset(aSub, 0, sizeof(aSub));
41054  assert( nList<=HASHTABLE_NPAGE && nList>0 );
41055  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
41056
41057  for(iList=0; iList<nList; iList++){
41058    nMerge = 1;
41059    aMerge = &aList[iList];
41060    for(iSub=0; iList & (1<<iSub); iSub++){
41061      struct Sublist *p = &aSub[iSub];
41062      assert( p->aList && p->nList<=(1<<iSub) );
41063      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
41064      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41065    }
41066    aSub[iSub].aList = aMerge;
41067    aSub[iSub].nList = nMerge;
41068  }
41069
41070  for(iSub++; iSub<ArraySize(aSub); iSub++){
41071    if( nList & (1<<iSub) ){
41072      struct Sublist *p = &aSub[iSub];
41073      assert( p->nList<=(1<<iSub) );
41074      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
41075      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41076    }
41077  }
41078  assert( aMerge==aList );
41079  *pnList = nMerge;
41080
41081#ifdef SQLITE_DEBUG
41082  {
41083    int i;
41084    for(i=1; i<*pnList; i++){
41085      assert( aContent[aList[i]] > aContent[aList[i-1]] );
41086    }
41087  }
41088#endif
41089}
41090
41091/*
41092** Free an iterator allocated by walIteratorInit().
41093*/
41094static void walIteratorFree(WalIterator *p){
41095  sqlite3ScratchFree(p);
41096}
41097
41098/*
41099** Construct a WalInterator object that can be used to loop over all
41100** pages in the WAL in ascending order. The caller must hold the checkpoint
41101**
41102** On success, make *pp point to the newly allocated WalInterator object
41103** return SQLITE_OK. Otherwise, return an error code. If this routine
41104** returns an error, the value of *pp is undefined.
41105**
41106** The calling routine should invoke walIteratorFree() to destroy the
41107** WalIterator object when it has finished with it.
41108*/
41109static int walIteratorInit(Wal *pWal, WalIterator **pp){
41110  WalIterator *p;                 /* Return value */
41111  int nSegment;                   /* Number of segments to merge */
41112  u32 iLast;                      /* Last frame in log */
41113  int nByte;                      /* Number of bytes to allocate */
41114  int i;                          /* Iterator variable */
41115  ht_slot *aTmp;                  /* Temp space used by merge-sort */
41116  int rc = SQLITE_OK;             /* Return Code */
41117
41118  /* This routine only runs while holding the checkpoint lock. And
41119  ** it only runs if there is actually content in the log (mxFrame>0).
41120  */
41121  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
41122  iLast = pWal->hdr.mxFrame;
41123
41124  /* Allocate space for the WalIterator object. */
41125  nSegment = walFramePage(iLast) + 1;
41126  nByte = sizeof(WalIterator)
41127        + (nSegment-1)*sizeof(struct WalSegment)
41128        + iLast*sizeof(ht_slot);
41129  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
41130  if( !p ){
41131    return SQLITE_NOMEM;
41132  }
41133  memset(p, 0, nByte);
41134  p->nSegment = nSegment;
41135
41136  /* Allocate temporary space used by the merge-sort routine. This block
41137  ** of memory will be freed before this function returns.
41138  */
41139  aTmp = (ht_slot *)sqlite3ScratchMalloc(
41140      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
41141  );
41142  if( !aTmp ){
41143    rc = SQLITE_NOMEM;
41144  }
41145
41146  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
41147    volatile ht_slot *aHash;
41148    u32 iZero;
41149    volatile u32 *aPgno;
41150
41151    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
41152    if( rc==SQLITE_OK ){
41153      int j;                      /* Counter variable */
41154      int nEntry;                 /* Number of entries in this segment */
41155      ht_slot *aIndex;            /* Sorted index for this segment */
41156
41157      aPgno++;
41158      nEntry = ((i+1)==nSegment)?(int)(iLast-iZero):(u32 *)aHash-(u32 *)aPgno;
41159      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
41160      iZero++;
41161
41162      for(j=0; j<nEntry; j++){
41163        aIndex[j] = j;
41164      }
41165      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
41166      p->aSegment[i].iZero = iZero;
41167      p->aSegment[i].nEntry = nEntry;
41168      p->aSegment[i].aIndex = aIndex;
41169      p->aSegment[i].aPgno = (u32 *)aPgno;
41170    }
41171  }
41172  sqlite3ScratchFree(aTmp);
41173
41174  if( rc!=SQLITE_OK ){
41175    walIteratorFree(p);
41176  }
41177  *pp = p;
41178  return rc;
41179}
41180
41181/*
41182** Copy as much content as we can from the WAL back into the database file
41183** in response to an sqlite3_wal_checkpoint() request or the equivalent.
41184**
41185** The amount of information copies from WAL to database might be limited
41186** by active readers.  This routine will never overwrite a database page
41187** that a concurrent reader might be using.
41188**
41189** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
41190** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
41191** checkpoints are always run by a background thread or background
41192** process, foreground threads will never block on a lengthy fsync call.
41193**
41194** Fsync is called on the WAL before writing content out of the WAL and
41195** into the database.  This ensures that if the new content is persistent
41196** in the WAL and can be recovered following a power-loss or hard reset.
41197**
41198** Fsync is also called on the database file if (and only if) the entire
41199** WAL content is copied into the database file.  This second fsync makes
41200** it safe to delete the WAL since the new content will persist in the
41201** database file.
41202**
41203** This routine uses and updates the nBackfill field of the wal-index header.
41204** This is the only routine tha will increase the value of nBackfill.
41205** (A WAL reset or recovery will revert nBackfill to zero, but not increase
41206** its value.)
41207**
41208** The caller must be holding sufficient locks to ensure that no other
41209** checkpoint is running (in any other thread or process) at the same
41210** time.
41211*/
41212static int walCheckpoint(
41213  Wal *pWal,                      /* Wal connection */
41214  int sync_flags,                 /* Flags for OsSync() (or 0) */
41215  int nBuf,                       /* Size of zBuf in bytes */
41216  u8 *zBuf                        /* Temporary buffer to use */
41217){
41218  int rc;                         /* Return code */
41219  int szPage = pWal->hdr.szPage;  /* Database page-size */
41220  WalIterator *pIter = 0;         /* Wal iterator context */
41221  u32 iDbpage = 0;                /* Next database page to write */
41222  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
41223  u32 mxSafeFrame;                /* Max frame that can be backfilled */
41224  int i;                          /* Loop counter */
41225  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
41226
41227  if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
41228
41229  /* Allocate the iterator */
41230  rc = walIteratorInit(pWal, &pIter);
41231  if( rc!=SQLITE_OK ){
41232    return rc;
41233  }
41234  assert( pIter );
41235
41236  /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
41237  if( pWal->hdr.szPage!=nBuf ){
41238    rc = SQLITE_CORRUPT_BKPT;
41239    goto walcheckpoint_out;
41240  }
41241
41242  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
41243  ** safe to write into the database.  Frames beyond mxSafeFrame might
41244  ** overwrite database pages that are in use by active readers and thus
41245  ** cannot be backfilled from the WAL.
41246  */
41247  mxSafeFrame = pWal->hdr.mxFrame;
41248  pInfo = walCkptInfo(pWal);
41249  for(i=1; i<WAL_NREADER; i++){
41250    u32 y = pInfo->aReadMark[i];
41251    if( mxSafeFrame>=y ){
41252      assert( y<=pWal->hdr.mxFrame );
41253      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41254      if( rc==SQLITE_OK ){
41255        pInfo->aReadMark[i] = READMARK_NOT_USED;
41256        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41257      }else if( rc==SQLITE_BUSY ){
41258        mxSafeFrame = y;
41259      }else{
41260        goto walcheckpoint_out;
41261      }
41262    }
41263  }
41264
41265  if( pInfo->nBackfill<mxSafeFrame
41266   && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
41267  ){
41268    u32 nBackfill = pInfo->nBackfill;
41269
41270    /* Sync the WAL to disk */
41271    if( sync_flags ){
41272      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
41273    }
41274
41275    /* Iterate through the contents of the WAL, copying data to the db file. */
41276    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
41277      assert( walFramePgno(pWal, iFrame)==iDbpage );
41278      if( iFrame<=nBackfill || iFrame>mxSafeFrame ) continue;
41279      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage,
41280          walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE
41281      );
41282      if( rc!=SQLITE_OK ) break;
41283      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, (iDbpage-1)*szPage);
41284      if( rc!=SQLITE_OK ) break;
41285    }
41286
41287    /* If work was actually accomplished... */
41288    if( rc==SQLITE_OK ){
41289      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
41290        rc = sqlite3OsTruncate(pWal->pDbFd, ((i64)pWal->hdr.nPage*(i64)szPage));
41291        if( rc==SQLITE_OK && sync_flags ){
41292          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
41293        }
41294      }
41295      if( rc==SQLITE_OK ){
41296        pInfo->nBackfill = mxSafeFrame;
41297      }
41298    }
41299
41300    /* Release the reader lock held while backfilling */
41301    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
41302  }else if( rc==SQLITE_BUSY ){
41303    /* Reset the return code so as not to report a checkpoint failure
41304    ** just because active readers prevent any backfill.
41305    */
41306    rc = SQLITE_OK;
41307  }
41308
41309 walcheckpoint_out:
41310  walIteratorFree(pIter);
41311  return rc;
41312}
41313
41314/*
41315** Close a connection to a log file.
41316*/
41317SQLITE_PRIVATE int sqlite3WalClose(
41318  Wal *pWal,                      /* Wal to close */
41319  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
41320  int nBuf,
41321  u8 *zBuf                        /* Buffer of at least nBuf bytes */
41322){
41323  int rc = SQLITE_OK;
41324  if( pWal ){
41325    int isDelete = 0;             /* True to unlink wal and wal-index files */
41326
41327    /* If an EXCLUSIVE lock can be obtained on the database file (using the
41328    ** ordinary, rollback-mode locking methods, this guarantees that the
41329    ** connection associated with this log file is the only connection to
41330    ** the database. In this case checkpoint the database and unlink both
41331    ** the wal and wal-index files.
41332    **
41333    ** The EXCLUSIVE lock is not released before returning.
41334    */
41335    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
41336    if( rc==SQLITE_OK ){
41337      pWal->exclusiveMode = 1;
41338      rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
41339      if( rc==SQLITE_OK ){
41340        isDelete = 1;
41341      }
41342    }
41343
41344    walIndexClose(pWal, isDelete);
41345    sqlite3OsClose(pWal->pWalFd);
41346    if( isDelete ){
41347      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
41348    }
41349    WALTRACE(("WAL%p: closed\n", pWal));
41350    sqlite3_free(pWal->apWiData);
41351    sqlite3_free(pWal);
41352  }
41353  return rc;
41354}
41355
41356/*
41357** Try to read the wal-index header.  Return 0 on success and 1 if
41358** there is a problem.
41359**
41360** The wal-index is in shared memory.  Another thread or process might
41361** be writing the header at the same time this procedure is trying to
41362** read it, which might result in inconsistency.  A dirty read is detected
41363** by verifying that both copies of the header are the same and also by
41364** a checksum on the header.
41365**
41366** If and only if the read is consistent and the header is different from
41367** pWal->hdr, then pWal->hdr is updated to the content of the new header
41368** and *pChanged is set to 1.
41369**
41370** If the checksum cannot be verified return non-zero. If the header
41371** is read successfully and the checksum verified, return zero.
41372*/
41373static int walIndexTryHdr(Wal *pWal, int *pChanged){
41374  u32 aCksum[2];                  /* Checksum on the header content */
41375  WalIndexHdr h1, h2;             /* Two copies of the header content */
41376  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
41377
41378  /* The first page of the wal-index must be mapped at this point. */
41379  assert( pWal->nWiData>0 && pWal->apWiData[0] );
41380
41381  /* Read the header. This might happen currently with a write to the
41382  ** same area of shared memory on a different CPU in a SMP,
41383  ** meaning it is possible that an inconsistent snapshot is read
41384  ** from the file. If this happens, return non-zero.
41385  **
41386  ** There are two copies of the header at the beginning of the wal-index.
41387  ** When reading, read [0] first then [1].  Writes are in the reverse order.
41388  ** Memory barriers are used to prevent the compiler or the hardware from
41389  ** reordering the reads and writes.
41390  */
41391  aHdr = walIndexHdr(pWal);
41392  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
41393  sqlite3OsShmBarrier(pWal->pDbFd);
41394  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
41395
41396  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
41397    return 1;   /* Dirty read */
41398  }
41399  if( h1.isInit==0 ){
41400    return 1;   /* Malformed header - probably all zeros */
41401  }
41402  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
41403  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
41404    return 1;   /* Checksum does not match */
41405  }
41406
41407  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
41408    *pChanged = 1;
41409    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
41410    pWal->szPage = pWal->hdr.szPage;
41411  }
41412
41413  /* The header was successfully read. Return zero. */
41414  return 0;
41415}
41416
41417/*
41418** Read the wal-index header from the wal-index and into pWal->hdr.
41419** If the wal-header appears to be corrupt, try to reconstruct the
41420** wal-index from the WAL before returning.
41421**
41422** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
41423** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
41424** to 0.
41425**
41426** If the wal-index header is successfully read, return SQLITE_OK.
41427** Otherwise an SQLite error code.
41428*/
41429static int walIndexReadHdr(Wal *pWal, int *pChanged){
41430  int rc;                         /* Return code */
41431  int badHdr;                     /* True if a header read failed */
41432  volatile u32 *page0;            /* Chunk of wal-index containing header */
41433
41434  /* Ensure that page 0 of the wal-index (the page that contains the
41435  ** wal-index header) is mapped. Return early if an error occurs here.
41436  */
41437  assert( pChanged );
41438  rc = walIndexPage(pWal, 0, &page0);
41439  if( rc!=SQLITE_OK ){
41440    return rc;
41441  };
41442  assert( page0 || pWal->writeLock==0 );
41443
41444  /* If the first page of the wal-index has been mapped, try to read the
41445  ** wal-index header immediately, without holding any lock. This usually
41446  ** works, but may fail if the wal-index header is corrupt or currently
41447  ** being modified by another thread or process.
41448  */
41449  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
41450
41451  /* If the first attempt failed, it might have been due to a race
41452  ** with a writer.  So get a WRITE lock and try again.
41453  */
41454  assert( badHdr==0 || pWal->writeLock==0 );
41455  if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
41456    pWal->writeLock = 1;
41457    if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
41458      badHdr = walIndexTryHdr(pWal, pChanged);
41459      if( badHdr ){
41460        /* If the wal-index header is still malformed even while holding
41461        ** a WRITE lock, it can only mean that the header is corrupted and
41462        ** needs to be reconstructed.  So run recovery to do exactly that.
41463        */
41464        rc = walIndexRecover(pWal);
41465        *pChanged = 1;
41466      }
41467    }
41468    pWal->writeLock = 0;
41469    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
41470  }
41471
41472  /* If the header is read successfully, check the version number to make
41473  ** sure the wal-index was not constructed with some future format that
41474  ** this version of SQLite cannot understand.
41475  */
41476  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
41477    rc = SQLITE_CANTOPEN_BKPT;
41478  }
41479
41480  return rc;
41481}
41482
41483/*
41484** This is the value that walTryBeginRead returns when it needs to
41485** be retried.
41486*/
41487#define WAL_RETRY  (-1)
41488
41489/*
41490** Attempt to start a read transaction.  This might fail due to a race or
41491** other transient condition.  When that happens, it returns WAL_RETRY to
41492** indicate to the caller that it is safe to retry immediately.
41493**
41494** On success return SQLITE_OK.  On a permanent failure (such an
41495** I/O error or an SQLITE_BUSY because another process is running
41496** recovery) return a positive error code.
41497**
41498** The useWal parameter is true to force the use of the WAL and disable
41499** the case where the WAL is bypassed because it has been completely
41500** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
41501** to make a copy of the wal-index header into pWal->hdr.  If the
41502** wal-index header has changed, *pChanged is set to 1 (as an indication
41503** to the caller that the local paget cache is obsolete and needs to be
41504** flushed.)  When useWal==1, the wal-index header is assumed to already
41505** be loaded and the pChanged parameter is unused.
41506**
41507** The caller must set the cnt parameter to the number of prior calls to
41508** this routine during the current read attempt that returned WAL_RETRY.
41509** This routine will start taking more aggressive measures to clear the
41510** race conditions after multiple WAL_RETRY returns, and after an excessive
41511** number of errors will ultimately return SQLITE_PROTOCOL.  The
41512** SQLITE_PROTOCOL return indicates that some other process has gone rogue
41513** and is not honoring the locking protocol.  There is a vanishingly small
41514** chance that SQLITE_PROTOCOL could be returned because of a run of really
41515** bad luck when there is lots of contention for the wal-index, but that
41516** possibility is so small that it can be safely neglected, we believe.
41517**
41518** On success, this routine obtains a read lock on
41519** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
41520** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
41521** that means the Wal does not hold any read lock.  The reader must not
41522** access any database page that is modified by a WAL frame up to and
41523** including frame number aReadMark[pWal->readLock].  The reader will
41524** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
41525** Or if pWal->readLock==0, then the reader will ignore the WAL
41526** completely and get all content directly from the database file.
41527** If the useWal parameter is 1 then the WAL will never be ignored and
41528** this routine will always set pWal->readLock>0 on success.
41529** When the read transaction is completed, the caller must release the
41530** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
41531**
41532** This routine uses the nBackfill and aReadMark[] fields of the header
41533** to select a particular WAL_READ_LOCK() that strives to let the
41534** checkpoint process do as much work as possible.  This routine might
41535** update values of the aReadMark[] array in the header, but if it does
41536** so it takes care to hold an exclusive lock on the corresponding
41537** WAL_READ_LOCK() while changing values.
41538*/
41539static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
41540  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
41541  u32 mxReadMark;                 /* Largest aReadMark[] value */
41542  int mxI;                        /* Index of largest aReadMark[] value */
41543  int i;                          /* Loop counter */
41544  int rc = SQLITE_OK;             /* Return code  */
41545
41546  assert( pWal->readLock<0 );     /* Not currently locked */
41547
41548  /* Take steps to avoid spinning forever if there is a protocol error. */
41549  if( cnt>5 ){
41550    if( cnt>100 ) return SQLITE_PROTOCOL;
41551    sqlite3OsSleep(pWal->pVfs, 1);
41552  }
41553
41554  if( !useWal ){
41555    rc = walIndexReadHdr(pWal, pChanged);
41556    if( rc==SQLITE_BUSY ){
41557      /* If there is not a recovery running in another thread or process
41558      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
41559      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
41560      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
41561      ** would be technically correct.  But the race is benign since with
41562      ** WAL_RETRY this routine will be called again and will probably be
41563      ** right on the second iteration.
41564      */
41565      rc = walLockShared(pWal, WAL_RECOVER_LOCK);
41566      if( rc==SQLITE_OK ){
41567        walUnlockShared(pWal, WAL_RECOVER_LOCK);
41568        rc = WAL_RETRY;
41569      }else if( rc==SQLITE_BUSY ){
41570        rc = SQLITE_BUSY_RECOVERY;
41571      }
41572    }
41573    if( rc!=SQLITE_OK ){
41574      return rc;
41575    }
41576  }
41577
41578  pInfo = walCkptInfo(pWal);
41579  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
41580    /* The WAL has been completely backfilled (or it is empty).
41581    ** and can be safely ignored.
41582    */
41583    rc = walLockShared(pWal, WAL_READ_LOCK(0));
41584    sqlite3OsShmBarrier(pWal->pDbFd);
41585    if( rc==SQLITE_OK ){
41586      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
41587        /* It is not safe to allow the reader to continue here if frames
41588        ** may have been appended to the log before READ_LOCK(0) was obtained.
41589        ** When holding READ_LOCK(0), the reader ignores the entire log file,
41590        ** which implies that the database file contains a trustworthy
41591        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
41592        ** happening, this is usually correct.
41593        **
41594        ** However, if frames have been appended to the log (or if the log
41595        ** is wrapped and written for that matter) before the READ_LOCK(0)
41596        ** is obtained, that is not necessarily true. A checkpointer may
41597        ** have started to backfill the appended frames but crashed before
41598        ** it finished. Leaving a corrupt image in the database file.
41599        */
41600        walUnlockShared(pWal, WAL_READ_LOCK(0));
41601        return WAL_RETRY;
41602      }
41603      pWal->readLock = 0;
41604      return SQLITE_OK;
41605    }else if( rc!=SQLITE_BUSY ){
41606      return rc;
41607    }
41608  }
41609
41610  /* If we get this far, it means that the reader will want to use
41611  ** the WAL to get at content from recent commits.  The job now is
41612  ** to select one of the aReadMark[] entries that is closest to
41613  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
41614  */
41615  mxReadMark = 0;
41616  mxI = 0;
41617  for(i=1; i<WAL_NREADER; i++){
41618    u32 thisMark = pInfo->aReadMark[i];
41619    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
41620      assert( thisMark!=READMARK_NOT_USED );
41621      mxReadMark = thisMark;
41622      mxI = i;
41623    }
41624  }
41625  if( mxI==0 ){
41626    /* If we get here, it means that all of the aReadMark[] entries between
41627    ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
41628    ** be mxFrame, then retry.
41629    */
41630    rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
41631    if( rc==SQLITE_OK ){
41632      pInfo->aReadMark[1] = pWal->hdr.mxFrame;
41633      walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
41634      rc = WAL_RETRY;
41635    }else if( rc==SQLITE_BUSY ){
41636      rc = WAL_RETRY;
41637    }
41638    return rc;
41639  }else{
41640    if( mxReadMark < pWal->hdr.mxFrame ){
41641      for(i=1; i<WAL_NREADER; i++){
41642        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41643        if( rc==SQLITE_OK ){
41644          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
41645          mxI = i;
41646          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41647          break;
41648        }else if( rc!=SQLITE_BUSY ){
41649          return rc;
41650        }
41651      }
41652    }
41653
41654    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
41655    if( rc ){
41656      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
41657    }
41658    /* Now that the read-lock has been obtained, check that neither the
41659    ** value in the aReadMark[] array or the contents of the wal-index
41660    ** header have changed.
41661    **
41662    ** It is necessary to check that the wal-index header did not change
41663    ** between the time it was read and when the shared-lock was obtained
41664    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
41665    ** that the log file may have been wrapped by a writer, or that frames
41666    ** that occur later in the log than pWal->hdr.mxFrame may have been
41667    ** copied into the database by a checkpointer. If either of these things
41668    ** happened, then reading the database with the current value of
41669    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
41670    ** instead.
41671    **
41672    ** This does not guarantee that the copy of the wal-index header is up to
41673    ** date before proceeding. That would not be possible without somehow
41674    ** blocking writers. It only guarantees that a dangerous checkpoint or
41675    ** log-wrap (either of which would require an exclusive lock on
41676    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
41677    */
41678    sqlite3OsShmBarrier(pWal->pDbFd);
41679    if( pInfo->aReadMark[mxI]!=mxReadMark
41680     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
41681    ){
41682      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
41683      return WAL_RETRY;
41684    }else{
41685      assert( mxReadMark<=pWal->hdr.mxFrame );
41686      pWal->readLock = mxI;
41687    }
41688  }
41689  return rc;
41690}
41691
41692/*
41693** Begin a read transaction on the database.
41694**
41695** This routine used to be called sqlite3OpenSnapshot() and with good reason:
41696** it takes a snapshot of the state of the WAL and wal-index for the current
41697** instant in time.  The current thread will continue to use this snapshot.
41698** Other threads might append new content to the WAL and wal-index but
41699** that extra content is ignored by the current thread.
41700**
41701** If the database contents have changes since the previous read
41702** transaction, then *pChanged is set to 1 before returning.  The
41703** Pager layer will use this to know that is cache is stale and
41704** needs to be flushed.
41705*/
41706SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
41707  int rc;                         /* Return code */
41708  int cnt = 0;                    /* Number of TryBeginRead attempts */
41709
41710  do{
41711    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
41712  }while( rc==WAL_RETRY );
41713  return rc;
41714}
41715
41716/*
41717** Finish with a read transaction.  All this does is release the
41718** read-lock.
41719*/
41720SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
41721  if( pWal->readLock>=0 ){
41722    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
41723    pWal->readLock = -1;
41724  }
41725}
41726
41727/*
41728** Read a page from the WAL, if it is present in the WAL and if the
41729** current read transaction is configured to use the WAL.
41730**
41731** The *pInWal is set to 1 if the requested page is in the WAL and
41732** has been loaded.  Or *pInWal is set to 0 if the page was not in
41733** the WAL and needs to be read out of the database.
41734*/
41735SQLITE_PRIVATE int sqlite3WalRead(
41736  Wal *pWal,                      /* WAL handle */
41737  Pgno pgno,                      /* Database page number to read data for */
41738  int *pInWal,                    /* OUT: True if data is read from WAL */
41739  int nOut,                       /* Size of buffer pOut in bytes */
41740  u8 *pOut                        /* Buffer to write page data to */
41741){
41742  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
41743  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
41744  int iHash;                      /* Used to loop through N hash tables */
41745
41746  /* This routine is only be called from within a read transaction. */
41747  assert( pWal->readLock>=0 || pWal->lockError );
41748
41749  /* If the "last page" field of the wal-index header snapshot is 0, then
41750  ** no data will be read from the wal under any circumstances. Return early
41751  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
41752  ** then the WAL is ignored by the reader so return early, as if the
41753  ** WAL were empty.
41754  */
41755  if( iLast==0 || pWal->readLock==0 ){
41756    *pInWal = 0;
41757    return SQLITE_OK;
41758  }
41759
41760  /* Search the hash table or tables for an entry matching page number
41761  ** pgno. Each iteration of the following for() loop searches one
41762  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
41763  **
41764  ** This code might run concurrently to the code in walIndexAppend()
41765  ** that adds entries to the wal-index (and possibly to this hash
41766  ** table). This means the value just read from the hash
41767  ** slot (aHash[iKey]) may have been added before or after the
41768  ** current read transaction was opened. Values added after the
41769  ** read transaction was opened may have been written incorrectly -
41770  ** i.e. these slots may contain garbage data. However, we assume
41771  ** that any slots written before the current read transaction was
41772  ** opened remain unmodified.
41773  **
41774  ** For the reasons above, the if(...) condition featured in the inner
41775  ** loop of the following block is more stringent that would be required
41776  ** if we had exclusive access to the hash-table:
41777  **
41778  **   (aPgno[iFrame]==pgno):
41779  **     This condition filters out normal hash-table collisions.
41780  **
41781  **   (iFrame<=iLast):
41782  **     This condition filters out entries that were added to the hash
41783  **     table after the current read-transaction had started.
41784  */
41785  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
41786    volatile ht_slot *aHash;      /* Pointer to hash table */
41787    volatile u32 *aPgno;          /* Pointer to array of page numbers */
41788    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
41789    int iKey;                     /* Hash slot index */
41790    int rc;
41791
41792    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
41793    if( rc!=SQLITE_OK ){
41794      return rc;
41795    }
41796    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
41797      u32 iFrame = aHash[iKey] + iZero;
41798      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
41799        assert( iFrame>iRead );
41800        iRead = iFrame;
41801      }
41802    }
41803  }
41804
41805#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
41806  /* If expensive assert() statements are available, do a linear search
41807  ** of the wal-index file content. Make sure the results agree with the
41808  ** result obtained using the hash indexes above.  */
41809  {
41810    u32 iRead2 = 0;
41811    u32 iTest;
41812    for(iTest=iLast; iTest>0; iTest--){
41813      if( walFramePgno(pWal, iTest)==pgno ){
41814        iRead2 = iTest;
41815        break;
41816      }
41817    }
41818    assert( iRead==iRead2 );
41819  }
41820#endif
41821
41822  /* If iRead is non-zero, then it is the log frame number that contains the
41823  ** required page. Read and return data from the log file.
41824  */
41825  if( iRead ){
41826    i64 iOffset = walFrameOffset(iRead, pWal->hdr.szPage) + WAL_FRAME_HDRSIZE;
41827    *pInWal = 1;
41828    return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
41829  }
41830
41831  *pInWal = 0;
41832  return SQLITE_OK;
41833}
41834
41835
41836/*
41837** Set *pPgno to the size of the database file (or zero, if unknown).
41838*/
41839SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
41840  assert( pWal->readLock>=0 || pWal->lockError );
41841  *pPgno = pWal->hdr.nPage;
41842}
41843
41844
41845/*
41846** This function starts a write transaction on the WAL.
41847**
41848** A read transaction must have already been started by a prior call
41849** to sqlite3WalBeginReadTransaction().
41850**
41851** If another thread or process has written into the database since
41852** the read transaction was started, then it is not possible for this
41853** thread to write as doing so would cause a fork.  So this routine
41854** returns SQLITE_BUSY in that case and no write transaction is started.
41855**
41856** There can only be a single writer active at a time.
41857*/
41858SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
41859  int rc;
41860
41861  /* Cannot start a write transaction without first holding a read
41862  ** transaction. */
41863  assert( pWal->readLock>=0 );
41864
41865  /* Only one writer allowed at a time.  Get the write lock.  Return
41866  ** SQLITE_BUSY if unable.
41867  */
41868  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
41869  if( rc ){
41870    return rc;
41871  }
41872  pWal->writeLock = 1;
41873
41874  /* If another connection has written to the database file since the
41875  ** time the read transaction on this connection was started, then
41876  ** the write is disallowed.
41877  */
41878  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
41879    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
41880    pWal->writeLock = 0;
41881    rc = SQLITE_BUSY;
41882  }
41883
41884  return rc;
41885}
41886
41887/*
41888** End a write transaction.  The commit has already been done.  This
41889** routine merely releases the lock.
41890*/
41891SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
41892  walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
41893  pWal->writeLock = 0;
41894  return SQLITE_OK;
41895}
41896
41897/*
41898** If any data has been written (but not committed) to the log file, this
41899** function moves the write-pointer back to the start of the transaction.
41900**
41901** Additionally, the callback function is invoked for each frame written
41902** to the WAL since the start of the transaction. If the callback returns
41903** other than SQLITE_OK, it is not invoked again and the error code is
41904** returned to the caller.
41905**
41906** Otherwise, if the callback function does not return an error, this
41907** function returns SQLITE_OK.
41908*/
41909SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
41910  int rc = SQLITE_OK;
41911  if( pWal->writeLock ){
41912    Pgno iMax = pWal->hdr.mxFrame;
41913    Pgno iFrame;
41914
41915    /* Restore the clients cache of the wal-index header to the state it
41916    ** was in before the client began writing to the database.
41917    */
41918    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
41919
41920    for(iFrame=pWal->hdr.mxFrame+1;
41921        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
41922        iFrame++
41923    ){
41924      /* This call cannot fail. Unless the page for which the page number
41925      ** is passed as the second argument is (a) in the cache and
41926      ** (b) has an outstanding reference, then xUndo is either a no-op
41927      ** (if (a) is false) or simply expels the page from the cache (if (b)
41928      ** is false).
41929      **
41930      ** If the upper layer is doing a rollback, it is guaranteed that there
41931      ** are no outstanding references to any page other than page 1. And
41932      ** page 1 is never written to the log until the transaction is
41933      ** committed. As a result, the call to xUndo may not fail.
41934      */
41935      assert( walFramePgno(pWal, iFrame)!=1 );
41936      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
41937    }
41938    walCleanupHash(pWal);
41939  }
41940  assert( rc==SQLITE_OK );
41941  return rc;
41942}
41943
41944/*
41945** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
41946** values. This function populates the array with values required to
41947** "rollback" the write position of the WAL handle back to the current
41948** point in the event of a savepoint rollback (via WalSavepointUndo()).
41949*/
41950SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
41951  assert( pWal->writeLock );
41952  aWalData[0] = pWal->hdr.mxFrame;
41953  aWalData[1] = pWal->hdr.aFrameCksum[0];
41954  aWalData[2] = pWal->hdr.aFrameCksum[1];
41955  aWalData[3] = pWal->nCkpt;
41956}
41957
41958/*
41959** Move the write position of the WAL back to the point identified by
41960** the values in the aWalData[] array. aWalData must point to an array
41961** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
41962** by a call to WalSavepoint().
41963*/
41964SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
41965  int rc = SQLITE_OK;
41966
41967  assert( pWal->writeLock );
41968  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
41969
41970  if( aWalData[3]!=pWal->nCkpt ){
41971    /* This savepoint was opened immediately after the write-transaction
41972    ** was started. Right after that, the writer decided to wrap around
41973    ** to the start of the log. Update the savepoint values to match.
41974    */
41975    aWalData[0] = 0;
41976    aWalData[3] = pWal->nCkpt;
41977  }
41978
41979  if( aWalData[0]<pWal->hdr.mxFrame ){
41980    pWal->hdr.mxFrame = aWalData[0];
41981    pWal->hdr.aFrameCksum[0] = aWalData[1];
41982    pWal->hdr.aFrameCksum[1] = aWalData[2];
41983    walCleanupHash(pWal);
41984  }
41985
41986  return rc;
41987}
41988
41989/*
41990** This function is called just before writing a set of frames to the log
41991** file (see sqlite3WalFrames()). It checks to see if, instead of appending
41992** to the current log file, it is possible to overwrite the start of the
41993** existing log file with the new frames (i.e. "reset" the log). If so,
41994** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
41995** unchanged.
41996**
41997** SQLITE_OK is returned if no error is encountered (regardless of whether
41998** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
41999** if some error
42000*/
42001static int walRestartLog(Wal *pWal){
42002  int rc = SQLITE_OK;
42003  int cnt;
42004
42005  if( pWal->readLock==0 ){
42006    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
42007    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
42008    if( pInfo->nBackfill>0 ){
42009      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42010      if( rc==SQLITE_OK ){
42011        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
42012        ** readers are currently using the WAL), then the transactions
42013        ** frames will overwrite the start of the existing log. Update the
42014        ** wal-index header to reflect this.
42015        **
42016        ** In theory it would be Ok to update the cache of the header only
42017        ** at this point. But updating the actual wal-index header is also
42018        ** safe and means there is no special case for sqlite3WalUndo()
42019        ** to handle if this transaction is rolled back.
42020        */
42021        int i;                    /* Loop counter */
42022        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
42023        pWal->nCkpt++;
42024        pWal->hdr.mxFrame = 0;
42025        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
42026        sqlite3_randomness(4, &aSalt[1]);
42027        walIndexWriteHdr(pWal);
42028        pInfo->nBackfill = 0;
42029        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42030        assert( pInfo->aReadMark[0]==0 );
42031        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42032      }
42033    }
42034    walUnlockShared(pWal, WAL_READ_LOCK(0));
42035    pWal->readLock = -1;
42036    cnt = 0;
42037    do{
42038      int notUsed;
42039      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
42040    }while( rc==WAL_RETRY );
42041  }
42042  return rc;
42043}
42044
42045/*
42046** Write a set of frames to the log. The caller must hold the write-lock
42047** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
42048*/
42049SQLITE_PRIVATE int sqlite3WalFrames(
42050  Wal *pWal,                      /* Wal handle to write to */
42051  int szPage,                     /* Database page-size in bytes */
42052  PgHdr *pList,                   /* List of dirty pages to write */
42053  Pgno nTruncate,                 /* Database size after this commit */
42054  int isCommit,                   /* True if this is a commit */
42055  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
42056){
42057  int rc;                         /* Used to catch return codes */
42058  u32 iFrame;                     /* Next frame address */
42059  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
42060  PgHdr *p;                       /* Iterator to run through pList with. */
42061  PgHdr *pLast = 0;               /* Last frame in list */
42062  int nLast = 0;                  /* Number of extra copies of last page */
42063
42064  assert( pList );
42065  assert( pWal->writeLock );
42066
42067#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
42068  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
42069    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
42070              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
42071  }
42072#endif
42073
42074  /* See if it is possible to write these frames into the start of the
42075  ** log file, instead of appending to it at pWal->hdr.mxFrame.
42076  */
42077  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
42078    return rc;
42079  }
42080
42081  /* If this is the first frame written into the log, write the WAL
42082  ** header to the start of the WAL file. See comments at the top of
42083  ** this source file for a description of the WAL header format.
42084  */
42085  iFrame = pWal->hdr.mxFrame;
42086  if( iFrame==0 ){
42087    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
42088    u32 aCksum[2];                /* Checksum for wal-header */
42089
42090    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
42091    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
42092    sqlite3Put4byte(&aWalHdr[8], szPage);
42093    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
42094    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
42095    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
42096    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
42097    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
42098
42099    pWal->szPage = szPage;
42100    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
42101    pWal->hdr.aFrameCksum[0] = aCksum[0];
42102    pWal->hdr.aFrameCksum[1] = aCksum[1];
42103
42104    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
42105    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
42106    if( rc!=SQLITE_OK ){
42107      return rc;
42108    }
42109  }
42110  assert( pWal->szPage==szPage );
42111
42112  /* Write the log file. */
42113  for(p=pList; p; p=p->pDirty){
42114    u32 nDbsize;                  /* Db-size field for frame header */
42115    i64 iOffset;                  /* Write offset in log file */
42116    void *pData;
42117
42118
42119    iOffset = walFrameOffset(++iFrame, szPage);
42120
42121    /* Populate and write the frame header */
42122    nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
42123#if defined(SQLITE_HAS_CODEC)
42124    if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
42125#else
42126    pData = p->pData;
42127#endif
42128    walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
42129    rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42130    if( rc!=SQLITE_OK ){
42131      return rc;
42132    }
42133
42134    /* Write the page data */
42135    rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
42136    if( rc!=SQLITE_OK ){
42137      return rc;
42138    }
42139    pLast = p;
42140  }
42141
42142  /* Sync the log file if the 'isSync' flag was specified. */
42143  if( sync_flags ){
42144    i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
42145    i64 iOffset = walFrameOffset(iFrame+1, szPage);
42146
42147    assert( isCommit );
42148    assert( iSegment>0 );
42149
42150    iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
42151    while( iOffset<iSegment ){
42152      void *pData;
42153#if defined(SQLITE_HAS_CODEC)
42154      if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
42155#else
42156      pData = pLast->pData;
42157#endif
42158      walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
42159      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42160      if( rc!=SQLITE_OK ){
42161        return rc;
42162      }
42163      iOffset += WAL_FRAME_HDRSIZE;
42164      rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
42165      if( rc!=SQLITE_OK ){
42166        return rc;
42167      }
42168      nLast++;
42169      iOffset += szPage;
42170    }
42171
42172    rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42173  }
42174
42175  /* Append data to the wal-index. It is not necessary to lock the
42176  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
42177  ** guarantees that there are no other writers, and no data that may
42178  ** be in use by existing readers is being overwritten.
42179  */
42180  iFrame = pWal->hdr.mxFrame;
42181  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
42182    iFrame++;
42183    rc = walIndexAppend(pWal, iFrame, p->pgno);
42184  }
42185  while( nLast>0 && rc==SQLITE_OK ){
42186    iFrame++;
42187    nLast--;
42188    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
42189  }
42190
42191  if( rc==SQLITE_OK ){
42192    /* Update the private copy of the header. */
42193    pWal->hdr.szPage = szPage;
42194    pWal->hdr.mxFrame = iFrame;
42195    if( isCommit ){
42196      pWal->hdr.iChange++;
42197      pWal->hdr.nPage = nTruncate;
42198    }
42199    /* If this is a commit, update the wal-index header too. */
42200    if( isCommit ){
42201      walIndexWriteHdr(pWal);
42202      pWal->iCallback = iFrame;
42203    }
42204  }
42205
42206  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
42207  return rc;
42208}
42209
42210/*
42211** This routine is called to implement sqlite3_wal_checkpoint() and
42212** related interfaces.
42213**
42214** Obtain a CHECKPOINT lock and then backfill as much information as
42215** we can from WAL into the database.
42216*/
42217SQLITE_PRIVATE int sqlite3WalCheckpoint(
42218  Wal *pWal,                      /* Wal connection */
42219  int sync_flags,                 /* Flags to sync db file with (or 0) */
42220  int nBuf,                       /* Size of temporary buffer */
42221  u8 *zBuf                        /* Temporary buffer to use */
42222){
42223  int rc;                         /* Return code */
42224  int isChanged = 0;              /* True if a new wal-index header is loaded */
42225
42226  assert( pWal->ckptLock==0 );
42227
42228  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
42229  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
42230  if( rc ){
42231    /* Usually this is SQLITE_BUSY meaning that another thread or process
42232    ** is already running a checkpoint, or maybe a recovery.  But it might
42233    ** also be SQLITE_IOERR. */
42234    return rc;
42235  }
42236  pWal->ckptLock = 1;
42237
42238  /* Copy data from the log to the database file. */
42239  rc = walIndexReadHdr(pWal, &isChanged);
42240  if( rc==SQLITE_OK ){
42241    rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
42242  }
42243  if( isChanged ){
42244    /* If a new wal-index header was loaded before the checkpoint was
42245    ** performed, then the pager-cache associated with pWal is now
42246    ** out of date. So zero the cached wal-index header to ensure that
42247    ** next time the pager opens a snapshot on this database it knows that
42248    ** the cache needs to be reset.
42249    */
42250    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42251  }
42252
42253  /* Release the locks. */
42254  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
42255  pWal->ckptLock = 0;
42256  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
42257  return rc;
42258}
42259
42260/* Return the value to pass to a sqlite3_wal_hook callback, the
42261** number of frames in the WAL at the point of the last commit since
42262** sqlite3WalCallback() was called.  If no commits have occurred since
42263** the last call, then return 0.
42264*/
42265SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
42266  u32 ret = 0;
42267  if( pWal ){
42268    ret = pWal->iCallback;
42269    pWal->iCallback = 0;
42270  }
42271  return (int)ret;
42272}
42273
42274/*
42275** This function is called to change the WAL subsystem into or out
42276** of locking_mode=EXCLUSIVE.
42277**
42278** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
42279** into locking_mode=NORMAL.  This means that we must acquire a lock
42280** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
42281** or if the acquisition of the lock fails, then return 0.  If the
42282** transition out of exclusive-mode is successful, return 1.  This
42283** operation must occur while the pager is still holding the exclusive
42284** lock on the main database file.
42285**
42286** If op is one, then change from locking_mode=NORMAL into
42287** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
42288** be released.  Return 1 if the transition is made and 0 if the
42289** WAL is already in exclusive-locking mode - meaning that this
42290** routine is a no-op.  The pager must already hold the exclusive lock
42291** on the main database file before invoking this operation.
42292**
42293** If op is negative, then do a dry-run of the op==1 case but do
42294** not actually change anything.  The pager uses this to see if it
42295** should acquire the database exclusive lock prior to invoking
42296** the op==1 case.
42297*/
42298SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
42299  int rc;
42300  assert( pWal->writeLock==0 );
42301
42302  /* pWal->readLock is usually set, but might be -1 if there was a
42303  ** prior error while attempting to acquire are read-lock. This cannot
42304  ** happen if the connection is actually in exclusive mode (as no xShmLock
42305  ** locks are taken in this case). Nor should the pager attempt to
42306  ** upgrade to exclusive-mode following such an error.
42307  */
42308  assert( pWal->readLock>=0 || pWal->lockError );
42309  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
42310
42311  if( op==0 ){
42312    if( pWal->exclusiveMode ){
42313      pWal->exclusiveMode = 0;
42314      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
42315        pWal->exclusiveMode = 1;
42316      }
42317      rc = pWal->exclusiveMode==0;
42318    }else{
42319      /* Already in locking_mode=NORMAL */
42320      rc = 0;
42321    }
42322  }else if( op>0 ){
42323    assert( pWal->exclusiveMode==0 );
42324    assert( pWal->readLock>=0 );
42325    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42326    pWal->exclusiveMode = 1;
42327    rc = 1;
42328  }else{
42329    rc = pWal->exclusiveMode==0;
42330  }
42331  return rc;
42332}
42333
42334#endif /* #ifndef SQLITE_OMIT_WAL */
42335
42336/************** End of wal.c *************************************************/
42337/************** Begin file btmutex.c *****************************************/
42338/*
42339** 2007 August 27
42340**
42341** The author disclaims copyright to this source code.  In place of
42342** a legal notice, here is a blessing:
42343**
42344**    May you do good and not evil.
42345**    May you find forgiveness for yourself and forgive others.
42346**    May you share freely, never taking more than you give.
42347**
42348*************************************************************************
42349**
42350** This file contains code used to implement mutexes on Btree objects.
42351** This code really belongs in btree.c.  But btree.c is getting too
42352** big and we want to break it down some.  This packaged seemed like
42353** a good breakout.
42354*/
42355/************** Include btreeInt.h in the middle of btmutex.c ****************/
42356/************** Begin file btreeInt.h ****************************************/
42357/*
42358** 2004 April 6
42359**
42360** The author disclaims copyright to this source code.  In place of
42361** a legal notice, here is a blessing:
42362**
42363**    May you do good and not evil.
42364**    May you find forgiveness for yourself and forgive others.
42365**    May you share freely, never taking more than you give.
42366**
42367*************************************************************************
42368** This file implements a external (disk-based) database using BTrees.
42369** For a detailed discussion of BTrees, refer to
42370**
42371**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
42372**     "Sorting And Searching", pages 473-480. Addison-Wesley
42373**     Publishing Company, Reading, Massachusetts.
42374**
42375** The basic idea is that each page of the file contains N database
42376** entries and N+1 pointers to subpages.
42377**
42378**   ----------------------------------------------------------------
42379**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
42380**   ----------------------------------------------------------------
42381**
42382** All of the keys on the page that Ptr(0) points to have values less
42383** than Key(0).  All of the keys on page Ptr(1) and its subpages have
42384** values greater than Key(0) and less than Key(1).  All of the keys
42385** on Ptr(N) and its subpages have values greater than Key(N-1).  And
42386** so forth.
42387**
42388** Finding a particular key requires reading O(log(M)) pages from the
42389** disk where M is the number of entries in the tree.
42390**
42391** In this implementation, a single file can hold one or more separate
42392** BTrees.  Each BTree is identified by the index of its root page.  The
42393** key and data for any entry are combined to form the "payload".  A
42394** fixed amount of payload can be carried directly on the database
42395** page.  If the payload is larger than the preset amount then surplus
42396** bytes are stored on overflow pages.  The payload for an entry
42397** and the preceding pointer are combined to form a "Cell".  Each
42398** page has a small header which contains the Ptr(N) pointer and other
42399** information such as the size of key and data.
42400**
42401** FORMAT DETAILS
42402**
42403** The file is divided into pages.  The first page is called page 1,
42404** the second is page 2, and so forth.  A page number of zero indicates
42405** "no such page".  The page size can be any power of 2 between 512 and 32768.
42406** Each page can be either a btree page, a freelist page, an overflow
42407** page, or a pointer-map page.
42408**
42409** The first page is always a btree page.  The first 100 bytes of the first
42410** page contain a special header (the "file header") that describes the file.
42411** The format of the file header is as follows:
42412**
42413**   OFFSET   SIZE    DESCRIPTION
42414**      0      16     Header string: "SQLite format 3\000"
42415**     16       2     Page size in bytes.
42416**     18       1     File format write version
42417**     19       1     File format read version
42418**     20       1     Bytes of unused space at the end of each page
42419**     21       1     Max embedded payload fraction
42420**     22       1     Min embedded payload fraction
42421**     23       1     Min leaf payload fraction
42422**     24       4     File change counter
42423**     28       4     Reserved for future use
42424**     32       4     First freelist page
42425**     36       4     Number of freelist pages in the file
42426**     40      60     15 4-byte meta values passed to higher layers
42427**
42428**     40       4     Schema cookie
42429**     44       4     File format of schema layer
42430**     48       4     Size of page cache
42431**     52       4     Largest root-page (auto/incr_vacuum)
42432**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
42433**     60       4     User version
42434**     64       4     Incremental vacuum mode
42435**     68       4     unused
42436**     72       4     unused
42437**     76       4     unused
42438**
42439** All of the integer values are big-endian (most significant byte first).
42440**
42441** The file change counter is incremented when the database is changed
42442** This counter allows other processes to know when the file has changed
42443** and thus when they need to flush their cache.
42444**
42445** The max embedded payload fraction is the amount of the total usable
42446** space in a page that can be consumed by a single cell for standard
42447** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
42448** is to limit the maximum cell size so that at least 4 cells will fit
42449** on one page.  Thus the default max embedded payload fraction is 64.
42450**
42451** If the payload for a cell is larger than the max payload, then extra
42452** payload is spilled to overflow pages.  Once an overflow page is allocated,
42453** as many bytes as possible are moved into the overflow pages without letting
42454** the cell size drop below the min embedded payload fraction.
42455**
42456** The min leaf payload fraction is like the min embedded payload fraction
42457** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
42458** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
42459** not specified in the header.
42460**
42461** Each btree pages is divided into three sections:  The header, the
42462** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
42463** file header that occurs before the page header.
42464**
42465**      |----------------|
42466**      | file header    |   100 bytes.  Page 1 only.
42467**      |----------------|
42468**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
42469**      |----------------|
42470**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
42471**      | array          |   |  Grows downward
42472**      |                |   v
42473**      |----------------|
42474**      | unallocated    |
42475**      | space          |
42476**      |----------------|   ^  Grows upwards
42477**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
42478**      | area           |   |  and free space fragments.
42479**      |----------------|
42480**
42481** The page headers looks like this:
42482**
42483**   OFFSET   SIZE     DESCRIPTION
42484**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
42485**      1       2      byte offset to the first freeblock
42486**      3       2      number of cells on this page
42487**      5       2      first byte of the cell content area
42488**      7       1      number of fragmented free bytes
42489**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
42490**
42491** The flags define the format of this btree page.  The leaf flag means that
42492** this page has no children.  The zerodata flag means that this page carries
42493** only keys and no data.  The intkey flag means that the key is a integer
42494** which is stored in the key size entry of the cell header rather than in
42495** the payload area.
42496**
42497** The cell pointer array begins on the first byte after the page header.
42498** The cell pointer array contains zero or more 2-byte numbers which are
42499** offsets from the beginning of the page to the cell content in the cell
42500** content area.  The cell pointers occur in sorted order.  The system strives
42501** to keep free space after the last cell pointer so that new cells can
42502** be easily added without having to defragment the page.
42503**
42504** Cell content is stored at the very end of the page and grows toward the
42505** beginning of the page.
42506**
42507** Unused space within the cell content area is collected into a linked list of
42508** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
42509** to the first freeblock is given in the header.  Freeblocks occur in
42510** increasing order.  Because a freeblock must be at least 4 bytes in size,
42511** any group of 3 or fewer unused bytes in the cell content area cannot
42512** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
42513** a fragment.  The total number of bytes in all fragments is recorded.
42514** in the page header at offset 7.
42515**
42516**    SIZE    DESCRIPTION
42517**      2     Byte offset of the next freeblock
42518**      2     Bytes in this freeblock
42519**
42520** Cells are of variable length.  Cells are stored in the cell content area at
42521** the end of the page.  Pointers to the cells are in the cell pointer array
42522** that immediately follows the page header.  Cells is not necessarily
42523** contiguous or in order, but cell pointers are contiguous and in order.
42524**
42525** Cell content makes use of variable length integers.  A variable
42526** length integer is 1 to 9 bytes where the lower 7 bits of each
42527** byte are used.  The integer consists of all bytes that have bit 8 set and
42528** the first byte with bit 8 clear.  The most significant byte of the integer
42529** appears first.  A variable-length integer may not be more than 9 bytes long.
42530** As a special case, all 8 bytes of the 9th byte are used as data.  This
42531** allows a 64-bit integer to be encoded in 9 bytes.
42532**
42533**    0x00                      becomes  0x00000000
42534**    0x7f                      becomes  0x0000007f
42535**    0x81 0x00                 becomes  0x00000080
42536**    0x82 0x00                 becomes  0x00000100
42537**    0x80 0x7f                 becomes  0x0000007f
42538**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
42539**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
42540**
42541** Variable length integers are used for rowids and to hold the number of
42542** bytes of key and data in a btree cell.
42543**
42544** The content of a cell looks like this:
42545**
42546**    SIZE    DESCRIPTION
42547**      4     Page number of the left child. Omitted if leaf flag is set.
42548**     var    Number of bytes of data. Omitted if the zerodata flag is set.
42549**     var    Number of bytes of key. Or the key itself if intkey flag is set.
42550**      *     Payload
42551**      4     First page of the overflow chain.  Omitted if no overflow
42552**
42553** Overflow pages form a linked list.  Each page except the last is completely
42554** filled with data (pagesize - 4 bytes).  The last page can have as little
42555** as 1 byte of data.
42556**
42557**    SIZE    DESCRIPTION
42558**      4     Page number of next overflow page
42559**      *     Data
42560**
42561** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
42562** file header points to the first in a linked list of trunk page.  Each trunk
42563** page points to multiple leaf pages.  The content of a leaf page is
42564** unspecified.  A trunk page looks like this:
42565**
42566**    SIZE    DESCRIPTION
42567**      4     Page number of next trunk page
42568**      4     Number of leaf pointers on this page
42569**      *     zero or more pages numbers of leaves
42570*/
42571
42572
42573/* The following value is the maximum cell size assuming a maximum page
42574** size give above.
42575*/
42576#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
42577
42578/* The maximum number of cells on a single page of the database.  This
42579** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
42580** plus 2 bytes for the index to the cell in the page header).  Such
42581** small cells will be rare, but they are possible.
42582*/
42583#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
42584
42585/* Forward declarations */
42586typedef struct MemPage MemPage;
42587typedef struct BtLock BtLock;
42588
42589/*
42590** This is a magic string that appears at the beginning of every
42591** SQLite database in order to identify the file as a real database.
42592**
42593** You can change this value at compile-time by specifying a
42594** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
42595** header must be exactly 16 bytes including the zero-terminator so
42596** the string itself should be 15 characters long.  If you change
42597** the header, then your custom library will not be able to read
42598** databases generated by the standard tools and the standard tools
42599** will not be able to read databases created by your custom library.
42600*/
42601#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
42602#  define SQLITE_FILE_HEADER "SQLite format 3"
42603#endif
42604
42605/*
42606** Page type flags.  An ORed combination of these flags appear as the
42607** first byte of on-disk image of every BTree page.
42608*/
42609#define PTF_INTKEY    0x01
42610#define PTF_ZERODATA  0x02
42611#define PTF_LEAFDATA  0x04
42612#define PTF_LEAF      0x08
42613
42614/*
42615** As each page of the file is loaded into memory, an instance of the following
42616** structure is appended and initialized to zero.  This structure stores
42617** information about the page that is decoded from the raw file page.
42618**
42619** The pParent field points back to the parent page.  This allows us to
42620** walk up the BTree from any leaf to the root.  Care must be taken to
42621** unref() the parent page pointer when this page is no longer referenced.
42622** The pageDestructor() routine handles that chore.
42623**
42624** Access to all fields of this structure is controlled by the mutex
42625** stored in MemPage.pBt->mutex.
42626*/
42627struct MemPage {
42628  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
42629  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
42630  u8 intKey;           /* True if intkey flag is set */
42631  u8 leaf;             /* True if leaf flag is set */
42632  u8 hasData;          /* True if this page stores data */
42633  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
42634  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
42635  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
42636  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
42637  u16 cellOffset;      /* Index in aData of first cell pointer */
42638  u16 nFree;           /* Number of free bytes on the page */
42639  u16 nCell;           /* Number of cells on this page, local and ovfl */
42640  u16 maskPage;        /* Mask for page offset */
42641  struct _OvflCell {   /* Cells that will not fit on aData[] */
42642    u8 *pCell;          /* Pointers to the body of the overflow cell */
42643    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
42644  } aOvfl[5];
42645  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
42646  u8 *aData;           /* Pointer to disk image of the page data */
42647  DbPage *pDbPage;     /* Pager page handle */
42648  Pgno pgno;           /* Page number for this page */
42649};
42650
42651/*
42652** The in-memory image of a disk page has the auxiliary information appended
42653** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
42654** that extra information.
42655*/
42656#define EXTRA_SIZE sizeof(MemPage)
42657
42658/*
42659** A linked list of the following structures is stored at BtShared.pLock.
42660** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
42661** is opened on the table with root page BtShared.iTable. Locks are removed
42662** from this list when a transaction is committed or rolled back, or when
42663** a btree handle is closed.
42664*/
42665struct BtLock {
42666  Btree *pBtree;        /* Btree handle holding this lock */
42667  Pgno iTable;          /* Root page of table */
42668  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
42669  BtLock *pNext;        /* Next in BtShared.pLock list */
42670};
42671
42672/* Candidate values for BtLock.eLock */
42673#define READ_LOCK     1
42674#define WRITE_LOCK    2
42675
42676/* A Btree handle
42677**
42678** A database connection contains a pointer to an instance of
42679** this object for every database file that it has open.  This structure
42680** is opaque to the database connection.  The database connection cannot
42681** see the internals of this structure and only deals with pointers to
42682** this structure.
42683**
42684** For some database files, the same underlying database cache might be
42685** shared between multiple connections.  In that case, each connection
42686** has it own instance of this object.  But each instance of this object
42687** points to the same BtShared object.  The database cache and the
42688** schema associated with the database file are all contained within
42689** the BtShared object.
42690**
42691** All fields in this structure are accessed under sqlite3.mutex.
42692** The pBt pointer itself may not be changed while there exists cursors
42693** in the referenced BtShared that point back to this Btree since those
42694** cursors have to do go through this Btree to find their BtShared and
42695** they often do so without holding sqlite3.mutex.
42696*/
42697struct Btree {
42698  sqlite3 *db;       /* The database connection holding this btree */
42699  BtShared *pBt;     /* Sharable content of this btree */
42700  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
42701  u8 sharable;       /* True if we can share pBt with another db */
42702  u8 locked;         /* True if db currently has pBt locked */
42703  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
42704  int nBackup;       /* Number of backup operations reading this btree */
42705  Btree *pNext;      /* List of other sharable Btrees from the same db */
42706  Btree *pPrev;      /* Back pointer of the same list */
42707#ifndef SQLITE_OMIT_SHARED_CACHE
42708  BtLock lock;       /* Object used to lock page 1 */
42709#endif
42710};
42711
42712/*
42713** Btree.inTrans may take one of the following values.
42714**
42715** If the shared-data extension is enabled, there may be multiple users
42716** of the Btree structure. At most one of these may open a write transaction,
42717** but any number may have active read transactions.
42718*/
42719#define TRANS_NONE  0
42720#define TRANS_READ  1
42721#define TRANS_WRITE 2
42722
42723/*
42724** An instance of this object represents a single database file.
42725**
42726** A single database file can be in use as the same time by two
42727** or more database connections.  When two or more connections are
42728** sharing the same database file, each connection has it own
42729** private Btree object for the file and each of those Btrees points
42730** to this one BtShared object.  BtShared.nRef is the number of
42731** connections currently sharing this database file.
42732**
42733** Fields in this structure are accessed under the BtShared.mutex
42734** mutex, except for nRef and pNext which are accessed under the
42735** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
42736** may not be modified once it is initially set as long as nRef>0.
42737** The pSchema field may be set once under BtShared.mutex and
42738** thereafter is unchanged as long as nRef>0.
42739**
42740** isPending:
42741**
42742**   If a BtShared client fails to obtain a write-lock on a database
42743**   table (because there exists one or more read-locks on the table),
42744**   the shared-cache enters 'pending-lock' state and isPending is
42745**   set to true.
42746**
42747**   The shared-cache leaves the 'pending lock' state when either of
42748**   the following occur:
42749**
42750**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
42751**     2) The number of locks held by other connections drops to zero.
42752**
42753**   while in the 'pending-lock' state, no connection may start a new
42754**   transaction.
42755**
42756**   This feature is included to help prevent writer-starvation.
42757*/
42758struct BtShared {
42759  Pager *pPager;        /* The page cache */
42760  sqlite3 *db;          /* Database connection currently using this Btree */
42761  BtCursor *pCursor;    /* A list of all open cursors */
42762  MemPage *pPage1;      /* First page of the database */
42763  u8 readOnly;          /* True if the underlying file is readonly */
42764  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
42765  u8 secureDelete;      /* True if secure_delete is enabled */
42766  u8 initiallyEmpty;    /* Database is empty at start of transaction */
42767#ifndef SQLITE_OMIT_AUTOVACUUM
42768  u8 autoVacuum;        /* True if auto-vacuum is enabled */
42769  u8 incrVacuum;        /* True if incr-vacuum is enabled */
42770#endif
42771  u16 pageSize;         /* Total number of bytes on a page */
42772  u16 usableSize;       /* Number of usable bytes on each page */
42773  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
42774  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
42775  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
42776  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
42777  u8 inTransaction;     /* Transaction state */
42778  u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
42779  int nTransaction;     /* Number of open transactions (read + write) */
42780  u32 nPage;            /* Number of pages in the database */
42781  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
42782  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
42783  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
42784  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
42785#ifndef SQLITE_OMIT_SHARED_CACHE
42786  int nRef;             /* Number of references to this structure */
42787  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
42788  BtLock *pLock;        /* List of locks held on this shared-btree struct */
42789  Btree *pWriter;       /* Btree with currently open write transaction */
42790  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
42791  u8 isPending;         /* If waiting for read-locks to clear */
42792#endif
42793  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
42794};
42795
42796/*
42797** An instance of the following structure is used to hold information
42798** about a cell.  The parseCellPtr() function fills in this structure
42799** based on information extract from the raw disk page.
42800*/
42801typedef struct CellInfo CellInfo;
42802struct CellInfo {
42803  u8 *pCell;     /* Pointer to the start of cell content */
42804  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
42805  u32 nData;     /* Number of bytes of data */
42806  u32 nPayload;  /* Total amount of payload */
42807  u16 nHeader;   /* Size of the cell content header in bytes */
42808  u16 nLocal;    /* Amount of payload held locally */
42809  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
42810  u16 nSize;     /* Size of the cell content on the main b-tree page */
42811};
42812
42813/*
42814** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
42815** this will be declared corrupt. This value is calculated based on a
42816** maximum database size of 2^31 pages a minimum fanout of 2 for a
42817** root-node and 3 for all other internal nodes.
42818**
42819** If a tree that appears to be taller than this is encountered, it is
42820** assumed that the database is corrupt.
42821*/
42822#define BTCURSOR_MAX_DEPTH 20
42823
42824/*
42825** A cursor is a pointer to a particular entry within a particular
42826** b-tree within a database file.
42827**
42828** The entry is identified by its MemPage and the index in
42829** MemPage.aCell[] of the entry.
42830**
42831** A single database file can shared by two more database connections,
42832** but cursors cannot be shared.  Each cursor is associated with a
42833** particular database connection identified BtCursor.pBtree.db.
42834**
42835** Fields in this structure are accessed under the BtShared.mutex
42836** found at self->pBt->mutex.
42837*/
42838struct BtCursor {
42839  Btree *pBtree;            /* The Btree to which this cursor belongs */
42840  BtShared *pBt;            /* The BtShared this cursor points to */
42841  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
42842  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
42843  Pgno pgnoRoot;            /* The root page of this tree */
42844  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
42845  CellInfo info;            /* A parse of the cell we are pointing at */
42846  u8 wrFlag;                /* True if writable */
42847  u8 atLast;                /* Cursor pointing to the last entry */
42848  u8 validNKey;             /* True if info.nKey is valid */
42849  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
42850  void *pKey;      /* Saved key that was cursor's last known position */
42851  i64 nKey;        /* Size of pKey, or last integer key */
42852  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
42853#ifndef SQLITE_OMIT_INCRBLOB
42854  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
42855  Pgno *aOverflow;          /* Cache of overflow page locations */
42856#endif
42857  i16 iPage;                            /* Index of current page in apPage */
42858  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
42859  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
42860};
42861
42862/*
42863** Potential values for BtCursor.eState.
42864**
42865** CURSOR_VALID:
42866**   Cursor points to a valid entry. getPayload() etc. may be called.
42867**
42868** CURSOR_INVALID:
42869**   Cursor does not point to a valid entry. This can happen (for example)
42870**   because the table is empty or because BtreeCursorFirst() has not been
42871**   called.
42872**
42873** CURSOR_REQUIRESEEK:
42874**   The table that this cursor was opened on still exists, but has been
42875**   modified since the cursor was last used. The cursor position is saved
42876**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
42877**   this state, restoreCursorPosition() can be called to attempt to
42878**   seek the cursor to the saved position.
42879**
42880** CURSOR_FAULT:
42881**   A unrecoverable error (an I/O error or a malloc failure) has occurred
42882**   on a different connection that shares the BtShared cache with this
42883**   cursor.  The error has left the cache in an inconsistent state.
42884**   Do nothing else with this cursor.  Any attempt to use the cursor
42885**   should return the error code stored in BtCursor.skip
42886*/
42887#define CURSOR_INVALID           0
42888#define CURSOR_VALID             1
42889#define CURSOR_REQUIRESEEK       2
42890#define CURSOR_FAULT             3
42891
42892/*
42893** The database page the PENDING_BYTE occupies. This page is never used.
42894*/
42895# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
42896
42897/*
42898** These macros define the location of the pointer-map entry for a
42899** database page. The first argument to each is the number of usable
42900** bytes on each page of the database (often 1024). The second is the
42901** page number to look up in the pointer map.
42902**
42903** PTRMAP_PAGENO returns the database page number of the pointer-map
42904** page that stores the required pointer. PTRMAP_PTROFFSET returns
42905** the offset of the requested map entry.
42906**
42907** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
42908** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
42909** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
42910** this test.
42911*/
42912#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
42913#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
42914#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
42915
42916/*
42917** The pointer map is a lookup table that identifies the parent page for
42918** each child page in the database file.  The parent page is the page that
42919** contains a pointer to the child.  Every page in the database contains
42920** 0 or 1 parent pages.  (In this context 'database page' refers
42921** to any page that is not part of the pointer map itself.)  Each pointer map
42922** entry consists of a single byte 'type' and a 4 byte parent page number.
42923** The PTRMAP_XXX identifiers below are the valid types.
42924**
42925** The purpose of the pointer map is to facility moving pages from one
42926** position in the file to another as part of autovacuum.  When a page
42927** is moved, the pointer in its parent must be updated to point to the
42928** new location.  The pointer map is used to locate the parent page quickly.
42929**
42930** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
42931**                  used in this case.
42932**
42933** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
42934**                  is not used in this case.
42935**
42936** PTRMAP_OVERFLOW1: The database page is the first page in a list of
42937**                   overflow pages. The page number identifies the page that
42938**                   contains the cell with a pointer to this overflow page.
42939**
42940** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
42941**                   overflow pages. The page-number identifies the previous
42942**                   page in the overflow page list.
42943**
42944** PTRMAP_BTREE: The database page is a non-root btree page. The page number
42945**               identifies the parent page in the btree.
42946*/
42947#define PTRMAP_ROOTPAGE 1
42948#define PTRMAP_FREEPAGE 2
42949#define PTRMAP_OVERFLOW1 3
42950#define PTRMAP_OVERFLOW2 4
42951#define PTRMAP_BTREE 5
42952
42953/* A bunch of assert() statements to check the transaction state variables
42954** of handle p (type Btree*) are internally consistent.
42955*/
42956#define btreeIntegrity(p) \
42957  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
42958  assert( p->pBt->inTransaction>=p->inTrans );
42959
42960
42961/*
42962** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
42963** if the database supports auto-vacuum or not. Because it is used
42964** within an expression that is an argument to another macro
42965** (sqliteMallocRaw), it is not possible to use conditional compilation.
42966** So, this macro is defined instead.
42967*/
42968#ifndef SQLITE_OMIT_AUTOVACUUM
42969#define ISAUTOVACUUM (pBt->autoVacuum)
42970#else
42971#define ISAUTOVACUUM 0
42972#endif
42973
42974
42975/*
42976** This structure is passed around through all the sanity checking routines
42977** in order to keep track of some global state information.
42978*/
42979typedef struct IntegrityCk IntegrityCk;
42980struct IntegrityCk {
42981  BtShared *pBt;    /* The tree being checked out */
42982  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
42983  Pgno nPage;       /* Number of pages in the database */
42984  int *anRef;       /* Number of times each page is referenced */
42985  int mxErr;        /* Stop accumulating errors when this reaches zero */
42986  int nErr;         /* Number of messages written to zErrMsg so far */
42987  int mallocFailed; /* A memory allocation error has occurred */
42988  StrAccum errMsg;  /* Accumulate the error message text here */
42989};
42990
42991/*
42992** Read or write a two- and four-byte big-endian integer values.
42993*/
42994#define get2byte(x)   ((x)[0]<<8 | (x)[1])
42995#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
42996#define get4byte sqlite3Get4byte
42997#define put4byte sqlite3Put4byte
42998
42999/************** End of btreeInt.h ********************************************/
43000/************** Continuing where we left off in btmutex.c ********************/
43001#ifndef SQLITE_OMIT_SHARED_CACHE
43002#if SQLITE_THREADSAFE
43003
43004/*
43005** Obtain the BtShared mutex associated with B-Tree handle p. Also,
43006** set BtShared.db to the database handle associated with p and the
43007** p->locked boolean to true.
43008*/
43009static void lockBtreeMutex(Btree *p){
43010  assert( p->locked==0 );
43011  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
43012  assert( sqlite3_mutex_held(p->db->mutex) );
43013
43014  sqlite3_mutex_enter(p->pBt->mutex);
43015  p->pBt->db = p->db;
43016  p->locked = 1;
43017}
43018
43019/*
43020** Release the BtShared mutex associated with B-Tree handle p and
43021** clear the p->locked boolean.
43022*/
43023static void unlockBtreeMutex(Btree *p){
43024  assert( p->locked==1 );
43025  assert( sqlite3_mutex_held(p->pBt->mutex) );
43026  assert( sqlite3_mutex_held(p->db->mutex) );
43027  assert( p->db==p->pBt->db );
43028
43029  sqlite3_mutex_leave(p->pBt->mutex);
43030  p->locked = 0;
43031}
43032
43033/*
43034** Enter a mutex on the given BTree object.
43035**
43036** If the object is not sharable, then no mutex is ever required
43037** and this routine is a no-op.  The underlying mutex is non-recursive.
43038** But we keep a reference count in Btree.wantToLock so the behavior
43039** of this interface is recursive.
43040**
43041** To avoid deadlocks, multiple Btrees are locked in the same order
43042** by all database connections.  The p->pNext is a list of other
43043** Btrees belonging to the same database connection as the p Btree
43044** which need to be locked after p.  If we cannot get a lock on
43045** p, then first unlock all of the others on p->pNext, then wait
43046** for the lock to become available on p, then relock all of the
43047** subsequent Btrees that desire a lock.
43048*/
43049SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43050  Btree *pLater;
43051
43052  /* Some basic sanity checking on the Btree.  The list of Btrees
43053  ** connected by pNext and pPrev should be in sorted order by
43054  ** Btree.pBt value. All elements of the list should belong to
43055  ** the same connection. Only shared Btrees are on the list. */
43056  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
43057  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
43058  assert( p->pNext==0 || p->pNext->db==p->db );
43059  assert( p->pPrev==0 || p->pPrev->db==p->db );
43060  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
43061
43062  /* Check for locking consistency */
43063  assert( !p->locked || p->wantToLock>0 );
43064  assert( p->sharable || p->wantToLock==0 );
43065
43066  /* We should already hold a lock on the database connection */
43067  assert( sqlite3_mutex_held(p->db->mutex) );
43068
43069  /* Unless the database is sharable and unlocked, then BtShared.db
43070  ** should already be set correctly. */
43071  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43072
43073  if( !p->sharable ) return;
43074  p->wantToLock++;
43075  if( p->locked ) return;
43076
43077  /* In most cases, we should be able to acquire the lock we
43078  ** want without having to go throught the ascending lock
43079  ** procedure that follows.  Just be sure not to block.
43080  */
43081  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
43082    p->pBt->db = p->db;
43083    p->locked = 1;
43084    return;
43085  }
43086
43087  /* To avoid deadlock, first release all locks with a larger
43088  ** BtShared address.  Then acquire our lock.  Then reacquire
43089  ** the other BtShared locks that we used to hold in ascending
43090  ** order.
43091  */
43092  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43093    assert( pLater->sharable );
43094    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
43095    assert( !pLater->locked || pLater->wantToLock>0 );
43096    if( pLater->locked ){
43097      unlockBtreeMutex(pLater);
43098    }
43099  }
43100  lockBtreeMutex(p);
43101  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43102    if( pLater->wantToLock ){
43103      lockBtreeMutex(pLater);
43104    }
43105  }
43106}
43107
43108/*
43109** Exit the recursive mutex on a Btree.
43110*/
43111SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
43112  if( p->sharable ){
43113    assert( p->wantToLock>0 );
43114    p->wantToLock--;
43115    if( p->wantToLock==0 ){
43116      unlockBtreeMutex(p);
43117    }
43118  }
43119}
43120
43121#ifndef NDEBUG
43122/*
43123** Return true if the BtShared mutex is held on the btree, or if the
43124** B-Tree is not marked as sharable.
43125**
43126** This routine is used only from within assert() statements.
43127*/
43128SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
43129  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
43130  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
43131  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
43132  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
43133
43134  return (p->sharable==0 || p->locked);
43135}
43136#endif
43137
43138
43139#ifndef SQLITE_OMIT_INCRBLOB
43140/*
43141** Enter and leave a mutex on a Btree given a cursor owned by that
43142** Btree.  These entry points are used by incremental I/O and can be
43143** omitted if that module is not used.
43144*/
43145SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
43146  sqlite3BtreeEnter(pCur->pBtree);
43147}
43148SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
43149  sqlite3BtreeLeave(pCur->pBtree);
43150}
43151#endif /* SQLITE_OMIT_INCRBLOB */
43152
43153
43154/*
43155** Enter the mutex on every Btree associated with a database
43156** connection.  This is needed (for example) prior to parsing
43157** a statement since we will be comparing table and column names
43158** against all schemas and we do not want those schemas being
43159** reset out from under us.
43160**
43161** There is a corresponding leave-all procedures.
43162**
43163** Enter the mutexes in accending order by BtShared pointer address
43164** to avoid the possibility of deadlock when two threads with
43165** two or more btrees in common both try to lock all their btrees
43166** at the same instant.
43167*/
43168SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43169  int i;
43170  Btree *p, *pLater;
43171  assert( sqlite3_mutex_held(db->mutex) );
43172  for(i=0; i<db->nDb; i++){
43173    p = db->aDb[i].pBt;
43174    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43175    if( p && p->sharable ){
43176      p->wantToLock++;
43177      if( !p->locked ){
43178        assert( p->wantToLock==1 );
43179        while( p->pPrev ) p = p->pPrev;
43180        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
43181        ** the chain.  Otherwise the !p->locked test above would have failed */
43182        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
43183        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
43184          if( pLater->locked ){
43185            unlockBtreeMutex(pLater);
43186          }
43187        }
43188        while( p ){
43189          lockBtreeMutex(p);
43190          p = p->pNext;
43191        }
43192      }
43193    }
43194  }
43195}
43196SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
43197  int i;
43198  Btree *p;
43199  assert( sqlite3_mutex_held(db->mutex) );
43200  for(i=0; i<db->nDb; i++){
43201    p = db->aDb[i].pBt;
43202    if( p && p->sharable ){
43203      assert( p->wantToLock>0 );
43204      p->wantToLock--;
43205      if( p->wantToLock==0 ){
43206        unlockBtreeMutex(p);
43207      }
43208    }
43209  }
43210}
43211
43212#ifndef NDEBUG
43213/*
43214** Return true if the current thread holds the database connection
43215** mutex and all required BtShared mutexes.
43216**
43217** This routine is used inside assert() statements only.
43218*/
43219SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
43220  int i;
43221  if( !sqlite3_mutex_held(db->mutex) ){
43222    return 0;
43223  }
43224  for(i=0; i<db->nDb; i++){
43225    Btree *p;
43226    p = db->aDb[i].pBt;
43227    if( p && p->sharable &&
43228         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
43229      return 0;
43230    }
43231  }
43232  return 1;
43233}
43234#endif /* NDEBUG */
43235
43236/*
43237** Add a new Btree pointer to a BtreeMutexArray.
43238** if the pointer can possibly be shared with
43239** another database connection.
43240**
43241** The pointers are kept in sorted order by pBtree->pBt.  That
43242** way when we go to enter all the mutexes, we can enter them
43243** in order without every having to backup and retry and without
43244** worrying about deadlock.
43245**
43246** The number of shared btrees will always be small (usually 0 or 1)
43247** so an insertion sort is an adequate algorithm here.
43248*/
43249SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
43250  int i, j;
43251  BtShared *pBt;
43252  if( pBtree==0 || pBtree->sharable==0 ) return;
43253#ifndef NDEBUG
43254  {
43255    for(i=0; i<pArray->nMutex; i++){
43256      assert( pArray->aBtree[i]!=pBtree );
43257    }
43258  }
43259#endif
43260  assert( pArray->nMutex>=0 );
43261  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
43262  pBt = pBtree->pBt;
43263  for(i=0; i<pArray->nMutex; i++){
43264    assert( pArray->aBtree[i]!=pBtree );
43265    if( pArray->aBtree[i]->pBt>pBt ){
43266      for(j=pArray->nMutex; j>i; j--){
43267        pArray->aBtree[j] = pArray->aBtree[j-1];
43268      }
43269      pArray->aBtree[i] = pBtree;
43270      pArray->nMutex++;
43271      return;
43272    }
43273  }
43274  pArray->aBtree[pArray->nMutex++] = pBtree;
43275}
43276
43277/*
43278** Enter the mutex of every btree in the array.  This routine is
43279** called at the beginning of sqlite3VdbeExec().  The mutexes are
43280** exited at the end of the same function.
43281*/
43282SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
43283  int i;
43284  for(i=0; i<pArray->nMutex; i++){
43285    Btree *p = pArray->aBtree[i];
43286    /* Some basic sanity checking */
43287    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43288    assert( !p->locked || p->wantToLock>0 );
43289
43290    /* We should already hold a lock on the database connection */
43291    assert( sqlite3_mutex_held(p->db->mutex) );
43292
43293    /* The Btree is sharable because only sharable Btrees are entered
43294    ** into the array in the first place. */
43295    assert( p->sharable );
43296
43297    p->wantToLock++;
43298    if( !p->locked ){
43299      lockBtreeMutex(p);
43300    }
43301  }
43302}
43303
43304/*
43305** Leave the mutex of every btree in the group.
43306*/
43307SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
43308  int i;
43309  for(i=0; i<pArray->nMutex; i++){
43310    Btree *p = pArray->aBtree[i];
43311    /* Some basic sanity checking */
43312    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43313    assert( p->locked );
43314    assert( p->wantToLock>0 );
43315
43316    /* We should already hold a lock on the database connection */
43317    assert( sqlite3_mutex_held(p->db->mutex) );
43318
43319    p->wantToLock--;
43320    if( p->wantToLock==0 ){
43321      unlockBtreeMutex(p);
43322    }
43323  }
43324}
43325
43326#else
43327SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43328  p->pBt->db = p->db;
43329}
43330SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43331  int i;
43332  for(i=0; i<db->nDb; i++){
43333    Btree *p = db->aDb[i].pBt;
43334    if( p ){
43335      p->pBt->db = p->db;
43336    }
43337  }
43338}
43339#endif /* if SQLITE_THREADSAFE */
43340#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
43341
43342/************** End of btmutex.c *********************************************/
43343/************** Begin file btree.c *******************************************/
43344/*
43345** 2004 April 6
43346**
43347** The author disclaims copyright to this source code.  In place of
43348** a legal notice, here is a blessing:
43349**
43350**    May you do good and not evil.
43351**    May you find forgiveness for yourself and forgive others.
43352**    May you share freely, never taking more than you give.
43353**
43354*************************************************************************
43355** This file implements a external (disk-based) database using BTrees.
43356** See the header comment on "btreeInt.h" for additional information.
43357** Including a description of file format and an overview of operation.
43358*/
43359
43360/*
43361** The header string that appears at the beginning of every
43362** SQLite database.
43363*/
43364static const char zMagicHeader[] = SQLITE_FILE_HEADER;
43365
43366/*
43367** Set this global variable to 1 to enable tracing using the TRACE
43368** macro.
43369*/
43370#if 0
43371int sqlite3BtreeTrace=1;  /* True to enable tracing */
43372# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
43373#else
43374# define TRACE(X)
43375#endif
43376
43377
43378
43379#ifndef SQLITE_OMIT_SHARED_CACHE
43380/*
43381** A list of BtShared objects that are eligible for participation
43382** in shared cache.  This variable has file scope during normal builds,
43383** but the test harness needs to access it so we make it global for
43384** test builds.
43385**
43386** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
43387*/
43388#ifdef SQLITE_TEST
43389SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43390#else
43391static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43392#endif
43393#endif /* SQLITE_OMIT_SHARED_CACHE */
43394
43395#ifndef SQLITE_OMIT_SHARED_CACHE
43396/*
43397** Enable or disable the shared pager and schema features.
43398**
43399** This routine has no effect on existing database connections.
43400** The shared cache setting effects only future calls to
43401** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
43402*/
43403SQLITE_API int sqlite3_enable_shared_cache(int enable){
43404  sqlite3GlobalConfig.sharedCacheEnabled = enable;
43405  return SQLITE_OK;
43406}
43407#endif
43408
43409
43410
43411#ifdef SQLITE_OMIT_SHARED_CACHE
43412  /*
43413  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
43414  ** and clearAllSharedCacheTableLocks()
43415  ** manipulate entries in the BtShared.pLock linked list used to store
43416  ** shared-cache table level locks. If the library is compiled with the
43417  ** shared-cache feature disabled, then there is only ever one user
43418  ** of each BtShared structure and so this locking is not necessary.
43419  ** So define the lock related functions as no-ops.
43420  */
43421  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
43422  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
43423  #define clearAllSharedCacheTableLocks(a)
43424  #define downgradeAllSharedCacheTableLocks(a)
43425  #define hasSharedCacheTableLock(a,b,c,d) 1
43426  #define hasReadConflicts(a, b) 0
43427#endif
43428
43429#ifndef SQLITE_OMIT_SHARED_CACHE
43430
43431#ifdef SQLITE_DEBUG
43432/*
43433**** This function is only used as part of an assert() statement. ***
43434**
43435** Check to see if pBtree holds the required locks to read or write to the
43436** table with root page iRoot.   Return 1 if it does and 0 if not.
43437**
43438** For example, when writing to a table with root-page iRoot via
43439** Btree connection pBtree:
43440**
43441**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
43442**
43443** When writing to an index that resides in a sharable database, the
43444** caller should have first obtained a lock specifying the root page of
43445** the corresponding table. This makes things a bit more complicated,
43446** as this module treats each table as a separate structure. To determine
43447** the table corresponding to the index being written, this
43448** function has to search through the database schema.
43449**
43450** Instead of a lock on the table/index rooted at page iRoot, the caller may
43451** hold a write-lock on the schema table (root page 1). This is also
43452** acceptable.
43453*/
43454static int hasSharedCacheTableLock(
43455  Btree *pBtree,         /* Handle that must hold lock */
43456  Pgno iRoot,            /* Root page of b-tree */
43457  int isIndex,           /* True if iRoot is the root of an index b-tree */
43458  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
43459){
43460  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
43461  Pgno iTab = 0;
43462  BtLock *pLock;
43463
43464  /* If this database is not shareable, or if the client is reading
43465  ** and has the read-uncommitted flag set, then no lock is required.
43466  ** Return true immediately.
43467  */
43468  if( (pBtree->sharable==0)
43469   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
43470  ){
43471    return 1;
43472  }
43473
43474  /* If the client is reading  or writing an index and the schema is
43475  ** not loaded, then it is too difficult to actually check to see if
43476  ** the correct locks are held.  So do not bother - just return true.
43477  ** This case does not come up very often anyhow.
43478  */
43479  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
43480    return 1;
43481  }
43482
43483  /* Figure out the root-page that the lock should be held on. For table
43484  ** b-trees, this is just the root page of the b-tree being read or
43485  ** written. For index b-trees, it is the root page of the associated
43486  ** table.  */
43487  if( isIndex ){
43488    HashElem *p;
43489    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
43490      Index *pIdx = (Index *)sqliteHashData(p);
43491      if( pIdx->tnum==(int)iRoot ){
43492        iTab = pIdx->pTable->tnum;
43493      }
43494    }
43495  }else{
43496    iTab = iRoot;
43497  }
43498
43499  /* Search for the required lock. Either a write-lock on root-page iTab, a
43500  ** write-lock on the schema table, or (if the client is reading) a
43501  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
43502  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
43503    if( pLock->pBtree==pBtree
43504     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
43505     && pLock->eLock>=eLockType
43506    ){
43507      return 1;
43508    }
43509  }
43510
43511  /* Failed to find the required lock. */
43512  return 0;
43513}
43514#endif /* SQLITE_DEBUG */
43515
43516#ifdef SQLITE_DEBUG
43517/*
43518**** This function may be used as part of assert() statements only. ****
43519**
43520** Return true if it would be illegal for pBtree to write into the
43521** table or index rooted at iRoot because other shared connections are
43522** simultaneously reading that same table or index.
43523**
43524** It is illegal for pBtree to write if some other Btree object that
43525** shares the same BtShared object is currently reading or writing
43526** the iRoot table.  Except, if the other Btree object has the
43527** read-uncommitted flag set, then it is OK for the other object to
43528** have a read cursor.
43529**
43530** For example, before writing to any part of the table or index
43531** rooted at page iRoot, one should call:
43532**
43533**    assert( !hasReadConflicts(pBtree, iRoot) );
43534*/
43535static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
43536  BtCursor *p;
43537  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
43538    if( p->pgnoRoot==iRoot
43539     && p->pBtree!=pBtree
43540     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
43541    ){
43542      return 1;
43543    }
43544  }
43545  return 0;
43546}
43547#endif    /* #ifdef SQLITE_DEBUG */
43548
43549/*
43550** Query to see if Btree handle p may obtain a lock of type eLock
43551** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
43552** SQLITE_OK if the lock may be obtained (by calling
43553** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
43554*/
43555static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
43556  BtShared *pBt = p->pBt;
43557  BtLock *pIter;
43558
43559  assert( sqlite3BtreeHoldsMutex(p) );
43560  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43561  assert( p->db!=0 );
43562  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
43563
43564  /* If requesting a write-lock, then the Btree must have an open write
43565  ** transaction on this file. And, obviously, for this to be so there
43566  ** must be an open write transaction on the file itself.
43567  */
43568  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
43569  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
43570
43571  /* This routine is a no-op if the shared-cache is not enabled */
43572  if( !p->sharable ){
43573    return SQLITE_OK;
43574  }
43575
43576  /* If some other connection is holding an exclusive lock, the
43577  ** requested lock may not be obtained.
43578  */
43579  if( pBt->pWriter!=p && pBt->isExclusive ){
43580    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
43581    return SQLITE_LOCKED_SHAREDCACHE;
43582  }
43583
43584  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43585    /* The condition (pIter->eLock!=eLock) in the following if(...)
43586    ** statement is a simplification of:
43587    **
43588    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
43589    **
43590    ** since we know that if eLock==WRITE_LOCK, then no other connection
43591    ** may hold a WRITE_LOCK on any table in this file (since there can
43592    ** only be a single writer).
43593    */
43594    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
43595    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
43596    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
43597      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
43598      if( eLock==WRITE_LOCK ){
43599        assert( p==pBt->pWriter );
43600        pBt->isPending = 1;
43601      }
43602      return SQLITE_LOCKED_SHAREDCACHE;
43603    }
43604  }
43605  return SQLITE_OK;
43606}
43607#endif /* !SQLITE_OMIT_SHARED_CACHE */
43608
43609#ifndef SQLITE_OMIT_SHARED_CACHE
43610/*
43611** Add a lock on the table with root-page iTable to the shared-btree used
43612** by Btree handle p. Parameter eLock must be either READ_LOCK or
43613** WRITE_LOCK.
43614**
43615** This function assumes the following:
43616**
43617**   (a) The specified Btree object p is connected to a sharable
43618**       database (one with the BtShared.sharable flag set), and
43619**
43620**   (b) No other Btree objects hold a lock that conflicts
43621**       with the requested lock (i.e. querySharedCacheTableLock() has
43622**       already been called and returned SQLITE_OK).
43623**
43624** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
43625** is returned if a malloc attempt fails.
43626*/
43627static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
43628  BtShared *pBt = p->pBt;
43629  BtLock *pLock = 0;
43630  BtLock *pIter;
43631
43632  assert( sqlite3BtreeHoldsMutex(p) );
43633  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43634  assert( p->db!=0 );
43635
43636  /* A connection with the read-uncommitted flag set will never try to
43637  ** obtain a read-lock using this function. The only read-lock obtained
43638  ** by a connection in read-uncommitted mode is on the sqlite_master
43639  ** table, and that lock is obtained in BtreeBeginTrans().  */
43640  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
43641
43642  /* This function should only be called on a sharable b-tree after it
43643  ** has been determined that no other b-tree holds a conflicting lock.  */
43644  assert( p->sharable );
43645  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
43646
43647  /* First search the list for an existing lock on this table. */
43648  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43649    if( pIter->iTable==iTable && pIter->pBtree==p ){
43650      pLock = pIter;
43651      break;
43652    }
43653  }
43654
43655  /* If the above search did not find a BtLock struct associating Btree p
43656  ** with table iTable, allocate one and link it into the list.
43657  */
43658  if( !pLock ){
43659    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
43660    if( !pLock ){
43661      return SQLITE_NOMEM;
43662    }
43663    pLock->iTable = iTable;
43664    pLock->pBtree = p;
43665    pLock->pNext = pBt->pLock;
43666    pBt->pLock = pLock;
43667  }
43668
43669  /* Set the BtLock.eLock variable to the maximum of the current lock
43670  ** and the requested lock. This means if a write-lock was already held
43671  ** and a read-lock requested, we don't incorrectly downgrade the lock.
43672  */
43673  assert( WRITE_LOCK>READ_LOCK );
43674  if( eLock>pLock->eLock ){
43675    pLock->eLock = eLock;
43676  }
43677
43678  return SQLITE_OK;
43679}
43680#endif /* !SQLITE_OMIT_SHARED_CACHE */
43681
43682#ifndef SQLITE_OMIT_SHARED_CACHE
43683/*
43684** Release all the table locks (locks obtained via calls to
43685** the setSharedCacheTableLock() procedure) held by Btree object p.
43686**
43687** This function assumes that Btree p has an open read or write
43688** transaction. If it does not, then the BtShared.isPending variable
43689** may be incorrectly cleared.
43690*/
43691static void clearAllSharedCacheTableLocks(Btree *p){
43692  BtShared *pBt = p->pBt;
43693  BtLock **ppIter = &pBt->pLock;
43694
43695  assert( sqlite3BtreeHoldsMutex(p) );
43696  assert( p->sharable || 0==*ppIter );
43697  assert( p->inTrans>0 );
43698
43699  while( *ppIter ){
43700    BtLock *pLock = *ppIter;
43701    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
43702    assert( pLock->pBtree->inTrans>=pLock->eLock );
43703    if( pLock->pBtree==p ){
43704      *ppIter = pLock->pNext;
43705      assert( pLock->iTable!=1 || pLock==&p->lock );
43706      if( pLock->iTable!=1 ){
43707        sqlite3_free(pLock);
43708      }
43709    }else{
43710      ppIter = &pLock->pNext;
43711    }
43712  }
43713
43714  assert( pBt->isPending==0 || pBt->pWriter );
43715  if( pBt->pWriter==p ){
43716    pBt->pWriter = 0;
43717    pBt->isExclusive = 0;
43718    pBt->isPending = 0;
43719  }else if( pBt->nTransaction==2 ){
43720    /* This function is called when Btree p is concluding its
43721    ** transaction. If there currently exists a writer, and p is not
43722    ** that writer, then the number of locks held by connections other
43723    ** than the writer must be about to drop to zero. In this case
43724    ** set the isPending flag to 0.
43725    **
43726    ** If there is not currently a writer, then BtShared.isPending must
43727    ** be zero already. So this next line is harmless in that case.
43728    */
43729    pBt->isPending = 0;
43730  }
43731}
43732
43733/*
43734** This function changes all write-locks held by Btree p into read-locks.
43735*/
43736static void downgradeAllSharedCacheTableLocks(Btree *p){
43737  BtShared *pBt = p->pBt;
43738  if( pBt->pWriter==p ){
43739    BtLock *pLock;
43740    pBt->pWriter = 0;
43741    pBt->isExclusive = 0;
43742    pBt->isPending = 0;
43743    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
43744      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
43745      pLock->eLock = READ_LOCK;
43746    }
43747  }
43748}
43749
43750#endif /* SQLITE_OMIT_SHARED_CACHE */
43751
43752static void releasePage(MemPage *pPage);  /* Forward reference */
43753
43754/*
43755***** This routine is used inside of assert() only ****
43756**
43757** Verify that the cursor holds the mutex on its BtShared
43758*/
43759#ifdef SQLITE_DEBUG
43760static int cursorHoldsMutex(BtCursor *p){
43761  return sqlite3_mutex_held(p->pBt->mutex);
43762}
43763#endif
43764
43765
43766#ifndef SQLITE_OMIT_INCRBLOB
43767/*
43768** Invalidate the overflow page-list cache for cursor pCur, if any.
43769*/
43770static void invalidateOverflowCache(BtCursor *pCur){
43771  assert( cursorHoldsMutex(pCur) );
43772  sqlite3_free(pCur->aOverflow);
43773  pCur->aOverflow = 0;
43774}
43775
43776/*
43777** Invalidate the overflow page-list cache for all cursors opened
43778** on the shared btree structure pBt.
43779*/
43780static void invalidateAllOverflowCache(BtShared *pBt){
43781  BtCursor *p;
43782  assert( sqlite3_mutex_held(pBt->mutex) );
43783  for(p=pBt->pCursor; p; p=p->pNext){
43784    invalidateOverflowCache(p);
43785  }
43786}
43787
43788/*
43789** This function is called before modifying the contents of a table
43790** to invalidate any incrblob cursors that are open on the
43791** row or one of the rows being modified.
43792**
43793** If argument isClearTable is true, then the entire contents of the
43794** table is about to be deleted. In this case invalidate all incrblob
43795** cursors open on any row within the table with root-page pgnoRoot.
43796**
43797** Otherwise, if argument isClearTable is false, then the row with
43798** rowid iRow is being replaced or deleted. In this case invalidate
43799** only those incrblob cursors open on that specific row.
43800*/
43801static void invalidateIncrblobCursors(
43802  Btree *pBtree,          /* The database file to check */
43803  i64 iRow,               /* The rowid that might be changing */
43804  int isClearTable        /* True if all rows are being deleted */
43805){
43806  BtCursor *p;
43807  BtShared *pBt = pBtree->pBt;
43808  assert( sqlite3BtreeHoldsMutex(pBtree) );
43809  for(p=pBt->pCursor; p; p=p->pNext){
43810    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
43811      p->eState = CURSOR_INVALID;
43812    }
43813  }
43814}
43815
43816#else
43817  /* Stub functions when INCRBLOB is omitted */
43818  #define invalidateOverflowCache(x)
43819  #define invalidateAllOverflowCache(x)
43820  #define invalidateIncrblobCursors(x,y,z)
43821#endif /* SQLITE_OMIT_INCRBLOB */
43822
43823/*
43824** Set bit pgno of the BtShared.pHasContent bitvec. This is called
43825** when a page that previously contained data becomes a free-list leaf
43826** page.
43827**
43828** The BtShared.pHasContent bitvec exists to work around an obscure
43829** bug caused by the interaction of two useful IO optimizations surrounding
43830** free-list leaf pages:
43831**
43832**   1) When all data is deleted from a page and the page becomes
43833**      a free-list leaf page, the page is not written to the database
43834**      (as free-list leaf pages contain no meaningful data). Sometimes
43835**      such a page is not even journalled (as it will not be modified,
43836**      why bother journalling it?).
43837**
43838**   2) When a free-list leaf page is reused, its content is not read
43839**      from the database or written to the journal file (why should it
43840**      be, if it is not at all meaningful?).
43841**
43842** By themselves, these optimizations work fine and provide a handy
43843** performance boost to bulk delete or insert operations. However, if
43844** a page is moved to the free-list and then reused within the same
43845** transaction, a problem comes up. If the page is not journalled when
43846** it is moved to the free-list and it is also not journalled when it
43847** is extracted from the free-list and reused, then the original data
43848** may be lost. In the event of a rollback, it may not be possible
43849** to restore the database to its original configuration.
43850**
43851** The solution is the BtShared.pHasContent bitvec. Whenever a page is
43852** moved to become a free-list leaf page, the corresponding bit is
43853** set in the bitvec. Whenever a leaf page is extracted from the free-list,
43854** optimization 2 above is omitted if the corresponding bit is already
43855** set in BtShared.pHasContent. The contents of the bitvec are cleared
43856** at the end of every transaction.
43857*/
43858static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
43859  int rc = SQLITE_OK;
43860  if( !pBt->pHasContent ){
43861    assert( pgno<=pBt->nPage );
43862    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
43863    if( !pBt->pHasContent ){
43864      rc = SQLITE_NOMEM;
43865    }
43866  }
43867  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
43868    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
43869  }
43870  return rc;
43871}
43872
43873/*
43874** Query the BtShared.pHasContent vector.
43875**
43876** This function is called when a free-list leaf page is removed from the
43877** free-list for reuse. It returns false if it is safe to retrieve the
43878** page from the pager layer with the 'no-content' flag set. True otherwise.
43879*/
43880static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
43881  Bitvec *p = pBt->pHasContent;
43882  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
43883}
43884
43885/*
43886** Clear (destroy) the BtShared.pHasContent bitvec. This should be
43887** invoked at the conclusion of each write-transaction.
43888*/
43889static void btreeClearHasContent(BtShared *pBt){
43890  sqlite3BitvecDestroy(pBt->pHasContent);
43891  pBt->pHasContent = 0;
43892}
43893
43894/*
43895** Save the current cursor position in the variables BtCursor.nKey
43896** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
43897**
43898** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
43899** prior to calling this routine.
43900*/
43901static int saveCursorPosition(BtCursor *pCur){
43902  int rc;
43903
43904  assert( CURSOR_VALID==pCur->eState );
43905  assert( 0==pCur->pKey );
43906  assert( cursorHoldsMutex(pCur) );
43907
43908  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
43909  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
43910
43911  /* If this is an intKey table, then the above call to BtreeKeySize()
43912  ** stores the integer key in pCur->nKey. In this case this value is
43913  ** all that is required. Otherwise, if pCur is not open on an intKey
43914  ** table, then malloc space for and store the pCur->nKey bytes of key
43915  ** data.
43916  */
43917  if( 0==pCur->apPage[0]->intKey ){
43918    void *pKey = sqlite3Malloc( (int)pCur->nKey );
43919    if( pKey ){
43920      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
43921      if( rc==SQLITE_OK ){
43922        pCur->pKey = pKey;
43923      }else{
43924        sqlite3_free(pKey);
43925      }
43926    }else{
43927      rc = SQLITE_NOMEM;
43928    }
43929  }
43930  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
43931
43932  if( rc==SQLITE_OK ){
43933    int i;
43934    for(i=0; i<=pCur->iPage; i++){
43935      releasePage(pCur->apPage[i]);
43936      pCur->apPage[i] = 0;
43937    }
43938    pCur->iPage = -1;
43939    pCur->eState = CURSOR_REQUIRESEEK;
43940  }
43941
43942  invalidateOverflowCache(pCur);
43943  return rc;
43944}
43945
43946/*
43947** Save the positions of all cursors (except pExcept) that are open on
43948** the table  with root-page iRoot. Usually, this is called just before cursor
43949** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
43950*/
43951static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
43952  BtCursor *p;
43953  assert( sqlite3_mutex_held(pBt->mutex) );
43954  assert( pExcept==0 || pExcept->pBt==pBt );
43955  for(p=pBt->pCursor; p; p=p->pNext){
43956    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
43957        p->eState==CURSOR_VALID ){
43958      int rc = saveCursorPosition(p);
43959      if( SQLITE_OK!=rc ){
43960        return rc;
43961      }
43962    }
43963  }
43964  return SQLITE_OK;
43965}
43966
43967/*
43968** Clear the current cursor position.
43969*/
43970SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
43971  assert( cursorHoldsMutex(pCur) );
43972  sqlite3_free(pCur->pKey);
43973  pCur->pKey = 0;
43974  pCur->eState = CURSOR_INVALID;
43975}
43976
43977/*
43978** In this version of BtreeMoveto, pKey is a packed index record
43979** such as is generated by the OP_MakeRecord opcode.  Unpack the
43980** record and then call BtreeMovetoUnpacked() to do the work.
43981*/
43982static int btreeMoveto(
43983  BtCursor *pCur,     /* Cursor open on the btree to be searched */
43984  const void *pKey,   /* Packed key if the btree is an index */
43985  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
43986  int bias,           /* Bias search to the high end */
43987  int *pRes           /* Write search results here */
43988){
43989  int rc;                    /* Status code */
43990  UnpackedRecord *pIdxKey;   /* Unpacked index key */
43991  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
43992
43993  if( pKey ){
43994    assert( nKey==(i64)(int)nKey );
43995    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
43996                                      aSpace, sizeof(aSpace));
43997    if( pIdxKey==0 ) return SQLITE_NOMEM;
43998  }else{
43999    pIdxKey = 0;
44000  }
44001  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
44002  if( pKey ){
44003    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
44004  }
44005  return rc;
44006}
44007
44008/*
44009** Restore the cursor to the position it was in (or as close to as possible)
44010** when saveCursorPosition() was called. Note that this call deletes the
44011** saved position info stored by saveCursorPosition(), so there can be
44012** at most one effective restoreCursorPosition() call after each
44013** saveCursorPosition().
44014*/
44015static int btreeRestoreCursorPosition(BtCursor *pCur){
44016  int rc;
44017  assert( cursorHoldsMutex(pCur) );
44018  assert( pCur->eState>=CURSOR_REQUIRESEEK );
44019  if( pCur->eState==CURSOR_FAULT ){
44020    return pCur->skipNext;
44021  }
44022  pCur->eState = CURSOR_INVALID;
44023  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
44024  if( rc==SQLITE_OK ){
44025    sqlite3_free(pCur->pKey);
44026    pCur->pKey = 0;
44027    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
44028  }
44029  return rc;
44030}
44031
44032#define restoreCursorPosition(p) \
44033  (p->eState>=CURSOR_REQUIRESEEK ? \
44034         btreeRestoreCursorPosition(p) : \
44035         SQLITE_OK)
44036
44037/*
44038** Determine whether or not a cursor has moved from the position it
44039** was last placed at.  Cursors can move when the row they are pointing
44040** at is deleted out from under them.
44041**
44042** This routine returns an error code if something goes wrong.  The
44043** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
44044*/
44045SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
44046  int rc;
44047
44048  rc = restoreCursorPosition(pCur);
44049  if( rc ){
44050    *pHasMoved = 1;
44051    return rc;
44052  }
44053  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
44054    *pHasMoved = 1;
44055  }else{
44056    *pHasMoved = 0;
44057  }
44058  return SQLITE_OK;
44059}
44060
44061#ifndef SQLITE_OMIT_AUTOVACUUM
44062/*
44063** Given a page number of a regular database page, return the page
44064** number for the pointer-map page that contains the entry for the
44065** input page number.
44066*/
44067static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
44068  int nPagesPerMapPage;
44069  Pgno iPtrMap, ret;
44070  assert( sqlite3_mutex_held(pBt->mutex) );
44071  nPagesPerMapPage = (pBt->usableSize/5)+1;
44072  iPtrMap = (pgno-2)/nPagesPerMapPage;
44073  ret = (iPtrMap*nPagesPerMapPage) + 2;
44074  if( ret==PENDING_BYTE_PAGE(pBt) ){
44075    ret++;
44076  }
44077  return ret;
44078}
44079
44080/*
44081** Write an entry into the pointer map.
44082**
44083** This routine updates the pointer map entry for page number 'key'
44084** so that it maps to type 'eType' and parent page number 'pgno'.
44085**
44086** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
44087** a no-op.  If an error occurs, the appropriate error code is written
44088** into *pRC.
44089*/
44090static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
44091  DbPage *pDbPage;  /* The pointer map page */
44092  u8 *pPtrmap;      /* The pointer map data */
44093  Pgno iPtrmap;     /* The pointer map page number */
44094  int offset;       /* Offset in pointer map page */
44095  int rc;           /* Return code from subfunctions */
44096
44097  if( *pRC ) return;
44098
44099  assert( sqlite3_mutex_held(pBt->mutex) );
44100  /* The master-journal page number must never be used as a pointer map page */
44101  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
44102
44103  assert( pBt->autoVacuum );
44104  if( key==0 ){
44105    *pRC = SQLITE_CORRUPT_BKPT;
44106    return;
44107  }
44108  iPtrmap = PTRMAP_PAGENO(pBt, key);
44109  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44110  if( rc!=SQLITE_OK ){
44111    *pRC = rc;
44112    return;
44113  }
44114  offset = PTRMAP_PTROFFSET(iPtrmap, key);
44115  if( offset<0 ){
44116    *pRC = SQLITE_CORRUPT_BKPT;
44117    goto ptrmap_exit;
44118  }
44119  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44120
44121  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
44122    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
44123    *pRC= rc = sqlite3PagerWrite(pDbPage);
44124    if( rc==SQLITE_OK ){
44125      pPtrmap[offset] = eType;
44126      put4byte(&pPtrmap[offset+1], parent);
44127    }
44128  }
44129
44130ptrmap_exit:
44131  sqlite3PagerUnref(pDbPage);
44132}
44133
44134/*
44135** Read an entry from the pointer map.
44136**
44137** This routine retrieves the pointer map entry for page 'key', writing
44138** the type and parent page number to *pEType and *pPgno respectively.
44139** An error code is returned if something goes wrong, otherwise SQLITE_OK.
44140*/
44141static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
44142  DbPage *pDbPage;   /* The pointer map page */
44143  int iPtrmap;       /* Pointer map page index */
44144  u8 *pPtrmap;       /* Pointer map page data */
44145  int offset;        /* Offset of entry in pointer map */
44146  int rc;
44147
44148  assert( sqlite3_mutex_held(pBt->mutex) );
44149
44150  iPtrmap = PTRMAP_PAGENO(pBt, key);
44151  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44152  if( rc!=0 ){
44153    return rc;
44154  }
44155  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44156
44157  offset = PTRMAP_PTROFFSET(iPtrmap, key);
44158  assert( pEType!=0 );
44159  *pEType = pPtrmap[offset];
44160  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
44161
44162  sqlite3PagerUnref(pDbPage);
44163  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
44164  return SQLITE_OK;
44165}
44166
44167#else /* if defined SQLITE_OMIT_AUTOVACUUM */
44168  #define ptrmapPut(w,x,y,z,rc)
44169  #define ptrmapGet(w,x,y,z) SQLITE_OK
44170  #define ptrmapPutOvflPtr(x, y, rc)
44171#endif
44172
44173/*
44174** Given a btree page and a cell index (0 means the first cell on
44175** the page, 1 means the second cell, and so forth) return a pointer
44176** to the cell content.
44177**
44178** This routine works only for pages that do not contain overflow cells.
44179*/
44180#define findCell(P,I) \
44181  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
44182
44183/*
44184** This a more complex version of findCell() that works for
44185** pages that do contain overflow cells.
44186*/
44187static u8 *findOverflowCell(MemPage *pPage, int iCell){
44188  int i;
44189  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44190  for(i=pPage->nOverflow-1; i>=0; i--){
44191    int k;
44192    struct _OvflCell *pOvfl;
44193    pOvfl = &pPage->aOvfl[i];
44194    k = pOvfl->idx;
44195    if( k<=iCell ){
44196      if( k==iCell ){
44197        return pOvfl->pCell;
44198      }
44199      iCell--;
44200    }
44201  }
44202  return findCell(pPage, iCell);
44203}
44204
44205/*
44206** Parse a cell content block and fill in the CellInfo structure.  There
44207** are two versions of this function.  btreeParseCell() takes a
44208** cell index as the second argument and btreeParseCellPtr()
44209** takes a pointer to the body of the cell as its second argument.
44210**
44211** Within this file, the parseCell() macro can be called instead of
44212** btreeParseCellPtr(). Using some compilers, this will be faster.
44213*/
44214static void btreeParseCellPtr(
44215  MemPage *pPage,         /* Page containing the cell */
44216  u8 *pCell,              /* Pointer to the cell text. */
44217  CellInfo *pInfo         /* Fill in this structure */
44218){
44219  u16 n;                  /* Number bytes in cell content header */
44220  u32 nPayload;           /* Number of bytes of cell payload */
44221
44222  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44223
44224  pInfo->pCell = pCell;
44225  assert( pPage->leaf==0 || pPage->leaf==1 );
44226  n = pPage->childPtrSize;
44227  assert( n==4-4*pPage->leaf );
44228  if( pPage->intKey ){
44229    if( pPage->hasData ){
44230      n += getVarint32(&pCell[n], nPayload);
44231    }else{
44232      nPayload = 0;
44233    }
44234    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
44235    pInfo->nData = nPayload;
44236  }else{
44237    pInfo->nData = 0;
44238    n += getVarint32(&pCell[n], nPayload);
44239    pInfo->nKey = nPayload;
44240  }
44241  pInfo->nPayload = nPayload;
44242  pInfo->nHeader = n;
44243  testcase( nPayload==pPage->maxLocal );
44244  testcase( nPayload==pPage->maxLocal+1 );
44245  if( likely(nPayload<=pPage->maxLocal) ){
44246    /* This is the (easy) common case where the entire payload fits
44247    ** on the local page.  No overflow is required.
44248    */
44249    int nSize;          /* Total size of cell content in bytes */
44250    nSize = nPayload + n;
44251    pInfo->nLocal = (u16)nPayload;
44252    pInfo->iOverflow = 0;
44253    if( (nSize & ~3)==0 ){
44254      nSize = 4;        /* Minimum cell size is 4 */
44255    }
44256    pInfo->nSize = (u16)nSize;
44257  }else{
44258    /* If the payload will not fit completely on the local page, we have
44259    ** to decide how much to store locally and how much to spill onto
44260    ** overflow pages.  The strategy is to minimize the amount of unused
44261    ** space on overflow pages while keeping the amount of local storage
44262    ** in between minLocal and maxLocal.
44263    **
44264    ** Warning:  changing the way overflow payload is distributed in any
44265    ** way will result in an incompatible file format.
44266    */
44267    int minLocal;  /* Minimum amount of payload held locally */
44268    int maxLocal;  /* Maximum amount of payload held locally */
44269    int surplus;   /* Overflow payload available for local storage */
44270
44271    minLocal = pPage->minLocal;
44272    maxLocal = pPage->maxLocal;
44273    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
44274    testcase( surplus==maxLocal );
44275    testcase( surplus==maxLocal+1 );
44276    if( surplus <= maxLocal ){
44277      pInfo->nLocal = (u16)surplus;
44278    }else{
44279      pInfo->nLocal = (u16)minLocal;
44280    }
44281    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
44282    pInfo->nSize = pInfo->iOverflow + 4;
44283  }
44284}
44285#define parseCell(pPage, iCell, pInfo) \
44286  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
44287static void btreeParseCell(
44288  MemPage *pPage,         /* Page containing the cell */
44289  int iCell,              /* The cell index.  First cell is 0 */
44290  CellInfo *pInfo         /* Fill in this structure */
44291){
44292  parseCell(pPage, iCell, pInfo);
44293}
44294
44295/*
44296** Compute the total number of bytes that a Cell needs in the cell
44297** data area of the btree-page.  The return number includes the cell
44298** data header and the local payload, but not any overflow page or
44299** the space used by the cell pointer.
44300*/
44301static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
44302  u8 *pIter = &pCell[pPage->childPtrSize];
44303  u32 nSize;
44304
44305#ifdef SQLITE_DEBUG
44306  /* The value returned by this function should always be the same as
44307  ** the (CellInfo.nSize) value found by doing a full parse of the
44308  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
44309  ** this function verifies that this invariant is not violated. */
44310  CellInfo debuginfo;
44311  btreeParseCellPtr(pPage, pCell, &debuginfo);
44312#endif
44313
44314  if( pPage->intKey ){
44315    u8 *pEnd;
44316    if( pPage->hasData ){
44317      pIter += getVarint32(pIter, nSize);
44318    }else{
44319      nSize = 0;
44320    }
44321
44322    /* pIter now points at the 64-bit integer key value, a variable length
44323    ** integer. The following block moves pIter to point at the first byte
44324    ** past the end of the key value. */
44325    pEnd = &pIter[9];
44326    while( (*pIter++)&0x80 && pIter<pEnd );
44327  }else{
44328    pIter += getVarint32(pIter, nSize);
44329  }
44330
44331  testcase( nSize==pPage->maxLocal );
44332  testcase( nSize==pPage->maxLocal+1 );
44333  if( nSize>pPage->maxLocal ){
44334    int minLocal = pPage->minLocal;
44335    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
44336    testcase( nSize==pPage->maxLocal );
44337    testcase( nSize==pPage->maxLocal+1 );
44338    if( nSize>pPage->maxLocal ){
44339      nSize = minLocal;
44340    }
44341    nSize += 4;
44342  }
44343  nSize += (u32)(pIter - pCell);
44344
44345  /* The minimum size of any cell is 4 bytes. */
44346  if( nSize<4 ){
44347    nSize = 4;
44348  }
44349
44350  assert( nSize==debuginfo.nSize );
44351  return (u16)nSize;
44352}
44353
44354#ifdef SQLITE_DEBUG
44355/* This variation on cellSizePtr() is used inside of assert() statements
44356** only. */
44357static u16 cellSize(MemPage *pPage, int iCell){
44358  return cellSizePtr(pPage, findCell(pPage, iCell));
44359}
44360#endif
44361
44362#ifndef SQLITE_OMIT_AUTOVACUUM
44363/*
44364** If the cell pCell, part of page pPage contains a pointer
44365** to an overflow page, insert an entry into the pointer-map
44366** for the overflow page.
44367*/
44368static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
44369  CellInfo info;
44370  if( *pRC ) return;
44371  assert( pCell!=0 );
44372  btreeParseCellPtr(pPage, pCell, &info);
44373  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
44374  if( info.iOverflow ){
44375    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
44376    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
44377  }
44378}
44379#endif
44380
44381
44382/*
44383** Defragment the page given.  All Cells are moved to the
44384** end of the page and all free space is collected into one
44385** big FreeBlk that occurs in between the header and cell
44386** pointer array and the cell content area.
44387*/
44388static int defragmentPage(MemPage *pPage){
44389  int i;                     /* Loop counter */
44390  int pc;                    /* Address of a i-th cell */
44391  int hdr;                   /* Offset to the page header */
44392  int size;                  /* Size of a cell */
44393  int usableSize;            /* Number of usable bytes on a page */
44394  int cellOffset;            /* Offset to the cell pointer array */
44395  int cbrk;                  /* Offset to the cell content area */
44396  int nCell;                 /* Number of cells on the page */
44397  unsigned char *data;       /* The page data */
44398  unsigned char *temp;       /* Temp area for cell content */
44399  int iCellFirst;            /* First allowable cell index */
44400  int iCellLast;             /* Last possible cell index */
44401
44402
44403  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44404  assert( pPage->pBt!=0 );
44405  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
44406  assert( pPage->nOverflow==0 );
44407  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44408  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
44409  data = pPage->aData;
44410  hdr = pPage->hdrOffset;
44411  cellOffset = pPage->cellOffset;
44412  nCell = pPage->nCell;
44413  assert( nCell==get2byte(&data[hdr+3]) );
44414  usableSize = pPage->pBt->usableSize;
44415  cbrk = get2byte(&data[hdr+5]);
44416  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
44417  cbrk = usableSize;
44418  iCellFirst = cellOffset + 2*nCell;
44419  iCellLast = usableSize - 4;
44420  for(i=0; i<nCell; i++){
44421    u8 *pAddr;     /* The i-th cell pointer */
44422    pAddr = &data[cellOffset + i*2];
44423    pc = get2byte(pAddr);
44424    testcase( pc==iCellFirst );
44425    testcase( pc==iCellLast );
44426#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44427    /* These conditions have already been verified in btreeInitPage()
44428    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
44429    */
44430    if( pc<iCellFirst || pc>iCellLast ){
44431      return SQLITE_CORRUPT_BKPT;
44432    }
44433#endif
44434    assert( pc>=iCellFirst && pc<=iCellLast );
44435    size = cellSizePtr(pPage, &temp[pc]);
44436    cbrk -= size;
44437#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44438    if( cbrk<iCellFirst ){
44439      return SQLITE_CORRUPT_BKPT;
44440    }
44441#else
44442    if( cbrk<iCellFirst || pc+size>usableSize ){
44443      return SQLITE_CORRUPT_BKPT;
44444    }
44445#endif
44446    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
44447    testcase( cbrk+size==usableSize );
44448    testcase( pc+size==usableSize );
44449    memcpy(&data[cbrk], &temp[pc], size);
44450    put2byte(pAddr, cbrk);
44451  }
44452  assert( cbrk>=iCellFirst );
44453  put2byte(&data[hdr+5], cbrk);
44454  data[hdr+1] = 0;
44455  data[hdr+2] = 0;
44456  data[hdr+7] = 0;
44457  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
44458  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44459  if( cbrk-iCellFirst!=pPage->nFree ){
44460    return SQLITE_CORRUPT_BKPT;
44461  }
44462  return SQLITE_OK;
44463}
44464
44465/*
44466** Allocate nByte bytes of space from within the B-Tree page passed
44467** as the first argument. Write into *pIdx the index into pPage->aData[]
44468** of the first byte of allocated space. Return either SQLITE_OK or
44469** an error code (usually SQLITE_CORRUPT).
44470**
44471** The caller guarantees that there is sufficient space to make the
44472** allocation.  This routine might need to defragment in order to bring
44473** all the space together, however.  This routine will avoid using
44474** the first two bytes past the cell pointer area since presumably this
44475** allocation is being made in order to insert a new cell, so we will
44476** also end up needing a new cell pointer.
44477*/
44478static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
44479  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
44480  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
44481  int nFrag;                           /* Number of fragmented bytes on pPage */
44482  int top;                             /* First byte of cell content area */
44483  int gap;        /* First byte of gap between cell pointers and cell content */
44484  int rc;         /* Integer return code */
44485  int usableSize; /* Usable size of the page */
44486
44487  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44488  assert( pPage->pBt );
44489  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44490  assert( nByte>=0 );  /* Minimum cell size is 4 */
44491  assert( pPage->nFree>=nByte );
44492  assert( pPage->nOverflow==0 );
44493  usableSize = pPage->pBt->usableSize;
44494  assert( nByte < usableSize-8 );
44495
44496  nFrag = data[hdr+7];
44497  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
44498  gap = pPage->cellOffset + 2*pPage->nCell;
44499  top = get2byte(&data[hdr+5]);
44500  if( gap>top ) return SQLITE_CORRUPT_BKPT;
44501  testcase( gap+2==top );
44502  testcase( gap+1==top );
44503  testcase( gap==top );
44504
44505  if( nFrag>=60 ){
44506    /* Always defragment highly fragmented pages */
44507    rc = defragmentPage(pPage);
44508    if( rc ) return rc;
44509    top = get2byte(&data[hdr+5]);
44510  }else if( gap+2<=top ){
44511    /* Search the freelist looking for a free slot big enough to satisfy
44512    ** the request. The allocation is made from the first free slot in
44513    ** the list that is large enough to accomadate it.
44514    */
44515    int pc, addr;
44516    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
44517      int size;            /* Size of the free slot */
44518      if( pc>usableSize-4 || pc<addr+4 ){
44519        return SQLITE_CORRUPT_BKPT;
44520      }
44521      size = get2byte(&data[pc+2]);
44522      if( size>=nByte ){
44523        int x = size - nByte;
44524        testcase( x==4 );
44525        testcase( x==3 );
44526        if( x<4 ){
44527          /* Remove the slot from the free-list. Update the number of
44528          ** fragmented bytes within the page. */
44529          memcpy(&data[addr], &data[pc], 2);
44530          data[hdr+7] = (u8)(nFrag + x);
44531        }else if( size+pc > usableSize ){
44532          return SQLITE_CORRUPT_BKPT;
44533        }else{
44534          /* The slot remains on the free-list. Reduce its size to account
44535          ** for the portion used by the new allocation. */
44536          put2byte(&data[pc+2], x);
44537        }
44538        *pIdx = pc + x;
44539        return SQLITE_OK;
44540      }
44541    }
44542  }
44543
44544  /* Check to make sure there is enough space in the gap to satisfy
44545  ** the allocation.  If not, defragment.
44546  */
44547  testcase( gap+2+nByte==top );
44548  if( gap+2+nByte>top ){
44549    rc = defragmentPage(pPage);
44550    if( rc ) return rc;
44551    top = get2byte(&data[hdr+5]);
44552    assert( gap+nByte<=top );
44553  }
44554
44555
44556  /* Allocate memory from the gap in between the cell pointer array
44557  ** and the cell content area.  The btreeInitPage() call has already
44558  ** validated the freelist.  Given that the freelist is valid, there
44559  ** is no way that the allocation can extend off the end of the page.
44560  ** The assert() below verifies the previous sentence.
44561  */
44562  top -= nByte;
44563  put2byte(&data[hdr+5], top);
44564  assert( top+nByte <= pPage->pBt->usableSize );
44565  *pIdx = top;
44566  return SQLITE_OK;
44567}
44568
44569/*
44570** Return a section of the pPage->aData to the freelist.
44571** The first byte of the new free block is pPage->aDisk[start]
44572** and the size of the block is "size" bytes.
44573**
44574** Most of the effort here is involved in coalesing adjacent
44575** free blocks into a single big free block.
44576*/
44577static int freeSpace(MemPage *pPage, int start, int size){
44578  int addr, pbegin, hdr;
44579  int iLast;                        /* Largest possible freeblock offset */
44580  unsigned char *data = pPage->aData;
44581
44582  assert( pPage->pBt!=0 );
44583  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44584  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
44585  assert( (start + size)<=pPage->pBt->usableSize );
44586  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44587  assert( size>=0 );   /* Minimum cell size is 4 */
44588
44589  if( pPage->pBt->secureDelete ){
44590    /* Overwrite deleted information with zeros when the secure_delete
44591    ** option is enabled */
44592    memset(&data[start], 0, size);
44593  }
44594
44595  /* Add the space back into the linked list of freeblocks.  Note that
44596  ** even though the freeblock list was checked by btreeInitPage(),
44597  ** btreeInitPage() did not detect overlapping cells or
44598  ** freeblocks that overlapped cells.   Nor does it detect when the
44599  ** cell content area exceeds the value in the page header.  If these
44600  ** situations arise, then subsequent insert operations might corrupt
44601  ** the freelist.  So we do need to check for corruption while scanning
44602  ** the freelist.
44603  */
44604  hdr = pPage->hdrOffset;
44605  addr = hdr + 1;
44606  iLast = pPage->pBt->usableSize - 4;
44607  assert( start<=iLast );
44608  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
44609    if( pbegin<addr+4 ){
44610      return SQLITE_CORRUPT_BKPT;
44611    }
44612    addr = pbegin;
44613  }
44614  if( pbegin>iLast ){
44615    return SQLITE_CORRUPT_BKPT;
44616  }
44617  assert( pbegin>addr || pbegin==0 );
44618  put2byte(&data[addr], start);
44619  put2byte(&data[start], pbegin);
44620  put2byte(&data[start+2], size);
44621  pPage->nFree = pPage->nFree + (u16)size;
44622
44623  /* Coalesce adjacent free blocks */
44624  addr = hdr + 1;
44625  while( (pbegin = get2byte(&data[addr]))>0 ){
44626    int pnext, psize, x;
44627    assert( pbegin>addr );
44628    assert( pbegin<=pPage->pBt->usableSize-4 );
44629    pnext = get2byte(&data[pbegin]);
44630    psize = get2byte(&data[pbegin+2]);
44631    if( pbegin + psize + 3 >= pnext && pnext>0 ){
44632      int frag = pnext - (pbegin+psize);
44633      if( (frag<0) || (frag>(int)data[hdr+7]) ){
44634        return SQLITE_CORRUPT_BKPT;
44635      }
44636      data[hdr+7] -= (u8)frag;
44637      x = get2byte(&data[pnext]);
44638      put2byte(&data[pbegin], x);
44639      x = pnext + get2byte(&data[pnext+2]) - pbegin;
44640      put2byte(&data[pbegin+2], x);
44641    }else{
44642      addr = pbegin;
44643    }
44644  }
44645
44646  /* If the cell content area begins with a freeblock, remove it. */
44647  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
44648    int top;
44649    pbegin = get2byte(&data[hdr+1]);
44650    memcpy(&data[hdr+1], &data[pbegin], 2);
44651    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
44652    put2byte(&data[hdr+5], top);
44653  }
44654  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44655  return SQLITE_OK;
44656}
44657
44658/*
44659** Decode the flags byte (the first byte of the header) for a page
44660** and initialize fields of the MemPage structure accordingly.
44661**
44662** Only the following combinations are supported.  Anything different
44663** indicates a corrupt database files:
44664**
44665**         PTF_ZERODATA
44666**         PTF_ZERODATA | PTF_LEAF
44667**         PTF_LEAFDATA | PTF_INTKEY
44668**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
44669*/
44670static int decodeFlags(MemPage *pPage, int flagByte){
44671  BtShared *pBt;     /* A copy of pPage->pBt */
44672
44673  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
44674  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44675  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
44676  flagByte &= ~PTF_LEAF;
44677  pPage->childPtrSize = 4-4*pPage->leaf;
44678  pBt = pPage->pBt;
44679  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
44680    pPage->intKey = 1;
44681    pPage->hasData = pPage->leaf;
44682    pPage->maxLocal = pBt->maxLeaf;
44683    pPage->minLocal = pBt->minLeaf;
44684  }else if( flagByte==PTF_ZERODATA ){
44685    pPage->intKey = 0;
44686    pPage->hasData = 0;
44687    pPage->maxLocal = pBt->maxLocal;
44688    pPage->minLocal = pBt->minLocal;
44689  }else{
44690    return SQLITE_CORRUPT_BKPT;
44691  }
44692  return SQLITE_OK;
44693}
44694
44695/*
44696** Initialize the auxiliary information for a disk block.
44697**
44698** Return SQLITE_OK on success.  If we see that the page does
44699** not contain a well-formed database page, then return
44700** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
44701** guarantee that the page is well-formed.  It only shows that
44702** we failed to detect any corruption.
44703*/
44704static int btreeInitPage(MemPage *pPage){
44705
44706  assert( pPage->pBt!=0 );
44707  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44708  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
44709  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
44710  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
44711
44712  if( !pPage->isInit ){
44713    u16 pc;            /* Address of a freeblock within pPage->aData[] */
44714    u8 hdr;            /* Offset to beginning of page header */
44715    u8 *data;          /* Equal to pPage->aData */
44716    BtShared *pBt;        /* The main btree structure */
44717    u16 usableSize;    /* Amount of usable space on each page */
44718    u16 cellOffset;    /* Offset from start of page to first cell pointer */
44719    u16 nFree;         /* Number of unused bytes on the page */
44720    u16 top;           /* First byte of the cell content area */
44721    int iCellFirst;    /* First allowable cell or freeblock offset */
44722    int iCellLast;     /* Last possible cell or freeblock offset */
44723
44724    pBt = pPage->pBt;
44725
44726    hdr = pPage->hdrOffset;
44727    data = pPage->aData;
44728    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
44729    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
44730    pPage->maskPage = pBt->pageSize - 1;
44731    pPage->nOverflow = 0;
44732    usableSize = pBt->usableSize;
44733    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
44734    top = get2byte(&data[hdr+5]);
44735    pPage->nCell = get2byte(&data[hdr+3]);
44736    if( pPage->nCell>MX_CELL(pBt) ){
44737      /* To many cells for a single page.  The page must be corrupt */
44738      return SQLITE_CORRUPT_BKPT;
44739    }
44740    testcase( pPage->nCell==MX_CELL(pBt) );
44741
44742    /* A malformed database page might cause us to read past the end
44743    ** of page when parsing a cell.
44744    **
44745    ** The following block of code checks early to see if a cell extends
44746    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
44747    ** returned if it does.
44748    */
44749    iCellFirst = cellOffset + 2*pPage->nCell;
44750    iCellLast = usableSize - 4;
44751#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44752    {
44753      int i;            /* Index into the cell pointer array */
44754      int sz;           /* Size of a cell */
44755
44756      if( !pPage->leaf ) iCellLast--;
44757      for(i=0; i<pPage->nCell; i++){
44758        pc = get2byte(&data[cellOffset+i*2]);
44759        testcase( pc==iCellFirst );
44760        testcase( pc==iCellLast );
44761        if( pc<iCellFirst || pc>iCellLast ){
44762          return SQLITE_CORRUPT_BKPT;
44763        }
44764        sz = cellSizePtr(pPage, &data[pc]);
44765        testcase( pc+sz==usableSize );
44766        if( pc+sz>usableSize ){
44767          return SQLITE_CORRUPT_BKPT;
44768        }
44769      }
44770      if( !pPage->leaf ) iCellLast++;
44771    }
44772#endif
44773
44774    /* Compute the total free space on the page */
44775    pc = get2byte(&data[hdr+1]);
44776    nFree = data[hdr+7] + top;
44777    while( pc>0 ){
44778      u16 next, size;
44779      if( pc<iCellFirst || pc>iCellLast ){
44780        /* Start of free block is off the page */
44781        return SQLITE_CORRUPT_BKPT;
44782      }
44783      next = get2byte(&data[pc]);
44784      size = get2byte(&data[pc+2]);
44785      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
44786        /* Free blocks must be in ascending order. And the last byte of
44787	** the free-block must lie on the database page.  */
44788        return SQLITE_CORRUPT_BKPT;
44789      }
44790      nFree = nFree + size;
44791      pc = next;
44792    }
44793
44794    /* At this point, nFree contains the sum of the offset to the start
44795    ** of the cell-content area plus the number of free bytes within
44796    ** the cell-content area. If this is greater than the usable-size
44797    ** of the page, then the page must be corrupted. This check also
44798    ** serves to verify that the offset to the start of the cell-content
44799    ** area, according to the page header, lies within the page.
44800    */
44801    if( nFree>usableSize ){
44802      return SQLITE_CORRUPT_BKPT;
44803    }
44804    pPage->nFree = (u16)(nFree - iCellFirst);
44805    pPage->isInit = 1;
44806  }
44807  return SQLITE_OK;
44808}
44809
44810/*
44811** Set up a raw page so that it looks like a database page holding
44812** no entries.
44813*/
44814static void zeroPage(MemPage *pPage, int flags){
44815  unsigned char *data = pPage->aData;
44816  BtShared *pBt = pPage->pBt;
44817  u8 hdr = pPage->hdrOffset;
44818  u16 first;
44819
44820  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
44821  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
44822  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
44823  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44824  assert( sqlite3_mutex_held(pBt->mutex) );
44825  if( pBt->secureDelete ){
44826    memset(&data[hdr], 0, pBt->usableSize - hdr);
44827  }
44828  data[hdr] = (char)flags;
44829  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
44830  memset(&data[hdr+1], 0, 4);
44831  data[hdr+7] = 0;
44832  put2byte(&data[hdr+5], pBt->usableSize);
44833  pPage->nFree = pBt->usableSize - first;
44834  decodeFlags(pPage, flags);
44835  pPage->hdrOffset = hdr;
44836  pPage->cellOffset = first;
44837  pPage->nOverflow = 0;
44838  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
44839  pPage->maskPage = pBt->pageSize - 1;
44840  pPage->nCell = 0;
44841  pPage->isInit = 1;
44842}
44843
44844
44845/*
44846** Convert a DbPage obtained from the pager into a MemPage used by
44847** the btree layer.
44848*/
44849static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
44850  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
44851  pPage->aData = sqlite3PagerGetData(pDbPage);
44852  pPage->pDbPage = pDbPage;
44853  pPage->pBt = pBt;
44854  pPage->pgno = pgno;
44855  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
44856  return pPage;
44857}
44858
44859/*
44860** Get a page from the pager.  Initialize the MemPage.pBt and
44861** MemPage.aData elements if needed.
44862**
44863** If the noContent flag is set, it means that we do not care about
44864** the content of the page at this time.  So do not go to the disk
44865** to fetch the content.  Just fill in the content with zeros for now.
44866** If in the future we call sqlite3PagerWrite() on this page, that
44867** means we have started to be concerned about content and the disk
44868** read should occur at that point.
44869*/
44870static int btreeGetPage(
44871  BtShared *pBt,       /* The btree */
44872  Pgno pgno,           /* Number of the page to fetch */
44873  MemPage **ppPage,    /* Return the page in this parameter */
44874  int noContent        /* Do not load page content if true */
44875){
44876  int rc;
44877  DbPage *pDbPage;
44878
44879  assert( sqlite3_mutex_held(pBt->mutex) );
44880  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
44881  if( rc ) return rc;
44882  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
44883  return SQLITE_OK;
44884}
44885
44886/*
44887** Retrieve a page from the pager cache. If the requested page is not
44888** already in the pager cache return NULL. Initialize the MemPage.pBt and
44889** MemPage.aData elements if needed.
44890*/
44891static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
44892  DbPage *pDbPage;
44893  assert( sqlite3_mutex_held(pBt->mutex) );
44894  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
44895  if( pDbPage ){
44896    return btreePageFromDbPage(pDbPage, pgno, pBt);
44897  }
44898  return 0;
44899}
44900
44901/*
44902** Return the size of the database file in pages. If there is any kind of
44903** error, return ((unsigned int)-1).
44904*/
44905static Pgno btreePagecount(BtShared *pBt){
44906  return pBt->nPage;
44907}
44908SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
44909  assert( sqlite3BtreeHoldsMutex(p) );
44910  assert( ((p->pBt->nPage)&0x8000000)==0 );
44911  return (int)btreePagecount(p->pBt);
44912}
44913
44914/*
44915** Get a page from the pager and initialize it.  This routine is just a
44916** convenience wrapper around separate calls to btreeGetPage() and
44917** btreeInitPage().
44918**
44919** If an error occurs, then the value *ppPage is set to is undefined. It
44920** may remain unchanged, or it may be set to an invalid value.
44921*/
44922static int getAndInitPage(
44923  BtShared *pBt,          /* The database file */
44924  Pgno pgno,           /* Number of the page to get */
44925  MemPage **ppPage     /* Write the page pointer here */
44926){
44927  int rc;
44928  assert( sqlite3_mutex_held(pBt->mutex) );
44929
44930  if( pgno<=0 || pgno>btreePagecount(pBt) ){
44931    return SQLITE_CORRUPT_BKPT;
44932  }
44933  rc = btreeGetPage(pBt, pgno, ppPage, 0);
44934  if( rc==SQLITE_OK ){
44935    rc = btreeInitPage(*ppPage);
44936    if( rc!=SQLITE_OK ){
44937      releasePage(*ppPage);
44938    }
44939  }
44940  return rc;
44941}
44942
44943/*
44944** Release a MemPage.  This should be called once for each prior
44945** call to btreeGetPage.
44946*/
44947static void releasePage(MemPage *pPage){
44948  if( pPage ){
44949    assert( pPage->aData );
44950    assert( pPage->pBt );
44951    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
44952    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
44953    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44954    sqlite3PagerUnref(pPage->pDbPage);
44955  }
44956}
44957
44958/*
44959** During a rollback, when the pager reloads information into the cache
44960** so that the cache is restored to its original state at the start of
44961** the transaction, for each page restored this routine is called.
44962**
44963** This routine needs to reset the extra data section at the end of the
44964** page to agree with the restored data.
44965*/
44966static void pageReinit(DbPage *pData){
44967  MemPage *pPage;
44968  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
44969  assert( sqlite3PagerPageRefcount(pData)>0 );
44970  if( pPage->isInit ){
44971    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44972    pPage->isInit = 0;
44973    if( sqlite3PagerPageRefcount(pData)>1 ){
44974      /* pPage might not be a btree page;  it might be an overflow page
44975      ** or ptrmap page or a free page.  In those cases, the following
44976      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
44977      ** But no harm is done by this.  And it is very important that
44978      ** btreeInitPage() be called on every btree page so we make
44979      ** the call for every page that comes in for re-initing. */
44980      btreeInitPage(pPage);
44981    }
44982  }
44983}
44984
44985/*
44986** Invoke the busy handler for a btree.
44987*/
44988static int btreeInvokeBusyHandler(void *pArg){
44989  BtShared *pBt = (BtShared*)pArg;
44990  assert( pBt->db );
44991  assert( sqlite3_mutex_held(pBt->db->mutex) );
44992  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
44993}
44994
44995/*
44996** Open a database file.
44997**
44998** zFilename is the name of the database file.  If zFilename is NULL
44999** a new database with a random name is created.  This randomly named
45000** database file will be deleted when sqlite3BtreeClose() is called.
45001** If zFilename is ":memory:" then an in-memory database is created
45002** that is automatically destroyed when it is closed.
45003**
45004** If the database is already opened in the same database connection
45005** and we are in shared cache mode, then the open will fail with an
45006** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
45007** objects in the same database connection since doing so will lead
45008** to problems with locking.
45009*/
45010SQLITE_PRIVATE int sqlite3BtreeOpen(
45011  const char *zFilename,  /* Name of the file containing the BTree database */
45012  sqlite3 *db,            /* Associated database handle */
45013  Btree **ppBtree,        /* Pointer to new Btree object written here */
45014  int flags,              /* Options */
45015  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
45016){
45017  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
45018  BtShared *pBt = 0;             /* Shared part of btree structure */
45019  Btree *p;                      /* Handle to return */
45020  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
45021  int rc = SQLITE_OK;            /* Result code from this function */
45022  u8 nReserve;                   /* Byte of unused space on each page */
45023  unsigned char zDbHeader[100];  /* Database header content */
45024
45025  /* Set the variable isMemdb to true for an in-memory database, or
45026  ** false for a file-based database. This symbol is only required if
45027  ** either of the shared-data or autovacuum features are compiled
45028  ** into the library.
45029  */
45030#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
45031  #ifdef SQLITE_OMIT_MEMORYDB
45032    const int isMemdb = 0;
45033  #else
45034    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
45035  #endif
45036#endif
45037
45038  assert( db!=0 );
45039  assert( sqlite3_mutex_held(db->mutex) );
45040
45041  pVfs = db->pVfs;
45042  p = sqlite3MallocZero(sizeof(Btree));
45043  if( !p ){
45044    return SQLITE_NOMEM;
45045  }
45046  p->inTrans = TRANS_NONE;
45047  p->db = db;
45048#ifndef SQLITE_OMIT_SHARED_CACHE
45049  p->lock.pBtree = p;
45050  p->lock.iTable = 1;
45051#endif
45052
45053#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45054  /*
45055  ** If this Btree is a candidate for shared cache, try to find an
45056  ** existing BtShared object that we can share with
45057  */
45058  if( isMemdb==0 && zFilename && zFilename[0] ){
45059    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
45060      int nFullPathname = pVfs->mxPathname+1;
45061      char *zFullPathname = sqlite3Malloc(nFullPathname);
45062      sqlite3_mutex *mutexShared;
45063      p->sharable = 1;
45064      if( !zFullPathname ){
45065        sqlite3_free(p);
45066        return SQLITE_NOMEM;
45067      }
45068      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
45069      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
45070      sqlite3_mutex_enter(mutexOpen);
45071      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45072      sqlite3_mutex_enter(mutexShared);
45073      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
45074        assert( pBt->nRef>0 );
45075        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
45076                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
45077          int iDb;
45078          for(iDb=db->nDb-1; iDb>=0; iDb--){
45079            Btree *pExisting = db->aDb[iDb].pBt;
45080            if( pExisting && pExisting->pBt==pBt ){
45081              sqlite3_mutex_leave(mutexShared);
45082              sqlite3_mutex_leave(mutexOpen);
45083              sqlite3_free(zFullPathname);
45084              sqlite3_free(p);
45085              return SQLITE_CONSTRAINT;
45086            }
45087          }
45088          p->pBt = pBt;
45089          pBt->nRef++;
45090          break;
45091        }
45092      }
45093      sqlite3_mutex_leave(mutexShared);
45094      sqlite3_free(zFullPathname);
45095    }
45096#ifdef SQLITE_DEBUG
45097    else{
45098      /* In debug mode, we mark all persistent databases as sharable
45099      ** even when they are not.  This exercises the locking code and
45100      ** gives more opportunity for asserts(sqlite3_mutex_held())
45101      ** statements to find locking problems.
45102      */
45103      p->sharable = 1;
45104    }
45105#endif
45106  }
45107#endif
45108  if( pBt==0 ){
45109    /*
45110    ** The following asserts make sure that structures used by the btree are
45111    ** the right size.  This is to guard against size changes that result
45112    ** when compiling on a different architecture.
45113    */
45114    assert( sizeof(i64)==8 || sizeof(i64)==4 );
45115    assert( sizeof(u64)==8 || sizeof(u64)==4 );
45116    assert( sizeof(u32)==4 );
45117    assert( sizeof(u16)==2 );
45118    assert( sizeof(Pgno)==4 );
45119
45120    pBt = sqlite3MallocZero( sizeof(*pBt) );
45121    if( pBt==0 ){
45122      rc = SQLITE_NOMEM;
45123      goto btree_open_out;
45124    }
45125    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
45126                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
45127    if( rc==SQLITE_OK ){
45128      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
45129    }
45130    if( rc!=SQLITE_OK ){
45131      goto btree_open_out;
45132    }
45133    pBt->db = db;
45134    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
45135    p->pBt = pBt;
45136
45137    pBt->pCursor = 0;
45138    pBt->pPage1 = 0;
45139    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
45140#ifdef SQLITE_SECURE_DELETE
45141    pBt->secureDelete = 1;
45142#endif
45143    pBt->pageSize = get2byte(&zDbHeader[16]);
45144    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
45145         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
45146      pBt->pageSize = 0;
45147#ifndef SQLITE_OMIT_AUTOVACUUM
45148      /* If the magic name ":memory:" will create an in-memory database, then
45149      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
45150      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
45151      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
45152      ** regular file-name. In this case the auto-vacuum applies as per normal.
45153      */
45154      if( zFilename && !isMemdb ){
45155        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
45156        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
45157      }
45158#endif
45159      nReserve = 0;
45160    }else{
45161      nReserve = zDbHeader[20];
45162      pBt->pageSizeFixed = 1;
45163#ifndef SQLITE_OMIT_AUTOVACUUM
45164      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
45165      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
45166#endif
45167    }
45168    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45169    if( rc ) goto btree_open_out;
45170    pBt->usableSize = pBt->pageSize - nReserve;
45171    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
45172
45173#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45174    /* Add the new BtShared object to the linked list sharable BtShareds.
45175    */
45176    if( p->sharable ){
45177      sqlite3_mutex *mutexShared;
45178      pBt->nRef = 1;
45179      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45180      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
45181        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
45182        if( pBt->mutex==0 ){
45183          rc = SQLITE_NOMEM;
45184          db->mallocFailed = 0;
45185          goto btree_open_out;
45186        }
45187      }
45188      sqlite3_mutex_enter(mutexShared);
45189      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
45190      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
45191      sqlite3_mutex_leave(mutexShared);
45192    }
45193#endif
45194  }
45195
45196#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45197  /* If the new Btree uses a sharable pBtShared, then link the new
45198  ** Btree into the list of all sharable Btrees for the same connection.
45199  ** The list is kept in ascending order by pBt address.
45200  */
45201  if( p->sharable ){
45202    int i;
45203    Btree *pSib;
45204    for(i=0; i<db->nDb; i++){
45205      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
45206        while( pSib->pPrev ){ pSib = pSib->pPrev; }
45207        if( p->pBt<pSib->pBt ){
45208          p->pNext = pSib;
45209          p->pPrev = 0;
45210          pSib->pPrev = p;
45211        }else{
45212          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
45213            pSib = pSib->pNext;
45214          }
45215          p->pNext = pSib->pNext;
45216          p->pPrev = pSib;
45217          if( p->pNext ){
45218            p->pNext->pPrev = p;
45219          }
45220          pSib->pNext = p;
45221        }
45222        break;
45223      }
45224    }
45225  }
45226#endif
45227  *ppBtree = p;
45228
45229btree_open_out:
45230  if( rc!=SQLITE_OK ){
45231    if( pBt && pBt->pPager ){
45232      sqlite3PagerClose(pBt->pPager);
45233    }
45234    sqlite3_free(pBt);
45235    sqlite3_free(p);
45236    *ppBtree = 0;
45237  }
45238  if( mutexOpen ){
45239    assert( sqlite3_mutex_held(mutexOpen) );
45240    sqlite3_mutex_leave(mutexOpen);
45241  }
45242  return rc;
45243}
45244
45245/*
45246** Decrement the BtShared.nRef counter.  When it reaches zero,
45247** remove the BtShared structure from the sharing list.  Return
45248** true if the BtShared.nRef counter reaches zero and return
45249** false if it is still positive.
45250*/
45251static int removeFromSharingList(BtShared *pBt){
45252#ifndef SQLITE_OMIT_SHARED_CACHE
45253  sqlite3_mutex *pMaster;
45254  BtShared *pList;
45255  int removed = 0;
45256
45257  assert( sqlite3_mutex_notheld(pBt->mutex) );
45258  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45259  sqlite3_mutex_enter(pMaster);
45260  pBt->nRef--;
45261  if( pBt->nRef<=0 ){
45262    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
45263      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
45264    }else{
45265      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
45266      while( ALWAYS(pList) && pList->pNext!=pBt ){
45267        pList=pList->pNext;
45268      }
45269      if( ALWAYS(pList) ){
45270        pList->pNext = pBt->pNext;
45271      }
45272    }
45273    if( SQLITE_THREADSAFE ){
45274      sqlite3_mutex_free(pBt->mutex);
45275    }
45276    removed = 1;
45277  }
45278  sqlite3_mutex_leave(pMaster);
45279  return removed;
45280#else
45281  return 1;
45282#endif
45283}
45284
45285/*
45286** Make sure pBt->pTmpSpace points to an allocation of
45287** MX_CELL_SIZE(pBt) bytes.
45288*/
45289static void allocateTempSpace(BtShared *pBt){
45290  if( !pBt->pTmpSpace ){
45291    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
45292  }
45293}
45294
45295/*
45296** Free the pBt->pTmpSpace allocation
45297*/
45298static void freeTempSpace(BtShared *pBt){
45299  sqlite3PageFree( pBt->pTmpSpace);
45300  pBt->pTmpSpace = 0;
45301}
45302
45303/*
45304** Close an open database and invalidate all cursors.
45305*/
45306SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
45307  BtShared *pBt = p->pBt;
45308  BtCursor *pCur;
45309
45310  /* Close all cursors opened via this handle.  */
45311  assert( sqlite3_mutex_held(p->db->mutex) );
45312  sqlite3BtreeEnter(p);
45313  pCur = pBt->pCursor;
45314  while( pCur ){
45315    BtCursor *pTmp = pCur;
45316    pCur = pCur->pNext;
45317    if( pTmp->pBtree==p ){
45318      sqlite3BtreeCloseCursor(pTmp);
45319    }
45320  }
45321
45322  /* Rollback any active transaction and free the handle structure.
45323  ** The call to sqlite3BtreeRollback() drops any table-locks held by
45324  ** this handle.
45325  */
45326  sqlite3BtreeRollback(p);
45327  sqlite3BtreeLeave(p);
45328
45329  /* If there are still other outstanding references to the shared-btree
45330  ** structure, return now. The remainder of this procedure cleans
45331  ** up the shared-btree.
45332  */
45333  assert( p->wantToLock==0 && p->locked==0 );
45334  if( !p->sharable || removeFromSharingList(pBt) ){
45335    /* The pBt is no longer on the sharing list, so we can access
45336    ** it without having to hold the mutex.
45337    **
45338    ** Clean out and delete the BtShared object.
45339    */
45340    assert( !pBt->pCursor );
45341    sqlite3PagerClose(pBt->pPager);
45342    if( pBt->xFreeSchema && pBt->pSchema ){
45343      pBt->xFreeSchema(pBt->pSchema);
45344    }
45345    sqlite3_free(pBt->pSchema);
45346    freeTempSpace(pBt);
45347    sqlite3_free(pBt);
45348  }
45349
45350#ifndef SQLITE_OMIT_SHARED_CACHE
45351  assert( p->wantToLock==0 );
45352  assert( p->locked==0 );
45353  if( p->pPrev ) p->pPrev->pNext = p->pNext;
45354  if( p->pNext ) p->pNext->pPrev = p->pPrev;
45355#endif
45356
45357  sqlite3_free(p);
45358  return SQLITE_OK;
45359}
45360
45361/*
45362** Change the limit on the number of pages allowed in the cache.
45363**
45364** The maximum number of cache pages is set to the absolute
45365** value of mxPage.  If mxPage is negative, the pager will
45366** operate asynchronously - it will not stop to do fsync()s
45367** to insure data is written to the disk surface before
45368** continuing.  Transactions still work if synchronous is off,
45369** and the database cannot be corrupted if this program
45370** crashes.  But if the operating system crashes or there is
45371** an abrupt power failure when synchronous is off, the database
45372** could be left in an inconsistent and unrecoverable state.
45373** Synchronous is on by default so database corruption is not
45374** normally a worry.
45375*/
45376SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
45377  BtShared *pBt = p->pBt;
45378  assert( sqlite3_mutex_held(p->db->mutex) );
45379  sqlite3BtreeEnter(p);
45380  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
45381  sqlite3BtreeLeave(p);
45382  return SQLITE_OK;
45383}
45384
45385/*
45386** Change the way data is synced to disk in order to increase or decrease
45387** how well the database resists damage due to OS crashes and power
45388** failures.  Level 1 is the same as asynchronous (no syncs() occur and
45389** there is a high probability of damage)  Level 2 is the default.  There
45390** is a very low but non-zero probability of damage.  Level 3 reduces the
45391** probability of damage to near zero but with a write performance reduction.
45392*/
45393#ifndef SQLITE_OMIT_PAGER_PRAGMAS
45394SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
45395  BtShared *pBt = p->pBt;
45396  assert( sqlite3_mutex_held(p->db->mutex) );
45397  sqlite3BtreeEnter(p);
45398  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
45399  sqlite3BtreeLeave(p);
45400  return SQLITE_OK;
45401}
45402#endif
45403
45404/*
45405** Return TRUE if the given btree is set to safety level 1.  In other
45406** words, return TRUE if no sync() occurs on the disk files.
45407*/
45408SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
45409  BtShared *pBt = p->pBt;
45410  int rc;
45411  assert( sqlite3_mutex_held(p->db->mutex) );
45412  sqlite3BtreeEnter(p);
45413  assert( pBt && pBt->pPager );
45414  rc = sqlite3PagerNosync(pBt->pPager);
45415  sqlite3BtreeLeave(p);
45416  return rc;
45417}
45418
45419#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
45420/*
45421** Change the default pages size and the number of reserved bytes per page.
45422** Or, if the page size has already been fixed, return SQLITE_READONLY
45423** without changing anything.
45424**
45425** The page size must be a power of 2 between 512 and 65536.  If the page
45426** size supplied does not meet this constraint then the page size is not
45427** changed.
45428**
45429** Page sizes are constrained to be a power of two so that the region
45430** of the database file used for locking (beginning at PENDING_BYTE,
45431** the first byte past the 1GB boundary, 0x40000000) needs to occur
45432** at the beginning of a page.
45433**
45434** If parameter nReserve is less than zero, then the number of reserved
45435** bytes per page is left unchanged.
45436**
45437** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
45438** and autovacuum mode can no longer be changed.
45439*/
45440SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
45441  int rc = SQLITE_OK;
45442  BtShared *pBt = p->pBt;
45443  assert( nReserve>=-1 && nReserve<=255 );
45444  sqlite3BtreeEnter(p);
45445  if( pBt->pageSizeFixed ){
45446    sqlite3BtreeLeave(p);
45447    return SQLITE_READONLY;
45448  }
45449  if( nReserve<0 ){
45450    nReserve = pBt->pageSize - pBt->usableSize;
45451  }
45452  assert( nReserve>=0 && nReserve<=255 );
45453  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
45454        ((pageSize-1)&pageSize)==0 ){
45455    assert( (pageSize & 7)==0 );
45456    assert( !pBt->pPage1 && !pBt->pCursor );
45457    pBt->pageSize = (u16)pageSize;
45458    freeTempSpace(pBt);
45459  }
45460  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45461  pBt->usableSize = pBt->pageSize - (u16)nReserve;
45462  if( iFix ) pBt->pageSizeFixed = 1;
45463  sqlite3BtreeLeave(p);
45464  return rc;
45465}
45466
45467/*
45468** Return the currently defined page size
45469*/
45470SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
45471  return p->pBt->pageSize;
45472}
45473
45474/*
45475** Return the number of bytes of space at the end of every page that
45476** are intentually left unused.  This is the "reserved" space that is
45477** sometimes used by extensions.
45478*/
45479SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
45480  int n;
45481  sqlite3BtreeEnter(p);
45482  n = p->pBt->pageSize - p->pBt->usableSize;
45483  sqlite3BtreeLeave(p);
45484  return n;
45485}
45486
45487/*
45488** Set the maximum page count for a database if mxPage is positive.
45489** No changes are made if mxPage is 0 or negative.
45490** Regardless of the value of mxPage, return the maximum page count.
45491*/
45492SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
45493  int n;
45494  sqlite3BtreeEnter(p);
45495  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
45496  sqlite3BtreeLeave(p);
45497  return n;
45498}
45499
45500/*
45501** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
45502** then make no changes.  Always return the value of the secureDelete
45503** setting after the change.
45504*/
45505SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
45506  int b;
45507  if( p==0 ) return 0;
45508  sqlite3BtreeEnter(p);
45509  if( newFlag>=0 ){
45510    p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
45511  }
45512  b = p->pBt->secureDelete;
45513  sqlite3BtreeLeave(p);
45514  return b;
45515}
45516#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
45517
45518/*
45519** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
45520** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
45521** is disabled. The default value for the auto-vacuum property is
45522** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
45523*/
45524SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
45525#ifdef SQLITE_OMIT_AUTOVACUUM
45526  return SQLITE_READONLY;
45527#else
45528  BtShared *pBt = p->pBt;
45529  int rc = SQLITE_OK;
45530  u8 av = (u8)autoVacuum;
45531
45532  sqlite3BtreeEnter(p);
45533  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
45534    rc = SQLITE_READONLY;
45535  }else{
45536    pBt->autoVacuum = av ?1:0;
45537    pBt->incrVacuum = av==2 ?1:0;
45538  }
45539  sqlite3BtreeLeave(p);
45540  return rc;
45541#endif
45542}
45543
45544/*
45545** Return the value of the 'auto-vacuum' property. If auto-vacuum is
45546** enabled 1 is returned. Otherwise 0.
45547*/
45548SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
45549#ifdef SQLITE_OMIT_AUTOVACUUM
45550  return BTREE_AUTOVACUUM_NONE;
45551#else
45552  int rc;
45553  sqlite3BtreeEnter(p);
45554  rc = (
45555    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
45556    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
45557    BTREE_AUTOVACUUM_INCR
45558  );
45559  sqlite3BtreeLeave(p);
45560  return rc;
45561#endif
45562}
45563
45564
45565/*
45566** Get a reference to pPage1 of the database file.  This will
45567** also acquire a readlock on that file.
45568**
45569** SQLITE_OK is returned on success.  If the file is not a
45570** well-formed database file, then SQLITE_CORRUPT is returned.
45571** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
45572** is returned if we run out of memory.
45573*/
45574static int lockBtree(BtShared *pBt){
45575  int rc;              /* Result code from subfunctions */
45576  MemPage *pPage1;     /* Page 1 of the database file */
45577  int nPage;           /* Number of pages in the database */
45578  int nPageFile = 0;   /* Number of pages in the database file */
45579  int nPageHeader;     /* Number of pages in the database according to hdr */
45580
45581  assert( sqlite3_mutex_held(pBt->mutex) );
45582  assert( pBt->pPage1==0 );
45583  rc = sqlite3PagerSharedLock(pBt->pPager);
45584  if( rc!=SQLITE_OK ) return rc;
45585  rc = btreeGetPage(pBt, 1, &pPage1, 0);
45586  if( rc!=SQLITE_OK ) return rc;
45587
45588  /* Do some checking to help insure the file we opened really is
45589  ** a valid database file.
45590  */
45591  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
45592  if( (rc = sqlite3PagerPagecount(pBt->pPager, &nPageFile))!=SQLITE_OK ){;
45593    goto page1_init_failed;
45594  }
45595  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
45596    nPage = nPageFile;
45597  }
45598  if( nPage>0 ){
45599    int pageSize;
45600    int usableSize;
45601    u8 *page1 = pPage1->aData;
45602    rc = SQLITE_NOTADB;
45603    if( memcmp(page1, zMagicHeader, 16)!=0 ){
45604      goto page1_init_failed;
45605    }
45606
45607#ifdef SQLITE_OMIT_WAL
45608    if( page1[18]>1 ){
45609      pBt->readOnly = 1;
45610    }
45611    if( page1[19]>1 ){
45612      goto page1_init_failed;
45613    }
45614#else
45615    if( page1[18]>2 ){
45616      pBt->readOnly = 1;
45617    }
45618    if( page1[19]>2 ){
45619      goto page1_init_failed;
45620    }
45621
45622    /* If the write version is set to 2, this database should be accessed
45623    ** in WAL mode. If the log is not already open, open it now. Then
45624    ** return SQLITE_OK and return without populating BtShared.pPage1.
45625    ** The caller detects this and calls this function again. This is
45626    ** required as the version of page 1 currently in the page1 buffer
45627    ** may not be the latest version - there may be a newer one in the log
45628    ** file.
45629    */
45630    if( page1[19]==2 && pBt->doNotUseWAL==0 ){
45631      int isOpen = 0;
45632      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
45633      if( rc!=SQLITE_OK ){
45634        goto page1_init_failed;
45635      }else if( isOpen==0 ){
45636        releasePage(pPage1);
45637        return SQLITE_OK;
45638      }
45639      rc = SQLITE_NOTADB;
45640    }
45641#endif
45642
45643    /* The maximum embedded fraction must be exactly 25%.  And the minimum
45644    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
45645    ** The original design allowed these amounts to vary, but as of
45646    ** version 3.6.0, we require them to be fixed.
45647    */
45648    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
45649      goto page1_init_failed;
45650    }
45651    pageSize = get2byte(&page1[16]);
45652    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
45653        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
45654    ){
45655      goto page1_init_failed;
45656    }
45657    assert( (pageSize & 7)==0 );
45658    usableSize = pageSize - page1[20];
45659    if( pageSize!=pBt->pageSize ){
45660      /* After reading the first page of the database assuming a page size
45661      ** of BtShared.pageSize, we have discovered that the page-size is
45662      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
45663      ** zero and return SQLITE_OK. The caller will call this function
45664      ** again with the correct page-size.
45665      */
45666      releasePage(pPage1);
45667      pBt->usableSize = (u16)usableSize;
45668      pBt->pageSize = (u16)pageSize;
45669      freeTempSpace(pBt);
45670      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
45671                                   pageSize-usableSize);
45672      return rc;
45673    }
45674    if( nPageHeader>nPageFile ){
45675      rc = SQLITE_CORRUPT_BKPT;
45676      goto page1_init_failed;
45677    }
45678    if( usableSize<480 ){
45679      goto page1_init_failed;
45680    }
45681    pBt->pageSize = (u16)pageSize;
45682    pBt->usableSize = (u16)usableSize;
45683#ifndef SQLITE_OMIT_AUTOVACUUM
45684    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
45685    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
45686#endif
45687  }
45688
45689  /* maxLocal is the maximum amount of payload to store locally for
45690  ** a cell.  Make sure it is small enough so that at least minFanout
45691  ** cells can will fit on one page.  We assume a 10-byte page header.
45692  ** Besides the payload, the cell must store:
45693  **     2-byte pointer to the cell
45694  **     4-byte child pointer
45695  **     9-byte nKey value
45696  **     4-byte nData value
45697  **     4-byte overflow page pointer
45698  ** So a cell consists of a 2-byte poiner, a header which is as much as
45699  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
45700  ** page pointer.
45701  */
45702  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
45703  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
45704  pBt->maxLeaf = pBt->usableSize - 35;
45705  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
45706  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
45707  pBt->pPage1 = pPage1;
45708  pBt->nPage = nPage;
45709  return SQLITE_OK;
45710
45711page1_init_failed:
45712  releasePage(pPage1);
45713  pBt->pPage1 = 0;
45714  return rc;
45715}
45716
45717/*
45718** If there are no outstanding cursors and we are not in the middle
45719** of a transaction but there is a read lock on the database, then
45720** this routine unrefs the first page of the database file which
45721** has the effect of releasing the read lock.
45722**
45723** If there is a transaction in progress, this routine is a no-op.
45724*/
45725static void unlockBtreeIfUnused(BtShared *pBt){
45726  assert( sqlite3_mutex_held(pBt->mutex) );
45727  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
45728  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
45729    assert( pBt->pPage1->aData );
45730    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
45731    assert( pBt->pPage1->aData );
45732    releasePage(pBt->pPage1);
45733    pBt->pPage1 = 0;
45734  }
45735}
45736
45737/*
45738** If pBt points to an empty file then convert that empty file
45739** into a new empty database by initializing the first page of
45740** the database.
45741*/
45742static int newDatabase(BtShared *pBt){
45743  MemPage *pP1;
45744  unsigned char *data;
45745  int rc;
45746
45747  assert( sqlite3_mutex_held(pBt->mutex) );
45748  if( pBt->nPage>0 ){
45749    return SQLITE_OK;
45750  }
45751  pP1 = pBt->pPage1;
45752  assert( pP1!=0 );
45753  data = pP1->aData;
45754  rc = sqlite3PagerWrite(pP1->pDbPage);
45755  if( rc ) return rc;
45756  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
45757  assert( sizeof(zMagicHeader)==16 );
45758  put2byte(&data[16], pBt->pageSize);
45759  data[18] = 1;
45760  data[19] = 1;
45761  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
45762  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
45763  data[21] = 64;
45764  data[22] = 32;
45765  data[23] = 32;
45766  memset(&data[24], 0, 100-24);
45767  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
45768  pBt->pageSizeFixed = 1;
45769#ifndef SQLITE_OMIT_AUTOVACUUM
45770  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
45771  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
45772  put4byte(&data[36 + 4*4], pBt->autoVacuum);
45773  put4byte(&data[36 + 7*4], pBt->incrVacuum);
45774#endif
45775  pBt->nPage = 1;
45776  data[31] = 1;
45777  return SQLITE_OK;
45778}
45779
45780/*
45781** Attempt to start a new transaction. A write-transaction
45782** is started if the second argument is nonzero, otherwise a read-
45783** transaction.  If the second argument is 2 or more and exclusive
45784** transaction is started, meaning that no other process is allowed
45785** to access the database.  A preexisting transaction may not be
45786** upgraded to exclusive by calling this routine a second time - the
45787** exclusivity flag only works for a new transaction.
45788**
45789** A write-transaction must be started before attempting any
45790** changes to the database.  None of the following routines
45791** will work unless a transaction is started first:
45792**
45793**      sqlite3BtreeCreateTable()
45794**      sqlite3BtreeCreateIndex()
45795**      sqlite3BtreeClearTable()
45796**      sqlite3BtreeDropTable()
45797**      sqlite3BtreeInsert()
45798**      sqlite3BtreeDelete()
45799**      sqlite3BtreeUpdateMeta()
45800**
45801** If an initial attempt to acquire the lock fails because of lock contention
45802** and the database was previously unlocked, then invoke the busy handler
45803** if there is one.  But if there was previously a read-lock, do not
45804** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
45805** returned when there is already a read-lock in order to avoid a deadlock.
45806**
45807** Suppose there are two processes A and B.  A has a read lock and B has
45808** a reserved lock.  B tries to promote to exclusive but is blocked because
45809** of A's read lock.  A tries to promote to reserved but is blocked by B.
45810** One or the other of the two processes must give way or there can be
45811** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
45812** when A already has a read lock, we encourage A to give up and let B
45813** proceed.
45814*/
45815SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
45816  sqlite3 *pBlock = 0;
45817  BtShared *pBt = p->pBt;
45818  int rc = SQLITE_OK;
45819
45820  sqlite3BtreeEnter(p);
45821  btreeIntegrity(p);
45822
45823  /* If the btree is already in a write-transaction, or it
45824  ** is already in a read-transaction and a read-transaction
45825  ** is requested, this is a no-op.
45826  */
45827  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
45828    goto trans_begun;
45829  }
45830
45831  /* Write transactions are not possible on a read-only database */
45832  if( pBt->readOnly && wrflag ){
45833    rc = SQLITE_READONLY;
45834    goto trans_begun;
45835  }
45836
45837#ifndef SQLITE_OMIT_SHARED_CACHE
45838  /* If another database handle has already opened a write transaction
45839  ** on this shared-btree structure and a second write transaction is
45840  ** requested, return SQLITE_LOCKED.
45841  */
45842  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
45843    pBlock = pBt->pWriter->db;
45844  }else if( wrflag>1 ){
45845    BtLock *pIter;
45846    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45847      if( pIter->pBtree!=p ){
45848        pBlock = pIter->pBtree->db;
45849        break;
45850      }
45851    }
45852  }
45853  if( pBlock ){
45854    sqlite3ConnectionBlocked(p->db, pBlock);
45855    rc = SQLITE_LOCKED_SHAREDCACHE;
45856    goto trans_begun;
45857  }
45858#endif
45859
45860  /* Any read-only or read-write transaction implies a read-lock on
45861  ** page 1. So if some other shared-cache client already has a write-lock
45862  ** on page 1, the transaction cannot be opened. */
45863  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45864  if( SQLITE_OK!=rc ) goto trans_begun;
45865
45866  pBt->initiallyEmpty = pBt->nPage==0;
45867  do {
45868    /* Call lockBtree() until either pBt->pPage1 is populated or
45869    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
45870    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
45871    ** reading page 1 it discovers that the page-size of the database
45872    ** file is not pBt->pageSize. In this case lockBtree() will update
45873    ** pBt->pageSize to the page-size of the file on disk.
45874    */
45875    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
45876
45877    if( rc==SQLITE_OK && wrflag ){
45878      if( pBt->readOnly ){
45879        rc = SQLITE_READONLY;
45880      }else{
45881        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
45882        if( rc==SQLITE_OK ){
45883          rc = newDatabase(pBt);
45884        }
45885      }
45886    }
45887
45888    if( rc!=SQLITE_OK ){
45889      unlockBtreeIfUnused(pBt);
45890    }
45891  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
45892          btreeInvokeBusyHandler(pBt) );
45893
45894  if( rc==SQLITE_OK ){
45895    if( p->inTrans==TRANS_NONE ){
45896      pBt->nTransaction++;
45897#ifndef SQLITE_OMIT_SHARED_CACHE
45898      if( p->sharable ){
45899	assert( p->lock.pBtree==p && p->lock.iTable==1 );
45900        p->lock.eLock = READ_LOCK;
45901        p->lock.pNext = pBt->pLock;
45902        pBt->pLock = &p->lock;
45903      }
45904#endif
45905    }
45906    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
45907    if( p->inTrans>pBt->inTransaction ){
45908      pBt->inTransaction = p->inTrans;
45909    }
45910#ifndef SQLITE_OMIT_SHARED_CACHE
45911    if( wrflag ){
45912      assert( !pBt->pWriter );
45913      pBt->pWriter = p;
45914      pBt->isExclusive = (u8)(wrflag>1);
45915    }
45916#endif
45917  }
45918
45919
45920trans_begun:
45921  if( rc==SQLITE_OK && wrflag ){
45922    /* This call makes sure that the pager has the correct number of
45923    ** open savepoints. If the second parameter is greater than 0 and
45924    ** the sub-journal is not already open, then it will be opened here.
45925    */
45926    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
45927  }
45928
45929  btreeIntegrity(p);
45930  sqlite3BtreeLeave(p);
45931  return rc;
45932}
45933
45934#ifndef SQLITE_OMIT_AUTOVACUUM
45935
45936/*
45937** Set the pointer-map entries for all children of page pPage. Also, if
45938** pPage contains cells that point to overflow pages, set the pointer
45939** map entries for the overflow pages as well.
45940*/
45941static int setChildPtrmaps(MemPage *pPage){
45942  int i;                             /* Counter variable */
45943  int nCell;                         /* Number of cells in page pPage */
45944  int rc;                            /* Return code */
45945  BtShared *pBt = pPage->pBt;
45946  u8 isInitOrig = pPage->isInit;
45947  Pgno pgno = pPage->pgno;
45948
45949  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45950  rc = btreeInitPage(pPage);
45951  if( rc!=SQLITE_OK ){
45952    goto set_child_ptrmaps_out;
45953  }
45954  nCell = pPage->nCell;
45955
45956  for(i=0; i<nCell; i++){
45957    u8 *pCell = findCell(pPage, i);
45958
45959    ptrmapPutOvflPtr(pPage, pCell, &rc);
45960
45961    if( !pPage->leaf ){
45962      Pgno childPgno = get4byte(pCell);
45963      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
45964    }
45965  }
45966
45967  if( !pPage->leaf ){
45968    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45969    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
45970  }
45971
45972set_child_ptrmaps_out:
45973  pPage->isInit = isInitOrig;
45974  return rc;
45975}
45976
45977/*
45978** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
45979** that it points to iTo. Parameter eType describes the type of pointer to
45980** be modified, as  follows:
45981**
45982** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
45983**                   page of pPage.
45984**
45985** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
45986**                   page pointed to by one of the cells on pPage.
45987**
45988** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
45989**                   overflow page in the list.
45990*/
45991static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
45992  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45993  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45994  if( eType==PTRMAP_OVERFLOW2 ){
45995    /* The pointer is always the first 4 bytes of the page in this case.  */
45996    if( get4byte(pPage->aData)!=iFrom ){
45997      return SQLITE_CORRUPT_BKPT;
45998    }
45999    put4byte(pPage->aData, iTo);
46000  }else{
46001    u8 isInitOrig = pPage->isInit;
46002    int i;
46003    int nCell;
46004
46005    btreeInitPage(pPage);
46006    nCell = pPage->nCell;
46007
46008    for(i=0; i<nCell; i++){
46009      u8 *pCell = findCell(pPage, i);
46010      if( eType==PTRMAP_OVERFLOW1 ){
46011        CellInfo info;
46012        btreeParseCellPtr(pPage, pCell, &info);
46013        if( info.iOverflow ){
46014          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
46015            put4byte(&pCell[info.iOverflow], iTo);
46016            break;
46017          }
46018        }
46019      }else{
46020        if( get4byte(pCell)==iFrom ){
46021          put4byte(pCell, iTo);
46022          break;
46023        }
46024      }
46025    }
46026
46027    if( i==nCell ){
46028      if( eType!=PTRMAP_BTREE ||
46029          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
46030        return SQLITE_CORRUPT_BKPT;
46031      }
46032      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
46033    }
46034
46035    pPage->isInit = isInitOrig;
46036  }
46037  return SQLITE_OK;
46038}
46039
46040
46041/*
46042** Move the open database page pDbPage to location iFreePage in the
46043** database. The pDbPage reference remains valid.
46044**
46045** The isCommit flag indicates that there is no need to remember that
46046** the journal needs to be sync()ed before database page pDbPage->pgno
46047** can be written to. The caller has already promised not to write to that
46048** page.
46049*/
46050static int relocatePage(
46051  BtShared *pBt,           /* Btree */
46052  MemPage *pDbPage,        /* Open page to move */
46053  u8 eType,                /* Pointer map 'type' entry for pDbPage */
46054  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
46055  Pgno iFreePage,          /* The location to move pDbPage to */
46056  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
46057){
46058  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
46059  Pgno iDbPage = pDbPage->pgno;
46060  Pager *pPager = pBt->pPager;
46061  int rc;
46062
46063  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
46064      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
46065  assert( sqlite3_mutex_held(pBt->mutex) );
46066  assert( pDbPage->pBt==pBt );
46067
46068  /* Move page iDbPage from its current location to page number iFreePage */
46069  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
46070      iDbPage, iFreePage, iPtrPage, eType));
46071  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
46072  if( rc!=SQLITE_OK ){
46073    return rc;
46074  }
46075  pDbPage->pgno = iFreePage;
46076
46077  /* If pDbPage was a btree-page, then it may have child pages and/or cells
46078  ** that point to overflow pages. The pointer map entries for all these
46079  ** pages need to be changed.
46080  **
46081  ** If pDbPage is an overflow page, then the first 4 bytes may store a
46082  ** pointer to a subsequent overflow page. If this is the case, then
46083  ** the pointer map needs to be updated for the subsequent overflow page.
46084  */
46085  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
46086    rc = setChildPtrmaps(pDbPage);
46087    if( rc!=SQLITE_OK ){
46088      return rc;
46089    }
46090  }else{
46091    Pgno nextOvfl = get4byte(pDbPage->aData);
46092    if( nextOvfl!=0 ){
46093      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
46094      if( rc!=SQLITE_OK ){
46095        return rc;
46096      }
46097    }
46098  }
46099
46100  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
46101  ** that it points at iFreePage. Also fix the pointer map entry for
46102  ** iPtrPage.
46103  */
46104  if( eType!=PTRMAP_ROOTPAGE ){
46105    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
46106    if( rc!=SQLITE_OK ){
46107      return rc;
46108    }
46109    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
46110    if( rc!=SQLITE_OK ){
46111      releasePage(pPtrPage);
46112      return rc;
46113    }
46114    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
46115    releasePage(pPtrPage);
46116    if( rc==SQLITE_OK ){
46117      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
46118    }
46119  }
46120  return rc;
46121}
46122
46123/* Forward declaration required by incrVacuumStep(). */
46124static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
46125
46126/*
46127** Perform a single step of an incremental-vacuum. If successful,
46128** return SQLITE_OK. If there is no work to do (and therefore no
46129** point in calling this function again), return SQLITE_DONE.
46130**
46131** More specificly, this function attempts to re-organize the
46132** database so that the last page of the file currently in use
46133** is no longer in use.
46134**
46135** If the nFin parameter is non-zero, this function assumes
46136** that the caller will keep calling incrVacuumStep() until
46137** it returns SQLITE_DONE or an error, and that nFin is the
46138** number of pages the database file will contain after this
46139** process is complete.  If nFin is zero, it is assumed that
46140** incrVacuumStep() will be called a finite amount of times
46141** which may or may not empty the freelist.  A full autovacuum
46142** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
46143*/
46144static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
46145  Pgno nFreeList;           /* Number of pages still on the free-list */
46146  int rc;
46147
46148  assert( sqlite3_mutex_held(pBt->mutex) );
46149  assert( iLastPg>nFin );
46150
46151  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
46152    u8 eType;
46153    Pgno iPtrPage;
46154
46155    nFreeList = get4byte(&pBt->pPage1->aData[36]);
46156    if( nFreeList==0 ){
46157      return SQLITE_DONE;
46158    }
46159
46160    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
46161    if( rc!=SQLITE_OK ){
46162      return rc;
46163    }
46164    if( eType==PTRMAP_ROOTPAGE ){
46165      return SQLITE_CORRUPT_BKPT;
46166    }
46167
46168    if( eType==PTRMAP_FREEPAGE ){
46169      if( nFin==0 ){
46170        /* Remove the page from the files free-list. This is not required
46171        ** if nFin is non-zero. In that case, the free-list will be
46172        ** truncated to zero after this function returns, so it doesn't
46173        ** matter if it still contains some garbage entries.
46174        */
46175        Pgno iFreePg;
46176        MemPage *pFreePg;
46177        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
46178        if( rc!=SQLITE_OK ){
46179          return rc;
46180        }
46181        assert( iFreePg==iLastPg );
46182        releasePage(pFreePg);
46183      }
46184    } else {
46185      Pgno iFreePg;             /* Index of free page to move pLastPg to */
46186      MemPage *pLastPg;
46187
46188      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
46189      if( rc!=SQLITE_OK ){
46190        return rc;
46191      }
46192
46193      /* If nFin is zero, this loop runs exactly once and page pLastPg
46194      ** is swapped with the first free page pulled off the free list.
46195      **
46196      ** On the other hand, if nFin is greater than zero, then keep
46197      ** looping until a free-page located within the first nFin pages
46198      ** of the file is found.
46199      */
46200      do {
46201        MemPage *pFreePg;
46202        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
46203        if( rc!=SQLITE_OK ){
46204          releasePage(pLastPg);
46205          return rc;
46206        }
46207        releasePage(pFreePg);
46208      }while( nFin!=0 && iFreePg>nFin );
46209      assert( iFreePg<iLastPg );
46210
46211      rc = sqlite3PagerWrite(pLastPg->pDbPage);
46212      if( rc==SQLITE_OK ){
46213        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
46214      }
46215      releasePage(pLastPg);
46216      if( rc!=SQLITE_OK ){
46217        return rc;
46218      }
46219    }
46220  }
46221
46222  if( nFin==0 ){
46223    iLastPg--;
46224    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
46225      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
46226        MemPage *pPg;
46227        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
46228        if( rc!=SQLITE_OK ){
46229          return rc;
46230        }
46231        rc = sqlite3PagerWrite(pPg->pDbPage);
46232        releasePage(pPg);
46233        if( rc!=SQLITE_OK ){
46234          return rc;
46235        }
46236      }
46237      iLastPg--;
46238    }
46239    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
46240    pBt->nPage = iLastPg;
46241  }
46242  return SQLITE_OK;
46243}
46244
46245/*
46246** A write-transaction must be opened before calling this function.
46247** It performs a single unit of work towards an incremental vacuum.
46248**
46249** If the incremental vacuum is finished after this function has run,
46250** SQLITE_DONE is returned. If it is not finished, but no error occurred,
46251** SQLITE_OK is returned. Otherwise an SQLite error code.
46252*/
46253SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
46254  int rc;
46255  BtShared *pBt = p->pBt;
46256
46257  sqlite3BtreeEnter(p);
46258  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
46259  if( !pBt->autoVacuum ){
46260    rc = SQLITE_DONE;
46261  }else{
46262    invalidateAllOverflowCache(pBt);
46263    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
46264    if( rc==SQLITE_OK ){
46265      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46266      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
46267    }
46268  }
46269  sqlite3BtreeLeave(p);
46270  return rc;
46271}
46272
46273/*
46274** This routine is called prior to sqlite3PagerCommit when a transaction
46275** is commited for an auto-vacuum database.
46276**
46277** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
46278** the database file should be truncated to during the commit process.
46279** i.e. the database has been reorganized so that only the first *pnTrunc
46280** pages are in use.
46281*/
46282static int autoVacuumCommit(BtShared *pBt){
46283  int rc = SQLITE_OK;
46284  Pager *pPager = pBt->pPager;
46285  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
46286
46287  assert( sqlite3_mutex_held(pBt->mutex) );
46288  invalidateAllOverflowCache(pBt);
46289  assert(pBt->autoVacuum);
46290  if( !pBt->incrVacuum ){
46291    Pgno nFin;         /* Number of pages in database after autovacuuming */
46292    Pgno nFree;        /* Number of pages on the freelist initially */
46293    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
46294    Pgno iFree;        /* The next page to be freed */
46295    int nEntry;        /* Number of entries on one ptrmap page */
46296    Pgno nOrig;        /* Database size before freeing */
46297
46298    nOrig = btreePagecount(pBt);
46299    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
46300      /* It is not possible to create a database for which the final page
46301      ** is either a pointer-map page or the pending-byte page. If one
46302      ** is encountered, this indicates corruption.
46303      */
46304      return SQLITE_CORRUPT_BKPT;
46305    }
46306
46307    nFree = get4byte(&pBt->pPage1->aData[36]);
46308    nEntry = pBt->usableSize/5;
46309    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
46310    nFin = nOrig - nFree - nPtrmap;
46311    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
46312      nFin--;
46313    }
46314    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
46315      nFin--;
46316    }
46317    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
46318
46319    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
46320      rc = incrVacuumStep(pBt, nFin, iFree);
46321    }
46322    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
46323      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46324      put4byte(&pBt->pPage1->aData[32], 0);
46325      put4byte(&pBt->pPage1->aData[36], 0);
46326      put4byte(&pBt->pPage1->aData[28], nFin);
46327      sqlite3PagerTruncateImage(pBt->pPager, nFin);
46328      pBt->nPage = nFin;
46329    }
46330    if( rc!=SQLITE_OK ){
46331      sqlite3PagerRollback(pPager);
46332    }
46333  }
46334
46335  assert( nRef==sqlite3PagerRefcount(pPager) );
46336  return rc;
46337}
46338
46339#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
46340# define setChildPtrmaps(x) SQLITE_OK
46341#endif
46342
46343/*
46344** This routine does the first phase of a two-phase commit.  This routine
46345** causes a rollback journal to be created (if it does not already exist)
46346** and populated with enough information so that if a power loss occurs
46347** the database can be restored to its original state by playing back
46348** the journal.  Then the contents of the journal are flushed out to
46349** the disk.  After the journal is safely on oxide, the changes to the
46350** database are written into the database file and flushed to oxide.
46351** At the end of this call, the rollback journal still exists on the
46352** disk and we are still holding all locks, so the transaction has not
46353** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
46354** commit process.
46355**
46356** This call is a no-op if no write-transaction is currently active on pBt.
46357**
46358** Otherwise, sync the database file for the btree pBt. zMaster points to
46359** the name of a master journal file that should be written into the
46360** individual journal file, or is NULL, indicating no master journal file
46361** (single database transaction).
46362**
46363** When this is called, the master journal should already have been
46364** created, populated with this journal pointer and synced to disk.
46365**
46366** Once this is routine has returned, the only thing required to commit
46367** the write-transaction for this database file is to delete the journal.
46368*/
46369SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
46370  int rc = SQLITE_OK;
46371  if( p->inTrans==TRANS_WRITE ){
46372    BtShared *pBt = p->pBt;
46373    sqlite3BtreeEnter(p);
46374#ifndef SQLITE_OMIT_AUTOVACUUM
46375    if( pBt->autoVacuum ){
46376      rc = autoVacuumCommit(pBt);
46377      if( rc!=SQLITE_OK ){
46378        sqlite3BtreeLeave(p);
46379        return rc;
46380      }
46381    }
46382#endif
46383    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
46384    sqlite3BtreeLeave(p);
46385  }
46386  return rc;
46387}
46388
46389/*
46390** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
46391** at the conclusion of a transaction.
46392*/
46393static void btreeEndTransaction(Btree *p){
46394  BtShared *pBt = p->pBt;
46395  assert( sqlite3BtreeHoldsMutex(p) );
46396
46397  btreeClearHasContent(pBt);
46398  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
46399    /* If there are other active statements that belong to this database
46400    ** handle, downgrade to a read-only transaction. The other statements
46401    ** may still be reading from the database.  */
46402    downgradeAllSharedCacheTableLocks(p);
46403    p->inTrans = TRANS_READ;
46404  }else{
46405    /* If the handle had any kind of transaction open, decrement the
46406    ** transaction count of the shared btree. If the transaction count
46407    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
46408    ** call below will unlock the pager.  */
46409    if( p->inTrans!=TRANS_NONE ){
46410      clearAllSharedCacheTableLocks(p);
46411      pBt->nTransaction--;
46412      if( 0==pBt->nTransaction ){
46413        pBt->inTransaction = TRANS_NONE;
46414      }
46415    }
46416
46417    /* Set the current transaction state to TRANS_NONE and unlock the
46418    ** pager if this call closed the only read or write transaction.  */
46419    p->inTrans = TRANS_NONE;
46420    unlockBtreeIfUnused(pBt);
46421  }
46422
46423  btreeIntegrity(p);
46424}
46425
46426/*
46427** Commit the transaction currently in progress.
46428**
46429** This routine implements the second phase of a 2-phase commit.  The
46430** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
46431** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
46432** routine did all the work of writing information out to disk and flushing the
46433** contents so that they are written onto the disk platter.  All this
46434** routine has to do is delete or truncate or zero the header in the
46435** the rollback journal (which causes the transaction to commit) and
46436** drop locks.
46437**
46438** This will release the write lock on the database file.  If there
46439** are no active cursors, it also releases the read lock.
46440*/
46441SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
46442  BtShared *pBt = p->pBt;
46443
46444  sqlite3BtreeEnter(p);
46445  btreeIntegrity(p);
46446
46447  /* If the handle has a write-transaction open, commit the shared-btrees
46448  ** transaction and set the shared state to TRANS_READ.
46449  */
46450  if( p->inTrans==TRANS_WRITE ){
46451    int rc;
46452    assert( pBt->inTransaction==TRANS_WRITE );
46453    assert( pBt->nTransaction>0 );
46454    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
46455    if( rc!=SQLITE_OK ){
46456      sqlite3BtreeLeave(p);
46457      return rc;
46458    }
46459    pBt->inTransaction = TRANS_READ;
46460  }
46461
46462  btreeEndTransaction(p);
46463  sqlite3BtreeLeave(p);
46464  return SQLITE_OK;
46465}
46466
46467/*
46468** Do both phases of a commit.
46469*/
46470SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
46471  int rc;
46472  sqlite3BtreeEnter(p);
46473  rc = sqlite3BtreeCommitPhaseOne(p, 0);
46474  if( rc==SQLITE_OK ){
46475    rc = sqlite3BtreeCommitPhaseTwo(p);
46476  }
46477  sqlite3BtreeLeave(p);
46478  return rc;
46479}
46480
46481#ifndef NDEBUG
46482/*
46483** Return the number of write-cursors open on this handle. This is for use
46484** in assert() expressions, so it is only compiled if NDEBUG is not
46485** defined.
46486**
46487** For the purposes of this routine, a write-cursor is any cursor that
46488** is capable of writing to the databse.  That means the cursor was
46489** originally opened for writing and the cursor has not be disabled
46490** by having its state changed to CURSOR_FAULT.
46491*/
46492static int countWriteCursors(BtShared *pBt){
46493  BtCursor *pCur;
46494  int r = 0;
46495  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
46496    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
46497  }
46498  return r;
46499}
46500#endif
46501
46502/*
46503** This routine sets the state to CURSOR_FAULT and the error
46504** code to errCode for every cursor on BtShared that pBtree
46505** references.
46506**
46507** Every cursor is tripped, including cursors that belong
46508** to other database connections that happen to be sharing
46509** the cache with pBtree.
46510**
46511** This routine gets called when a rollback occurs.
46512** All cursors using the same cache must be tripped
46513** to prevent them from trying to use the btree after
46514** the rollback.  The rollback may have deleted tables
46515** or moved root pages, so it is not sufficient to
46516** save the state of the cursor.  The cursor must be
46517** invalidated.
46518*/
46519SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
46520  BtCursor *p;
46521  sqlite3BtreeEnter(pBtree);
46522  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
46523    int i;
46524    sqlite3BtreeClearCursor(p);
46525    p->eState = CURSOR_FAULT;
46526    p->skipNext = errCode;
46527    for(i=0; i<=p->iPage; i++){
46528      releasePage(p->apPage[i]);
46529      p->apPage[i] = 0;
46530    }
46531  }
46532  sqlite3BtreeLeave(pBtree);
46533}
46534
46535/*
46536** Rollback the transaction in progress.  All cursors will be
46537** invalided by this operation.  Any attempt to use a cursor
46538** that was open at the beginning of this operation will result
46539** in an error.
46540**
46541** This will release the write lock on the database file.  If there
46542** are no active cursors, it also releases the read lock.
46543*/
46544SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
46545  int rc;
46546  BtShared *pBt = p->pBt;
46547  MemPage *pPage1;
46548
46549  sqlite3BtreeEnter(p);
46550  rc = saveAllCursors(pBt, 0, 0);
46551#ifndef SQLITE_OMIT_SHARED_CACHE
46552  if( rc!=SQLITE_OK ){
46553    /* This is a horrible situation. An IO or malloc() error occurred whilst
46554    ** trying to save cursor positions. If this is an automatic rollback (as
46555    ** the result of a constraint, malloc() failure or IO error) then
46556    ** the cache may be internally inconsistent (not contain valid trees) so
46557    ** we cannot simply return the error to the caller. Instead, abort
46558    ** all queries that may be using any of the cursors that failed to save.
46559    */
46560    sqlite3BtreeTripAllCursors(p, rc);
46561  }
46562#endif
46563  btreeIntegrity(p);
46564
46565  if( p->inTrans==TRANS_WRITE ){
46566    int rc2;
46567
46568    assert( TRANS_WRITE==pBt->inTransaction );
46569    rc2 = sqlite3PagerRollback(pBt->pPager);
46570    if( rc2!=SQLITE_OK ){
46571      rc = rc2;
46572    }
46573
46574    /* The rollback may have destroyed the pPage1->aData value.  So
46575    ** call btreeGetPage() on page 1 again to make
46576    ** sure pPage1->aData is set correctly. */
46577    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
46578      int nPage = get4byte(28+(u8*)pPage1->aData);
46579      testcase( nPage==0 );
46580      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
46581      testcase( pBt->nPage!=nPage );
46582      pBt->nPage = nPage;
46583      releasePage(pPage1);
46584    }
46585    assert( countWriteCursors(pBt)==0 );
46586    pBt->inTransaction = TRANS_READ;
46587  }
46588
46589  btreeEndTransaction(p);
46590  sqlite3BtreeLeave(p);
46591  return rc;
46592}
46593
46594/*
46595** Start a statement subtransaction. The subtransaction can can be rolled
46596** back independently of the main transaction. You must start a transaction
46597** before starting a subtransaction. The subtransaction is ended automatically
46598** if the main transaction commits or rolls back.
46599**
46600** Statement subtransactions are used around individual SQL statements
46601** that are contained within a BEGIN...COMMIT block.  If a constraint
46602** error occurs within the statement, the effect of that one statement
46603** can be rolled back without having to rollback the entire transaction.
46604**
46605** A statement sub-transaction is implemented as an anonymous savepoint. The
46606** value passed as the second parameter is the total number of savepoints,
46607** including the new anonymous savepoint, open on the B-Tree. i.e. if there
46608** are no active savepoints and no other statement-transactions open,
46609** iStatement is 1. This anonymous savepoint can be released or rolled back
46610** using the sqlite3BtreeSavepoint() function.
46611*/
46612SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
46613  int rc;
46614  BtShared *pBt = p->pBt;
46615  sqlite3BtreeEnter(p);
46616  assert( p->inTrans==TRANS_WRITE );
46617  assert( pBt->readOnly==0 );
46618  assert( iStatement>0 );
46619  assert( iStatement>p->db->nSavepoint );
46620  assert( pBt->inTransaction==TRANS_WRITE );
46621  /* At the pager level, a statement transaction is a savepoint with
46622  ** an index greater than all savepoints created explicitly using
46623  ** SQL statements. It is illegal to open, release or rollback any
46624  ** such savepoints while the statement transaction savepoint is active.
46625  */
46626  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
46627  sqlite3BtreeLeave(p);
46628  return rc;
46629}
46630
46631/*
46632** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
46633** or SAVEPOINT_RELEASE. This function either releases or rolls back the
46634** savepoint identified by parameter iSavepoint, depending on the value
46635** of op.
46636**
46637** Normally, iSavepoint is greater than or equal to zero. However, if op is
46638** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
46639** contents of the entire transaction are rolled back. This is different
46640** from a normal transaction rollback, as no locks are released and the
46641** transaction remains open.
46642*/
46643SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
46644  int rc = SQLITE_OK;
46645  if( p && p->inTrans==TRANS_WRITE ){
46646    BtShared *pBt = p->pBt;
46647    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
46648    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
46649    sqlite3BtreeEnter(p);
46650    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
46651    if( rc==SQLITE_OK ){
46652      if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
46653      rc = newDatabase(pBt);
46654      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
46655      if( pBt->nPage==0 ){
46656        sqlite3PagerPagecount(pBt->pPager, (int*)&pBt->nPage);
46657      }
46658    }
46659    sqlite3BtreeLeave(p);
46660  }
46661  return rc;
46662}
46663
46664/*
46665** Create a new cursor for the BTree whose root is on the page
46666** iTable. If a read-only cursor is requested, it is assumed that
46667** the caller already has at least a read-only transaction open
46668** on the database already. If a write-cursor is requested, then
46669** the caller is assumed to have an open write transaction.
46670**
46671** If wrFlag==0, then the cursor can only be used for reading.
46672** If wrFlag==1, then the cursor can be used for reading or for
46673** writing if other conditions for writing are also met.  These
46674** are the conditions that must be met in order for writing to
46675** be allowed:
46676**
46677** 1:  The cursor must have been opened with wrFlag==1
46678**
46679** 2:  Other database connections that share the same pager cache
46680**     but which are not in the READ_UNCOMMITTED state may not have
46681**     cursors open with wrFlag==0 on the same table.  Otherwise
46682**     the changes made by this write cursor would be visible to
46683**     the read cursors in the other database connection.
46684**
46685** 3:  The database must be writable (not on read-only media)
46686**
46687** 4:  There must be an active transaction.
46688**
46689** No checking is done to make sure that page iTable really is the
46690** root page of a b-tree.  If it is not, then the cursor acquired
46691** will not work correctly.
46692**
46693** It is assumed that the sqlite3BtreeCursorZero() has been called
46694** on pCur to initialize the memory space prior to invoking this routine.
46695*/
46696static int btreeCursor(
46697  Btree *p,                              /* The btree */
46698  int iTable,                            /* Root page of table to open */
46699  int wrFlag,                            /* 1 to write. 0 read-only */
46700  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
46701  BtCursor *pCur                         /* Space for new cursor */
46702){
46703  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
46704
46705  assert( sqlite3BtreeHoldsMutex(p) );
46706  assert( wrFlag==0 || wrFlag==1 );
46707
46708  /* The following assert statements verify that if this is a sharable
46709  ** b-tree database, the connection is holding the required table locks,
46710  ** and that no other connection has any open cursor that conflicts with
46711  ** this lock.  */
46712  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
46713  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
46714
46715  /* Assert that the caller has opened the required transaction. */
46716  assert( p->inTrans>TRANS_NONE );
46717  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
46718  assert( pBt->pPage1 && pBt->pPage1->aData );
46719
46720  if( NEVER(wrFlag && pBt->readOnly) ){
46721    return SQLITE_READONLY;
46722  }
46723  if( iTable==1 && btreePagecount(pBt)==0 ){
46724    return SQLITE_EMPTY;
46725  }
46726
46727  /* Now that no other errors can occur, finish filling in the BtCursor
46728  ** variables and link the cursor into the BtShared list.  */
46729  pCur->pgnoRoot = (Pgno)iTable;
46730  pCur->iPage = -1;
46731  pCur->pKeyInfo = pKeyInfo;
46732  pCur->pBtree = p;
46733  pCur->pBt = pBt;
46734  pCur->wrFlag = (u8)wrFlag;
46735  pCur->pNext = pBt->pCursor;
46736  if( pCur->pNext ){
46737    pCur->pNext->pPrev = pCur;
46738  }
46739  pBt->pCursor = pCur;
46740  pCur->eState = CURSOR_INVALID;
46741  pCur->cachedRowid = 0;
46742  return SQLITE_OK;
46743}
46744SQLITE_PRIVATE int sqlite3BtreeCursor(
46745  Btree *p,                                   /* The btree */
46746  int iTable,                                 /* Root page of table to open */
46747  int wrFlag,                                 /* 1 to write. 0 read-only */
46748  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
46749  BtCursor *pCur                              /* Write new cursor here */
46750){
46751  int rc;
46752  sqlite3BtreeEnter(p);
46753  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
46754  sqlite3BtreeLeave(p);
46755  return rc;
46756}
46757
46758/*
46759** Return the size of a BtCursor object in bytes.
46760**
46761** This interfaces is needed so that users of cursors can preallocate
46762** sufficient storage to hold a cursor.  The BtCursor object is opaque
46763** to users so they cannot do the sizeof() themselves - they must call
46764** this routine.
46765*/
46766SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
46767  return ROUND8(sizeof(BtCursor));
46768}
46769
46770/*
46771** Initialize memory that will be converted into a BtCursor object.
46772**
46773** The simple approach here would be to memset() the entire object
46774** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
46775** do not need to be zeroed and they are large, so we can save a lot
46776** of run-time by skipping the initialization of those elements.
46777*/
46778SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
46779  memset(p, 0, offsetof(BtCursor, iPage));
46780}
46781
46782/*
46783** Set the cached rowid value of every cursor in the same database file
46784** as pCur and having the same root page number as pCur.  The value is
46785** set to iRowid.
46786**
46787** Only positive rowid values are considered valid for this cache.
46788** The cache is initialized to zero, indicating an invalid cache.
46789** A btree will work fine with zero or negative rowids.  We just cannot
46790** cache zero or negative rowids, which means tables that use zero or
46791** negative rowids might run a little slower.  But in practice, zero
46792** or negative rowids are very uncommon so this should not be a problem.
46793*/
46794SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
46795  BtCursor *p;
46796  for(p=pCur->pBt->pCursor; p; p=p->pNext){
46797    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
46798  }
46799  assert( pCur->cachedRowid==iRowid );
46800}
46801
46802/*
46803** Return the cached rowid for the given cursor.  A negative or zero
46804** return value indicates that the rowid cache is invalid and should be
46805** ignored.  If the rowid cache has never before been set, then a
46806** zero is returned.
46807*/
46808SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
46809  return pCur->cachedRowid;
46810}
46811
46812/*
46813** Close a cursor.  The read lock on the database file is released
46814** when the last cursor is closed.
46815*/
46816SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
46817  Btree *pBtree = pCur->pBtree;
46818  if( pBtree ){
46819    int i;
46820    BtShared *pBt = pCur->pBt;
46821    sqlite3BtreeEnter(pBtree);
46822    sqlite3BtreeClearCursor(pCur);
46823    if( pCur->pPrev ){
46824      pCur->pPrev->pNext = pCur->pNext;
46825    }else{
46826      pBt->pCursor = pCur->pNext;
46827    }
46828    if( pCur->pNext ){
46829      pCur->pNext->pPrev = pCur->pPrev;
46830    }
46831    for(i=0; i<=pCur->iPage; i++){
46832      releasePage(pCur->apPage[i]);
46833    }
46834    unlockBtreeIfUnused(pBt);
46835    invalidateOverflowCache(pCur);
46836    /* sqlite3_free(pCur); */
46837    sqlite3BtreeLeave(pBtree);
46838  }
46839  return SQLITE_OK;
46840}
46841
46842/*
46843** Make sure the BtCursor* given in the argument has a valid
46844** BtCursor.info structure.  If it is not already valid, call
46845** btreeParseCell() to fill it in.
46846**
46847** BtCursor.info is a cache of the information in the current cell.
46848** Using this cache reduces the number of calls to btreeParseCell().
46849**
46850** 2007-06-25:  There is a bug in some versions of MSVC that cause the
46851** compiler to crash when getCellInfo() is implemented as a macro.
46852** But there is a measureable speed advantage to using the macro on gcc
46853** (when less compiler optimizations like -Os or -O0 are used and the
46854** compiler is not doing agressive inlining.)  So we use a real function
46855** for MSVC and a macro for everything else.  Ticket #2457.
46856*/
46857#ifndef NDEBUG
46858  static void assertCellInfo(BtCursor *pCur){
46859    CellInfo info;
46860    int iPage = pCur->iPage;
46861    memset(&info, 0, sizeof(info));
46862    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
46863    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
46864  }
46865#else
46866  #define assertCellInfo(x)
46867#endif
46868#ifdef _MSC_VER
46869  /* Use a real function in MSVC to work around bugs in that compiler. */
46870  static void getCellInfo(BtCursor *pCur){
46871    if( pCur->info.nSize==0 ){
46872      int iPage = pCur->iPage;
46873      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
46874      pCur->validNKey = 1;
46875    }else{
46876      assertCellInfo(pCur);
46877    }
46878  }
46879#else /* if not _MSC_VER */
46880  /* Use a macro in all other compilers so that the function is inlined */
46881#define getCellInfo(pCur)                                                      \
46882  if( pCur->info.nSize==0 ){                                                   \
46883    int iPage = pCur->iPage;                                                   \
46884    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
46885    pCur->validNKey = 1;                                                       \
46886  }else{                                                                       \
46887    assertCellInfo(pCur);                                                      \
46888  }
46889#endif /* _MSC_VER */
46890
46891#ifndef NDEBUG  /* The next routine used only within assert() statements */
46892/*
46893** Return true if the given BtCursor is valid.  A valid cursor is one
46894** that is currently pointing to a row in a (non-empty) table.
46895** This is a verification routine is used only within assert() statements.
46896*/
46897SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
46898  return pCur && pCur->eState==CURSOR_VALID;
46899}
46900#endif /* NDEBUG */
46901
46902/*
46903** Set *pSize to the size of the buffer needed to hold the value of
46904** the key for the current entry.  If the cursor is not pointing
46905** to a valid entry, *pSize is set to 0.
46906**
46907** For a table with the INTKEY flag set, this routine returns the key
46908** itself, not the number of bytes in the key.
46909**
46910** The caller must position the cursor prior to invoking this routine.
46911**
46912** This routine cannot fail.  It always returns SQLITE_OK.
46913*/
46914SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
46915  assert( cursorHoldsMutex(pCur) );
46916  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
46917  if( pCur->eState!=CURSOR_VALID ){
46918    *pSize = 0;
46919  }else{
46920    getCellInfo(pCur);
46921    *pSize = pCur->info.nKey;
46922  }
46923  return SQLITE_OK;
46924}
46925
46926/*
46927** Set *pSize to the number of bytes of data in the entry the
46928** cursor currently points to.
46929**
46930** The caller must guarantee that the cursor is pointing to a non-NULL
46931** valid entry.  In other words, the calling procedure must guarantee
46932** that the cursor has Cursor.eState==CURSOR_VALID.
46933**
46934** Failure is not possible.  This function always returns SQLITE_OK.
46935** It might just as well be a procedure (returning void) but we continue
46936** to return an integer result code for historical reasons.
46937*/
46938SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
46939  assert( cursorHoldsMutex(pCur) );
46940  assert( pCur->eState==CURSOR_VALID );
46941  getCellInfo(pCur);
46942  *pSize = pCur->info.nData;
46943  return SQLITE_OK;
46944}
46945
46946/*
46947** Given the page number of an overflow page in the database (parameter
46948** ovfl), this function finds the page number of the next page in the
46949** linked list of overflow pages. If possible, it uses the auto-vacuum
46950** pointer-map data instead of reading the content of page ovfl to do so.
46951**
46952** If an error occurs an SQLite error code is returned. Otherwise:
46953**
46954** The page number of the next overflow page in the linked list is
46955** written to *pPgnoNext. If page ovfl is the last page in its linked
46956** list, *pPgnoNext is set to zero.
46957**
46958** If ppPage is not NULL, and a reference to the MemPage object corresponding
46959** to page number pOvfl was obtained, then *ppPage is set to point to that
46960** reference. It is the responsibility of the caller to call releasePage()
46961** on *ppPage to free the reference. In no reference was obtained (because
46962** the pointer-map was used to obtain the value for *pPgnoNext), then
46963** *ppPage is set to zero.
46964*/
46965static int getOverflowPage(
46966  BtShared *pBt,               /* The database file */
46967  Pgno ovfl,                   /* Current overflow page number */
46968  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
46969  Pgno *pPgnoNext              /* OUT: Next overflow page number */
46970){
46971  Pgno next = 0;
46972  MemPage *pPage = 0;
46973  int rc = SQLITE_OK;
46974
46975  assert( sqlite3_mutex_held(pBt->mutex) );
46976  assert(pPgnoNext);
46977
46978#ifndef SQLITE_OMIT_AUTOVACUUM
46979  /* Try to find the next page in the overflow list using the
46980  ** autovacuum pointer-map pages. Guess that the next page in
46981  ** the overflow list is page number (ovfl+1). If that guess turns
46982  ** out to be wrong, fall back to loading the data of page
46983  ** number ovfl to determine the next page number.
46984  */
46985  if( pBt->autoVacuum ){
46986    Pgno pgno;
46987    Pgno iGuess = ovfl+1;
46988    u8 eType;
46989
46990    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
46991      iGuess++;
46992    }
46993
46994    if( iGuess<=btreePagecount(pBt) ){
46995      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
46996      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
46997        next = iGuess;
46998        rc = SQLITE_DONE;
46999      }
47000    }
47001  }
47002#endif
47003
47004  assert( next==0 || rc==SQLITE_DONE );
47005  if( rc==SQLITE_OK ){
47006    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
47007    assert( rc==SQLITE_OK || pPage==0 );
47008    if( rc==SQLITE_OK ){
47009      next = get4byte(pPage->aData);
47010    }
47011  }
47012
47013  *pPgnoNext = next;
47014  if( ppPage ){
47015    *ppPage = pPage;
47016  }else{
47017    releasePage(pPage);
47018  }
47019  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
47020}
47021
47022/*
47023** Copy data from a buffer to a page, or from a page to a buffer.
47024**
47025** pPayload is a pointer to data stored on database page pDbPage.
47026** If argument eOp is false, then nByte bytes of data are copied
47027** from pPayload to the buffer pointed at by pBuf. If eOp is true,
47028** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
47029** of data are copied from the buffer pBuf to pPayload.
47030**
47031** SQLITE_OK is returned on success, otherwise an error code.
47032*/
47033static int copyPayload(
47034  void *pPayload,           /* Pointer to page data */
47035  void *pBuf,               /* Pointer to buffer */
47036  int nByte,                /* Number of bytes to copy */
47037  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
47038  DbPage *pDbPage           /* Page containing pPayload */
47039){
47040  if( eOp ){
47041    /* Copy data from buffer to page (a write operation) */
47042    int rc = sqlite3PagerWrite(pDbPage);
47043    if( rc!=SQLITE_OK ){
47044      return rc;
47045    }
47046    memcpy(pPayload, pBuf, nByte);
47047  }else{
47048    /* Copy data from page to buffer (a read operation) */
47049    memcpy(pBuf, pPayload, nByte);
47050  }
47051  return SQLITE_OK;
47052}
47053
47054/*
47055** This function is used to read or overwrite payload information
47056** for the entry that the pCur cursor is pointing to. If the eOp
47057** parameter is 0, this is a read operation (data copied into
47058** buffer pBuf). If it is non-zero, a write (data copied from
47059** buffer pBuf).
47060**
47061** A total of "amt" bytes are read or written beginning at "offset".
47062** Data is read to or from the buffer pBuf.
47063**
47064** The content being read or written might appear on the main page
47065** or be scattered out on multiple overflow pages.
47066**
47067** If the BtCursor.isIncrblobHandle flag is set, and the current
47068** cursor entry uses one or more overflow pages, this function
47069** allocates space for and lazily popluates the overflow page-list
47070** cache array (BtCursor.aOverflow). Subsequent calls use this
47071** cache to make seeking to the supplied offset more efficient.
47072**
47073** Once an overflow page-list cache has been allocated, it may be
47074** invalidated if some other cursor writes to the same table, or if
47075** the cursor is moved to a different row. Additionally, in auto-vacuum
47076** mode, the following events may invalidate an overflow page-list cache.
47077**
47078**   * An incremental vacuum,
47079**   * A commit in auto_vacuum="full" mode,
47080**   * Creating a table (may require moving an overflow page).
47081*/
47082static int accessPayload(
47083  BtCursor *pCur,      /* Cursor pointing to entry to read from */
47084  u32 offset,          /* Begin reading this far into payload */
47085  u32 amt,             /* Read this many bytes */
47086  unsigned char *pBuf, /* Write the bytes into this buffer */
47087  int eOp              /* zero to read. non-zero to write. */
47088){
47089  unsigned char *aPayload;
47090  int rc = SQLITE_OK;
47091  u32 nKey;
47092  int iIdx = 0;
47093  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
47094  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
47095
47096  assert( pPage );
47097  assert( pCur->eState==CURSOR_VALID );
47098  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47099  assert( cursorHoldsMutex(pCur) );
47100
47101  getCellInfo(pCur);
47102  aPayload = pCur->info.pCell + pCur->info.nHeader;
47103  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
47104
47105  if( NEVER(offset+amt > nKey+pCur->info.nData)
47106   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
47107  ){
47108    /* Trying to read or write past the end of the data is an error */
47109    return SQLITE_CORRUPT_BKPT;
47110  }
47111
47112  /* Check if data must be read/written to/from the btree page itself. */
47113  if( offset<pCur->info.nLocal ){
47114    int a = amt;
47115    if( a+offset>pCur->info.nLocal ){
47116      a = pCur->info.nLocal - offset;
47117    }
47118    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
47119    offset = 0;
47120    pBuf += a;
47121    amt -= a;
47122  }else{
47123    offset -= pCur->info.nLocal;
47124  }
47125
47126  if( rc==SQLITE_OK && amt>0 ){
47127    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
47128    Pgno nextPage;
47129
47130    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
47131
47132#ifndef SQLITE_OMIT_INCRBLOB
47133    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
47134    ** has not been allocated, allocate it now. The array is sized at
47135    ** one entry for each overflow page in the overflow chain. The
47136    ** page number of the first overflow page is stored in aOverflow[0],
47137    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
47138    ** (the cache is lazily populated).
47139    */
47140    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
47141      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
47142      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
47143      /* nOvfl is always positive.  If it were zero, fetchPayload would have
47144      ** been used instead of this routine. */
47145      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
47146        rc = SQLITE_NOMEM;
47147      }
47148    }
47149
47150    /* If the overflow page-list cache has been allocated and the
47151    ** entry for the first required overflow page is valid, skip
47152    ** directly to it.
47153    */
47154    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
47155      iIdx = (offset/ovflSize);
47156      nextPage = pCur->aOverflow[iIdx];
47157      offset = (offset%ovflSize);
47158    }
47159#endif
47160
47161    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
47162
47163#ifndef SQLITE_OMIT_INCRBLOB
47164      /* If required, populate the overflow page-list cache. */
47165      if( pCur->aOverflow ){
47166        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
47167        pCur->aOverflow[iIdx] = nextPage;
47168      }
47169#endif
47170
47171      if( offset>=ovflSize ){
47172        /* The only reason to read this page is to obtain the page
47173        ** number for the next page in the overflow chain. The page
47174        ** data is not required. So first try to lookup the overflow
47175        ** page-list cache, if any, then fall back to the getOverflowPage()
47176        ** function.
47177        */
47178#ifndef SQLITE_OMIT_INCRBLOB
47179        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
47180          nextPage = pCur->aOverflow[iIdx+1];
47181        } else
47182#endif
47183          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
47184        offset -= ovflSize;
47185      }else{
47186        /* Need to read this page properly. It contains some of the
47187        ** range of data that is being read (eOp==0) or written (eOp!=0).
47188        */
47189        DbPage *pDbPage;
47190        int a = amt;
47191        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
47192        if( rc==SQLITE_OK ){
47193          aPayload = sqlite3PagerGetData(pDbPage);
47194          nextPage = get4byte(aPayload);
47195          if( a + offset > ovflSize ){
47196            a = ovflSize - offset;
47197          }
47198          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
47199          sqlite3PagerUnref(pDbPage);
47200          offset = 0;
47201          amt -= a;
47202          pBuf += a;
47203        }
47204      }
47205    }
47206  }
47207
47208  if( rc==SQLITE_OK && amt>0 ){
47209    return SQLITE_CORRUPT_BKPT;
47210  }
47211  return rc;
47212}
47213
47214/*
47215** Read part of the key associated with cursor pCur.  Exactly
47216** "amt" bytes will be transfered into pBuf[].  The transfer
47217** begins at "offset".
47218**
47219** The caller must ensure that pCur is pointing to a valid row
47220** in the table.
47221**
47222** Return SQLITE_OK on success or an error code if anything goes
47223** wrong.  An error is returned if "offset+amt" is larger than
47224** the available payload.
47225*/
47226SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47227  assert( cursorHoldsMutex(pCur) );
47228  assert( pCur->eState==CURSOR_VALID );
47229  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47230  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47231  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
47232}
47233
47234/*
47235** Read part of the data associated with cursor pCur.  Exactly
47236** "amt" bytes will be transfered into pBuf[].  The transfer
47237** begins at "offset".
47238**
47239** Return SQLITE_OK on success or an error code if anything goes
47240** wrong.  An error is returned if "offset+amt" is larger than
47241** the available payload.
47242*/
47243SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47244  int rc;
47245
47246#ifndef SQLITE_OMIT_INCRBLOB
47247  if ( pCur->eState==CURSOR_INVALID ){
47248    return SQLITE_ABORT;
47249  }
47250#endif
47251
47252  assert( cursorHoldsMutex(pCur) );
47253  rc = restoreCursorPosition(pCur);
47254  if( rc==SQLITE_OK ){
47255    assert( pCur->eState==CURSOR_VALID );
47256    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47257    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47258    rc = accessPayload(pCur, offset, amt, pBuf, 0);
47259  }
47260  return rc;
47261}
47262
47263/*
47264** Return a pointer to payload information from the entry that the
47265** pCur cursor is pointing to.  The pointer is to the beginning of
47266** the key if skipKey==0 and it points to the beginning of data if
47267** skipKey==1.  The number of bytes of available key/data is written
47268** into *pAmt.  If *pAmt==0, then the value returned will not be
47269** a valid pointer.
47270**
47271** This routine is an optimization.  It is common for the entire key
47272** and data to fit on the local page and for there to be no overflow
47273** pages.  When that is so, this routine can be used to access the
47274** key and data without making a copy.  If the key and/or data spills
47275** onto overflow pages, then accessPayload() must be used to reassemble
47276** the key/data and copy it into a preallocated buffer.
47277**
47278** The pointer returned by this routine looks directly into the cached
47279** page of the database.  The data might change or move the next time
47280** any btree routine is called.
47281*/
47282static const unsigned char *fetchPayload(
47283  BtCursor *pCur,      /* Cursor pointing to entry to read from */
47284  int *pAmt,           /* Write the number of available bytes here */
47285  int skipKey          /* read beginning at data if this is true */
47286){
47287  unsigned char *aPayload;
47288  MemPage *pPage;
47289  u32 nKey;
47290  u32 nLocal;
47291
47292  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
47293  assert( pCur->eState==CURSOR_VALID );
47294  assert( cursorHoldsMutex(pCur) );
47295  pPage = pCur->apPage[pCur->iPage];
47296  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47297  if( NEVER(pCur->info.nSize==0) ){
47298    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
47299                   &pCur->info);
47300  }
47301  aPayload = pCur->info.pCell;
47302  aPayload += pCur->info.nHeader;
47303  if( pPage->intKey ){
47304    nKey = 0;
47305  }else{
47306    nKey = (int)pCur->info.nKey;
47307  }
47308  if( skipKey ){
47309    aPayload += nKey;
47310    nLocal = pCur->info.nLocal - nKey;
47311  }else{
47312    nLocal = pCur->info.nLocal;
47313    assert( nLocal<=nKey );
47314  }
47315  *pAmt = nLocal;
47316  return aPayload;
47317}
47318
47319
47320/*
47321** For the entry that cursor pCur is point to, return as
47322** many bytes of the key or data as are available on the local
47323** b-tree page.  Write the number of available bytes into *pAmt.
47324**
47325** The pointer returned is ephemeral.  The key/data may move
47326** or be destroyed on the next call to any Btree routine,
47327** including calls from other threads against the same cache.
47328** Hence, a mutex on the BtShared should be held prior to calling
47329** this routine.
47330**
47331** These routines is used to get quick access to key and data
47332** in the common case where no overflow pages are used.
47333*/
47334SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
47335  const void *p = 0;
47336  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47337  assert( cursorHoldsMutex(pCur) );
47338  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47339    p = (const void*)fetchPayload(pCur, pAmt, 0);
47340  }
47341  return p;
47342}
47343SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
47344  const void *p = 0;
47345  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47346  assert( cursorHoldsMutex(pCur) );
47347  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47348    p = (const void*)fetchPayload(pCur, pAmt, 1);
47349  }
47350  return p;
47351}
47352
47353
47354/*
47355** Move the cursor down to a new child page.  The newPgno argument is the
47356** page number of the child page to move to.
47357**
47358** This function returns SQLITE_CORRUPT if the page-header flags field of
47359** the new child page does not match the flags field of the parent (i.e.
47360** if an intkey page appears to be the parent of a non-intkey page, or
47361** vice-versa).
47362*/
47363static int moveToChild(BtCursor *pCur, u32 newPgno){
47364  int rc;
47365  int i = pCur->iPage;
47366  MemPage *pNewPage;
47367  BtShared *pBt = pCur->pBt;
47368
47369  assert( cursorHoldsMutex(pCur) );
47370  assert( pCur->eState==CURSOR_VALID );
47371  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
47372  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
47373    return SQLITE_CORRUPT_BKPT;
47374  }
47375  rc = getAndInitPage(pBt, newPgno, &pNewPage);
47376  if( rc ) return rc;
47377  pCur->apPage[i+1] = pNewPage;
47378  pCur->aiIdx[i+1] = 0;
47379  pCur->iPage++;
47380
47381  pCur->info.nSize = 0;
47382  pCur->validNKey = 0;
47383  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
47384    return SQLITE_CORRUPT_BKPT;
47385  }
47386  return SQLITE_OK;
47387}
47388
47389#ifndef NDEBUG
47390/*
47391** Page pParent is an internal (non-leaf) tree page. This function
47392** asserts that page number iChild is the left-child if the iIdx'th
47393** cell in page pParent. Or, if iIdx is equal to the total number of
47394** cells in pParent, that page number iChild is the right-child of
47395** the page.
47396*/
47397static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
47398  assert( iIdx<=pParent->nCell );
47399  if( iIdx==pParent->nCell ){
47400    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
47401  }else{
47402    assert( get4byte(findCell(pParent, iIdx))==iChild );
47403  }
47404}
47405#else
47406#  define assertParentIndex(x,y,z)
47407#endif
47408
47409/*
47410** Move the cursor up to the parent page.
47411**
47412** pCur->idx is set to the cell index that contains the pointer
47413** to the page we are coming from.  If we are coming from the
47414** right-most child page then pCur->idx is set to one more than
47415** the largest cell index.
47416*/
47417static void moveToParent(BtCursor *pCur){
47418  assert( cursorHoldsMutex(pCur) );
47419  assert( pCur->eState==CURSOR_VALID );
47420  assert( pCur->iPage>0 );
47421  assert( pCur->apPage[pCur->iPage] );
47422  assertParentIndex(
47423    pCur->apPage[pCur->iPage-1],
47424    pCur->aiIdx[pCur->iPage-1],
47425    pCur->apPage[pCur->iPage]->pgno
47426  );
47427  releasePage(pCur->apPage[pCur->iPage]);
47428  pCur->iPage--;
47429  pCur->info.nSize = 0;
47430  pCur->validNKey = 0;
47431}
47432
47433/*
47434** Move the cursor to point to the root page of its b-tree structure.
47435**
47436** If the table has a virtual root page, then the cursor is moved to point
47437** to the virtual root page instead of the actual root page. A table has a
47438** virtual root page when the actual root page contains no cells and a
47439** single child page. This can only happen with the table rooted at page 1.
47440**
47441** If the b-tree structure is empty, the cursor state is set to
47442** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
47443** cell located on the root (or virtual root) page and the cursor state
47444** is set to CURSOR_VALID.
47445**
47446** If this function returns successfully, it may be assumed that the
47447** page-header flags indicate that the [virtual] root-page is the expected
47448** kind of b-tree page (i.e. if when opening the cursor the caller did not
47449** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
47450** indicating a table b-tree, or if the caller did specify a KeyInfo
47451** structure the flags byte is set to 0x02 or 0x0A, indicating an index
47452** b-tree).
47453*/
47454static int moveToRoot(BtCursor *pCur){
47455  MemPage *pRoot;
47456  int rc = SQLITE_OK;
47457  Btree *p = pCur->pBtree;
47458  BtShared *pBt = p->pBt;
47459
47460  assert( cursorHoldsMutex(pCur) );
47461  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
47462  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
47463  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
47464  if( pCur->eState>=CURSOR_REQUIRESEEK ){
47465    if( pCur->eState==CURSOR_FAULT ){
47466      assert( pCur->skipNext!=SQLITE_OK );
47467      return pCur->skipNext;
47468    }
47469    sqlite3BtreeClearCursor(pCur);
47470  }
47471
47472  if( pCur->iPage>=0 ){
47473    int i;
47474    for(i=1; i<=pCur->iPage; i++){
47475      releasePage(pCur->apPage[i]);
47476    }
47477    pCur->iPage = 0;
47478  }else{
47479    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
47480    if( rc!=SQLITE_OK ){
47481      pCur->eState = CURSOR_INVALID;
47482      return rc;
47483    }
47484    pCur->iPage = 0;
47485
47486    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
47487    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
47488    ** NULL, the caller expects a table b-tree. If this is not the case,
47489    ** return an SQLITE_CORRUPT error.  */
47490    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
47491    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
47492      return SQLITE_CORRUPT_BKPT;
47493    }
47494  }
47495
47496  /* Assert that the root page is of the correct type. This must be the
47497  ** case as the call to this function that loaded the root-page (either
47498  ** this call or a previous invocation) would have detected corruption
47499  ** if the assumption were not true, and it is not possible for the flags
47500  ** byte to have been modified while this cursor is holding a reference
47501  ** to the page.  */
47502  pRoot = pCur->apPage[0];
47503  assert( pRoot->pgno==pCur->pgnoRoot );
47504  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
47505
47506  pCur->aiIdx[0] = 0;
47507  pCur->info.nSize = 0;
47508  pCur->atLast = 0;
47509  pCur->validNKey = 0;
47510
47511  if( pRoot->nCell==0 && !pRoot->leaf ){
47512    Pgno subpage;
47513    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
47514    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
47515    pCur->eState = CURSOR_VALID;
47516    rc = moveToChild(pCur, subpage);
47517  }else{
47518    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
47519  }
47520  return rc;
47521}
47522
47523/*
47524** Move the cursor down to the left-most leaf entry beneath the
47525** entry to which it is currently pointing.
47526**
47527** The left-most leaf is the one with the smallest key - the first
47528** in ascending order.
47529*/
47530static int moveToLeftmost(BtCursor *pCur){
47531  Pgno pgno;
47532  int rc = SQLITE_OK;
47533  MemPage *pPage;
47534
47535  assert( cursorHoldsMutex(pCur) );
47536  assert( pCur->eState==CURSOR_VALID );
47537  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47538    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47539    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
47540    rc = moveToChild(pCur, pgno);
47541  }
47542  return rc;
47543}
47544
47545/*
47546** Move the cursor down to the right-most leaf entry beneath the
47547** page to which it is currently pointing.  Notice the difference
47548** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
47549** finds the left-most entry beneath the *entry* whereas moveToRightmost()
47550** finds the right-most entry beneath the *page*.
47551**
47552** The right-most entry is the one with the largest key - the last
47553** key in ascending order.
47554*/
47555static int moveToRightmost(BtCursor *pCur){
47556  Pgno pgno;
47557  int rc = SQLITE_OK;
47558  MemPage *pPage = 0;
47559
47560  assert( cursorHoldsMutex(pCur) );
47561  assert( pCur->eState==CURSOR_VALID );
47562  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47563    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47564    pCur->aiIdx[pCur->iPage] = pPage->nCell;
47565    rc = moveToChild(pCur, pgno);
47566  }
47567  if( rc==SQLITE_OK ){
47568    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
47569    pCur->info.nSize = 0;
47570    pCur->validNKey = 0;
47571  }
47572  return rc;
47573}
47574
47575/* Move the cursor to the first entry in the table.  Return SQLITE_OK
47576** on success.  Set *pRes to 0 if the cursor actually points to something
47577** or set *pRes to 1 if the table is empty.
47578*/
47579SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
47580  int rc;
47581
47582  assert( cursorHoldsMutex(pCur) );
47583  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47584  rc = moveToRoot(pCur);
47585  if( rc==SQLITE_OK ){
47586    if( pCur->eState==CURSOR_INVALID ){
47587      assert( pCur->apPage[pCur->iPage]->nCell==0 );
47588      *pRes = 1;
47589      rc = SQLITE_OK;
47590    }else{
47591      assert( pCur->apPage[pCur->iPage]->nCell>0 );
47592      *pRes = 0;
47593      rc = moveToLeftmost(pCur);
47594    }
47595  }
47596  return rc;
47597}
47598
47599/* Move the cursor to the last entry in the table.  Return SQLITE_OK
47600** on success.  Set *pRes to 0 if the cursor actually points to something
47601** or set *pRes to 1 if the table is empty.
47602*/
47603SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
47604  int rc;
47605
47606  assert( cursorHoldsMutex(pCur) );
47607  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47608
47609  /* If the cursor already points to the last entry, this is a no-op. */
47610  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
47611#ifdef SQLITE_DEBUG
47612    /* This block serves to assert() that the cursor really does point
47613    ** to the last entry in the b-tree. */
47614    int ii;
47615    for(ii=0; ii<pCur->iPage; ii++){
47616      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
47617    }
47618    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
47619    assert( pCur->apPage[pCur->iPage]->leaf );
47620#endif
47621    return SQLITE_OK;
47622  }
47623
47624  rc = moveToRoot(pCur);
47625  if( rc==SQLITE_OK ){
47626    if( CURSOR_INVALID==pCur->eState ){
47627      assert( pCur->apPage[pCur->iPage]->nCell==0 );
47628      *pRes = 1;
47629    }else{
47630      assert( pCur->eState==CURSOR_VALID );
47631      *pRes = 0;
47632      rc = moveToRightmost(pCur);
47633      pCur->atLast = rc==SQLITE_OK ?1:0;
47634    }
47635  }
47636  return rc;
47637}
47638
47639/* Move the cursor so that it points to an entry near the key
47640** specified by pIdxKey or intKey.   Return a success code.
47641**
47642** For INTKEY tables, the intKey parameter is used.  pIdxKey
47643** must be NULL.  For index tables, pIdxKey is used and intKey
47644** is ignored.
47645**
47646** If an exact match is not found, then the cursor is always
47647** left pointing at a leaf page which would hold the entry if it
47648** were present.  The cursor might point to an entry that comes
47649** before or after the key.
47650**
47651** An integer is written into *pRes which is the result of
47652** comparing the key with the entry to which the cursor is
47653** pointing.  The meaning of the integer written into
47654** *pRes is as follows:
47655**
47656**     *pRes<0      The cursor is left pointing at an entry that
47657**                  is smaller than intKey/pIdxKey or if the table is empty
47658**                  and the cursor is therefore left point to nothing.
47659**
47660**     *pRes==0     The cursor is left pointing at an entry that
47661**                  exactly matches intKey/pIdxKey.
47662**
47663**     *pRes>0      The cursor is left pointing at an entry that
47664**                  is larger than intKey/pIdxKey.
47665**
47666*/
47667SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
47668  BtCursor *pCur,          /* The cursor to be moved */
47669  UnpackedRecord *pIdxKey, /* Unpacked index key */
47670  i64 intKey,              /* The table key */
47671  int biasRight,           /* If true, bias the search to the high end */
47672  int *pRes                /* Write search results here */
47673){
47674  int rc;
47675
47676  assert( cursorHoldsMutex(pCur) );
47677  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47678  assert( pRes );
47679  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
47680
47681  /* If the cursor is already positioned at the point we are trying
47682  ** to move to, then just return without doing any work */
47683  if( pCur->eState==CURSOR_VALID && pCur->validNKey
47684   && pCur->apPage[0]->intKey
47685  ){
47686    if( pCur->info.nKey==intKey ){
47687      *pRes = 0;
47688      return SQLITE_OK;
47689    }
47690    if( pCur->atLast && pCur->info.nKey<intKey ){
47691      *pRes = -1;
47692      return SQLITE_OK;
47693    }
47694  }
47695
47696  rc = moveToRoot(pCur);
47697  if( rc ){
47698    return rc;
47699  }
47700  assert( pCur->apPage[pCur->iPage] );
47701  assert( pCur->apPage[pCur->iPage]->isInit );
47702  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
47703  if( pCur->eState==CURSOR_INVALID ){
47704    *pRes = -1;
47705    assert( pCur->apPage[pCur->iPage]->nCell==0 );
47706    return SQLITE_OK;
47707  }
47708  assert( pCur->apPage[0]->intKey || pIdxKey );
47709  for(;;){
47710    int lwr, upr;
47711    Pgno chldPg;
47712    MemPage *pPage = pCur->apPage[pCur->iPage];
47713    int c;
47714
47715    /* pPage->nCell must be greater than zero. If this is the root-page
47716    ** the cursor would have been INVALID above and this for(;;) loop
47717    ** not run. If this is not the root-page, then the moveToChild() routine
47718    ** would have already detected db corruption. Similarly, pPage must
47719    ** be the right kind (index or table) of b-tree page. Otherwise
47720    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
47721    assert( pPage->nCell>0 );
47722    assert( pPage->intKey==(pIdxKey==0) );
47723    lwr = 0;
47724    upr = pPage->nCell-1;
47725    if( biasRight ){
47726      pCur->aiIdx[pCur->iPage] = (u16)upr;
47727    }else{
47728      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
47729    }
47730    for(;;){
47731      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
47732      u8 *pCell;                          /* Pointer to current cell in pPage */
47733
47734      pCur->info.nSize = 0;
47735      pCell = findCell(pPage, idx) + pPage->childPtrSize;
47736      if( pPage->intKey ){
47737        i64 nCellKey;
47738        if( pPage->hasData ){
47739          u32 dummy;
47740          pCell += getVarint32(pCell, dummy);
47741        }
47742        getVarint(pCell, (u64*)&nCellKey);
47743        if( nCellKey==intKey ){
47744          c = 0;
47745        }else if( nCellKey<intKey ){
47746          c = -1;
47747        }else{
47748          assert( nCellKey>intKey );
47749          c = +1;
47750        }
47751        pCur->validNKey = 1;
47752        pCur->info.nKey = nCellKey;
47753      }else{
47754        /* The maximum supported page-size is 32768 bytes. This means that
47755        ** the maximum number of record bytes stored on an index B-Tree
47756        ** page is at most 8198 bytes, which may be stored as a 2-byte
47757        ** varint. This information is used to attempt to avoid parsing
47758        ** the entire cell by checking for the cases where the record is
47759        ** stored entirely within the b-tree page by inspecting the first
47760        ** 2 bytes of the cell.
47761        */
47762        int nCell = pCell[0];
47763        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
47764          /* This branch runs if the record-size field of the cell is a
47765          ** single byte varint and the record fits entirely on the main
47766          ** b-tree page.  */
47767          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
47768        }else if( !(pCell[1] & 0x80)
47769          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
47770        ){
47771          /* The record-size field is a 2 byte varint and the record
47772          ** fits entirely on the main b-tree page.  */
47773          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
47774        }else{
47775          /* The record flows over onto one or more overflow pages. In
47776          ** this case the whole cell needs to be parsed, a buffer allocated
47777          ** and accessPayload() used to retrieve the record into the
47778          ** buffer before VdbeRecordCompare() can be called. */
47779          void *pCellKey;
47780          u8 * const pCellBody = pCell - pPage->childPtrSize;
47781          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
47782          nCell = (int)pCur->info.nKey;
47783          pCellKey = sqlite3Malloc( nCell );
47784          if( pCellKey==0 ){
47785            rc = SQLITE_NOMEM;
47786            goto moveto_finish;
47787          }
47788          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
47789          if( rc ){
47790            sqlite3_free(pCellKey);
47791            goto moveto_finish;
47792          }
47793          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
47794          sqlite3_free(pCellKey);
47795        }
47796      }
47797      if( c==0 ){
47798        if( pPage->intKey && !pPage->leaf ){
47799          lwr = idx;
47800          upr = lwr - 1;
47801          break;
47802        }else{
47803          *pRes = 0;
47804          rc = SQLITE_OK;
47805          goto moveto_finish;
47806        }
47807      }
47808      if( c<0 ){
47809        lwr = idx+1;
47810      }else{
47811        upr = idx-1;
47812      }
47813      if( lwr>upr ){
47814        break;
47815      }
47816      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
47817    }
47818    assert( lwr==upr+1 );
47819    assert( pPage->isInit );
47820    if( pPage->leaf ){
47821      chldPg = 0;
47822    }else if( lwr>=pPage->nCell ){
47823      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47824    }else{
47825      chldPg = get4byte(findCell(pPage, lwr));
47826    }
47827    if( chldPg==0 ){
47828      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47829      *pRes = c;
47830      rc = SQLITE_OK;
47831      goto moveto_finish;
47832    }
47833    pCur->aiIdx[pCur->iPage] = (u16)lwr;
47834    pCur->info.nSize = 0;
47835    pCur->validNKey = 0;
47836    rc = moveToChild(pCur, chldPg);
47837    if( rc ) goto moveto_finish;
47838  }
47839moveto_finish:
47840  return rc;
47841}
47842
47843
47844/*
47845** Return TRUE if the cursor is not pointing at an entry of the table.
47846**
47847** TRUE will be returned after a call to sqlite3BtreeNext() moves
47848** past the last entry in the table or sqlite3BtreePrev() moves past
47849** the first entry.  TRUE is also returned if the table is empty.
47850*/
47851SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
47852  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
47853  ** have been deleted? This API will need to change to return an error code
47854  ** as well as the boolean result value.
47855  */
47856  return (CURSOR_VALID!=pCur->eState);
47857}
47858
47859/*
47860** Advance the cursor to the next entry in the database.  If
47861** successful then set *pRes=0.  If the cursor
47862** was already pointing to the last entry in the database before
47863** this routine was called, then set *pRes=1.
47864*/
47865SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
47866  int rc;
47867  int idx;
47868  MemPage *pPage;
47869
47870  assert( cursorHoldsMutex(pCur) );
47871  rc = restoreCursorPosition(pCur);
47872  if( rc!=SQLITE_OK ){
47873    return rc;
47874  }
47875  assert( pRes!=0 );
47876  if( CURSOR_INVALID==pCur->eState ){
47877    *pRes = 1;
47878    return SQLITE_OK;
47879  }
47880  if( pCur->skipNext>0 ){
47881    pCur->skipNext = 0;
47882    *pRes = 0;
47883    return SQLITE_OK;
47884  }
47885  pCur->skipNext = 0;
47886
47887  pPage = pCur->apPage[pCur->iPage];
47888  idx = ++pCur->aiIdx[pCur->iPage];
47889  assert( pPage->isInit );
47890  assert( idx<=pPage->nCell );
47891
47892  pCur->info.nSize = 0;
47893  pCur->validNKey = 0;
47894  if( idx>=pPage->nCell ){
47895    if( !pPage->leaf ){
47896      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
47897      if( rc ) return rc;
47898      rc = moveToLeftmost(pCur);
47899      *pRes = 0;
47900      return rc;
47901    }
47902    do{
47903      if( pCur->iPage==0 ){
47904        *pRes = 1;
47905        pCur->eState = CURSOR_INVALID;
47906        return SQLITE_OK;
47907      }
47908      moveToParent(pCur);
47909      pPage = pCur->apPage[pCur->iPage];
47910    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
47911    *pRes = 0;
47912    if( pPage->intKey ){
47913      rc = sqlite3BtreeNext(pCur, pRes);
47914    }else{
47915      rc = SQLITE_OK;
47916    }
47917    return rc;
47918  }
47919  *pRes = 0;
47920  if( pPage->leaf ){
47921    return SQLITE_OK;
47922  }
47923  rc = moveToLeftmost(pCur);
47924  return rc;
47925}
47926
47927
47928/*
47929** Step the cursor to the back to the previous entry in the database.  If
47930** successful then set *pRes=0.  If the cursor
47931** was already pointing to the first entry in the database before
47932** this routine was called, then set *pRes=1.
47933*/
47934SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
47935  int rc;
47936  MemPage *pPage;
47937
47938  assert( cursorHoldsMutex(pCur) );
47939  rc = restoreCursorPosition(pCur);
47940  if( rc!=SQLITE_OK ){
47941    return rc;
47942  }
47943  pCur->atLast = 0;
47944  if( CURSOR_INVALID==pCur->eState ){
47945    *pRes = 1;
47946    return SQLITE_OK;
47947  }
47948  if( pCur->skipNext<0 ){
47949    pCur->skipNext = 0;
47950    *pRes = 0;
47951    return SQLITE_OK;
47952  }
47953  pCur->skipNext = 0;
47954
47955  pPage = pCur->apPage[pCur->iPage];
47956  assert( pPage->isInit );
47957  if( !pPage->leaf ){
47958    int idx = pCur->aiIdx[pCur->iPage];
47959    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
47960    if( rc ){
47961      return rc;
47962    }
47963    rc = moveToRightmost(pCur);
47964  }else{
47965    while( pCur->aiIdx[pCur->iPage]==0 ){
47966      if( pCur->iPage==0 ){
47967        pCur->eState = CURSOR_INVALID;
47968        *pRes = 1;
47969        return SQLITE_OK;
47970      }
47971      moveToParent(pCur);
47972    }
47973    pCur->info.nSize = 0;
47974    pCur->validNKey = 0;
47975
47976    pCur->aiIdx[pCur->iPage]--;
47977    pPage = pCur->apPage[pCur->iPage];
47978    if( pPage->intKey && !pPage->leaf ){
47979      rc = sqlite3BtreePrevious(pCur, pRes);
47980    }else{
47981      rc = SQLITE_OK;
47982    }
47983  }
47984  *pRes = 0;
47985  return rc;
47986}
47987
47988/*
47989** Allocate a new page from the database file.
47990**
47991** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
47992** has already been called on the new page.)  The new page has also
47993** been referenced and the calling routine is responsible for calling
47994** sqlite3PagerUnref() on the new page when it is done.
47995**
47996** SQLITE_OK is returned on success.  Any other return value indicates
47997** an error.  *ppPage and *pPgno are undefined in the event of an error.
47998** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
47999**
48000** If the "nearby" parameter is not 0, then a (feeble) effort is made to
48001** locate a page close to the page number "nearby".  This can be used in an
48002** attempt to keep related pages close to each other in the database file,
48003** which in turn can make database access faster.
48004**
48005** If the "exact" parameter is not 0, and the page-number nearby exists
48006** anywhere on the free-list, then it is guarenteed to be returned. This
48007** is only used by auto-vacuum databases when allocating a new table.
48008*/
48009static int allocateBtreePage(
48010  BtShared *pBt,
48011  MemPage **ppPage,
48012  Pgno *pPgno,
48013  Pgno nearby,
48014  u8 exact
48015){
48016  MemPage *pPage1;
48017  int rc;
48018  u32 n;     /* Number of pages on the freelist */
48019  u32 k;     /* Number of leaves on the trunk of the freelist */
48020  MemPage *pTrunk = 0;
48021  MemPage *pPrevTrunk = 0;
48022  Pgno mxPage;     /* Total size of the database file */
48023
48024  assert( sqlite3_mutex_held(pBt->mutex) );
48025  pPage1 = pBt->pPage1;
48026  mxPage = btreePagecount(pBt);
48027  n = get4byte(&pPage1->aData[36]);
48028  testcase( n==mxPage-1 );
48029  if( n>=mxPage ){
48030    return SQLITE_CORRUPT_BKPT;
48031  }
48032  if( n>0 ){
48033    /* There are pages on the freelist.  Reuse one of those pages. */
48034    Pgno iTrunk;
48035    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
48036
48037    /* If the 'exact' parameter was true and a query of the pointer-map
48038    ** shows that the page 'nearby' is somewhere on the free-list, then
48039    ** the entire-list will be searched for that page.
48040    */
48041#ifndef SQLITE_OMIT_AUTOVACUUM
48042    if( exact && nearby<=mxPage ){
48043      u8 eType;
48044      assert( nearby>0 );
48045      assert( pBt->autoVacuum );
48046      rc = ptrmapGet(pBt, nearby, &eType, 0);
48047      if( rc ) return rc;
48048      if( eType==PTRMAP_FREEPAGE ){
48049        searchList = 1;
48050      }
48051      *pPgno = nearby;
48052    }
48053#endif
48054
48055    /* Decrement the free-list count by 1. Set iTrunk to the index of the
48056    ** first free-list trunk page. iPrevTrunk is initially 1.
48057    */
48058    rc = sqlite3PagerWrite(pPage1->pDbPage);
48059    if( rc ) return rc;
48060    put4byte(&pPage1->aData[36], n-1);
48061
48062    /* The code within this loop is run only once if the 'searchList' variable
48063    ** is not true. Otherwise, it runs once for each trunk-page on the
48064    ** free-list until the page 'nearby' is located.
48065    */
48066    do {
48067      pPrevTrunk = pTrunk;
48068      if( pPrevTrunk ){
48069        iTrunk = get4byte(&pPrevTrunk->aData[0]);
48070      }else{
48071        iTrunk = get4byte(&pPage1->aData[32]);
48072      }
48073      testcase( iTrunk==mxPage );
48074      if( iTrunk>mxPage ){
48075        rc = SQLITE_CORRUPT_BKPT;
48076      }else{
48077        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48078      }
48079      if( rc ){
48080        pTrunk = 0;
48081        goto end_allocate_page;
48082      }
48083
48084      k = get4byte(&pTrunk->aData[4]);
48085      if( k==0 && !searchList ){
48086        /* The trunk has no leaves and the list is not being searched.
48087        ** So extract the trunk page itself and use it as the newly
48088        ** allocated page */
48089        assert( pPrevTrunk==0 );
48090        rc = sqlite3PagerWrite(pTrunk->pDbPage);
48091        if( rc ){
48092          goto end_allocate_page;
48093        }
48094        *pPgno = iTrunk;
48095        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48096        *ppPage = pTrunk;
48097        pTrunk = 0;
48098        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48099      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
48100        /* Value of k is out of range.  Database corruption */
48101        rc = SQLITE_CORRUPT_BKPT;
48102        goto end_allocate_page;
48103#ifndef SQLITE_OMIT_AUTOVACUUM
48104      }else if( searchList && nearby==iTrunk ){
48105        /* The list is being searched and this trunk page is the page
48106        ** to allocate, regardless of whether it has leaves.
48107        */
48108        assert( *pPgno==iTrunk );
48109        *ppPage = pTrunk;
48110        searchList = 0;
48111        rc = sqlite3PagerWrite(pTrunk->pDbPage);
48112        if( rc ){
48113          goto end_allocate_page;
48114        }
48115        if( k==0 ){
48116          if( !pPrevTrunk ){
48117            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48118          }else{
48119            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
48120          }
48121        }else{
48122          /* The trunk page is required by the caller but it contains
48123          ** pointers to free-list leaves. The first leaf becomes a trunk
48124          ** page in this case.
48125          */
48126          MemPage *pNewTrunk;
48127          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
48128          if( iNewTrunk>mxPage ){
48129            rc = SQLITE_CORRUPT_BKPT;
48130            goto end_allocate_page;
48131          }
48132          testcase( iNewTrunk==mxPage );
48133          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
48134          if( rc!=SQLITE_OK ){
48135            goto end_allocate_page;
48136          }
48137          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
48138          if( rc!=SQLITE_OK ){
48139            releasePage(pNewTrunk);
48140            goto end_allocate_page;
48141          }
48142          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
48143          put4byte(&pNewTrunk->aData[4], k-1);
48144          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
48145          releasePage(pNewTrunk);
48146          if( !pPrevTrunk ){
48147            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
48148            put4byte(&pPage1->aData[32], iNewTrunk);
48149          }else{
48150            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
48151            if( rc ){
48152              goto end_allocate_page;
48153            }
48154            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
48155          }
48156        }
48157        pTrunk = 0;
48158        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48159#endif
48160      }else if( k>0 ){
48161        /* Extract a leaf from the trunk */
48162        u32 closest;
48163        Pgno iPage;
48164        unsigned char *aData = pTrunk->aData;
48165        rc = sqlite3PagerWrite(pTrunk->pDbPage);
48166        if( rc ){
48167          goto end_allocate_page;
48168        }
48169        if( nearby>0 ){
48170          u32 i;
48171          int dist;
48172          closest = 0;
48173          dist = get4byte(&aData[8]) - nearby;
48174          if( dist<0 ) dist = -dist;
48175          for(i=1; i<k; i++){
48176            int d2 = get4byte(&aData[8+i*4]) - nearby;
48177            if( d2<0 ) d2 = -d2;
48178            if( d2<dist ){
48179              closest = i;
48180              dist = d2;
48181            }
48182          }
48183        }else{
48184          closest = 0;
48185        }
48186
48187        iPage = get4byte(&aData[8+closest*4]);
48188        testcase( iPage==mxPage );
48189        if( iPage>mxPage ){
48190          rc = SQLITE_CORRUPT_BKPT;
48191          goto end_allocate_page;
48192        }
48193        testcase( iPage==mxPage );
48194        if( !searchList || iPage==nearby ){
48195          int noContent;
48196          *pPgno = iPage;
48197          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
48198                 ": %d more free pages\n",
48199                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
48200          if( closest<k-1 ){
48201            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
48202          }
48203          put4byte(&aData[4], k-1);
48204          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
48205          noContent = !btreeGetHasContent(pBt, *pPgno);
48206          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
48207          if( rc==SQLITE_OK ){
48208            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48209            if( rc!=SQLITE_OK ){
48210              releasePage(*ppPage);
48211            }
48212          }
48213          searchList = 0;
48214        }
48215      }
48216      releasePage(pPrevTrunk);
48217      pPrevTrunk = 0;
48218    }while( searchList );
48219  }else{
48220    /* There are no pages on the freelist, so create a new page at the
48221    ** end of the file */
48222    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48223    if( rc ) return rc;
48224    pBt->nPage++;
48225    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
48226
48227#ifndef SQLITE_OMIT_AUTOVACUUM
48228    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
48229      /* If *pPgno refers to a pointer-map page, allocate two new pages
48230      ** at the end of the file instead of one. The first allocated page
48231      ** becomes a new pointer-map page, the second is used by the caller.
48232      */
48233      MemPage *pPg = 0;
48234      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
48235      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
48236      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
48237      if( rc==SQLITE_OK ){
48238        rc = sqlite3PagerWrite(pPg->pDbPage);
48239        releasePage(pPg);
48240      }
48241      if( rc ) return rc;
48242      pBt->nPage++;
48243      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
48244    }
48245#endif
48246    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
48247    *pPgno = pBt->nPage;
48248
48249    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48250    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
48251    if( rc ) return rc;
48252    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48253    if( rc!=SQLITE_OK ){
48254      releasePage(*ppPage);
48255    }
48256    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
48257  }
48258
48259  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48260
48261end_allocate_page:
48262  releasePage(pTrunk);
48263  releasePage(pPrevTrunk);
48264  if( rc==SQLITE_OK ){
48265    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
48266      releasePage(*ppPage);
48267      return SQLITE_CORRUPT_BKPT;
48268    }
48269    (*ppPage)->isInit = 0;
48270  }else{
48271    *ppPage = 0;
48272  }
48273  return rc;
48274}
48275
48276/*
48277** This function is used to add page iPage to the database file free-list.
48278** It is assumed that the page is not already a part of the free-list.
48279**
48280** The value passed as the second argument to this function is optional.
48281** If the caller happens to have a pointer to the MemPage object
48282** corresponding to page iPage handy, it may pass it as the second value.
48283** Otherwise, it may pass NULL.
48284**
48285** If a pointer to a MemPage object is passed as the second argument,
48286** its reference count is not altered by this function.
48287*/
48288static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
48289  MemPage *pTrunk = 0;                /* Free-list trunk page */
48290  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
48291  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
48292  MemPage *pPage;                     /* Page being freed. May be NULL. */
48293  int rc;                             /* Return Code */
48294  int nFree;                          /* Initial number of pages on free-list */
48295
48296  assert( sqlite3_mutex_held(pBt->mutex) );
48297  assert( iPage>1 );
48298  assert( !pMemPage || pMemPage->pgno==iPage );
48299
48300  if( pMemPage ){
48301    pPage = pMemPage;
48302    sqlite3PagerRef(pPage->pDbPage);
48303  }else{
48304    pPage = btreePageLookup(pBt, iPage);
48305  }
48306
48307  /* Increment the free page count on pPage1 */
48308  rc = sqlite3PagerWrite(pPage1->pDbPage);
48309  if( rc ) goto freepage_out;
48310  nFree = get4byte(&pPage1->aData[36]);
48311  put4byte(&pPage1->aData[36], nFree+1);
48312
48313  if( pBt->secureDelete ){
48314    /* If the secure_delete option is enabled, then
48315    ** always fully overwrite deleted information with zeros.
48316    */
48317    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
48318     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
48319    ){
48320      goto freepage_out;
48321    }
48322    memset(pPage->aData, 0, pPage->pBt->pageSize);
48323  }
48324
48325  /* If the database supports auto-vacuum, write an entry in the pointer-map
48326  ** to indicate that the page is free.
48327  */
48328  if( ISAUTOVACUUM ){
48329    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
48330    if( rc ) goto freepage_out;
48331  }
48332
48333  /* Now manipulate the actual database free-list structure. There are two
48334  ** possibilities. If the free-list is currently empty, or if the first
48335  ** trunk page in the free-list is full, then this page will become a
48336  ** new free-list trunk page. Otherwise, it will become a leaf of the
48337  ** first trunk page in the current free-list. This block tests if it
48338  ** is possible to add the page as a new free-list leaf.
48339  */
48340  if( nFree!=0 ){
48341    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
48342
48343    iTrunk = get4byte(&pPage1->aData[32]);
48344    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48345    if( rc!=SQLITE_OK ){
48346      goto freepage_out;
48347    }
48348
48349    nLeaf = get4byte(&pTrunk->aData[4]);
48350    assert( pBt->usableSize>32 );
48351    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
48352      rc = SQLITE_CORRUPT_BKPT;
48353      goto freepage_out;
48354    }
48355    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
48356      /* In this case there is room on the trunk page to insert the page
48357      ** being freed as a new leaf.
48358      **
48359      ** Note that the trunk page is not really full until it contains
48360      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
48361      ** coded.  But due to a coding error in versions of SQLite prior to
48362      ** 3.6.0, databases with freelist trunk pages holding more than
48363      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
48364      ** to maintain backwards compatibility with older versions of SQLite,
48365      ** we will continue to restrict the number of entries to usableSize/4 - 8
48366      ** for now.  At some point in the future (once everyone has upgraded
48367      ** to 3.6.0 or later) we should consider fixing the conditional above
48368      ** to read "usableSize/4-2" instead of "usableSize/4-8".
48369      */
48370      rc = sqlite3PagerWrite(pTrunk->pDbPage);
48371      if( rc==SQLITE_OK ){
48372        put4byte(&pTrunk->aData[4], nLeaf+1);
48373        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
48374        if( pPage && !pBt->secureDelete ){
48375          sqlite3PagerDontWrite(pPage->pDbPage);
48376        }
48377        rc = btreeSetHasContent(pBt, iPage);
48378      }
48379      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
48380      goto freepage_out;
48381    }
48382  }
48383
48384  /* If control flows to this point, then it was not possible to add the
48385  ** the page being freed as a leaf page of the first trunk in the free-list.
48386  ** Possibly because the free-list is empty, or possibly because the
48387  ** first trunk in the free-list is full. Either way, the page being freed
48388  ** will become the new first trunk page in the free-list.
48389  */
48390  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
48391    goto freepage_out;
48392  }
48393  rc = sqlite3PagerWrite(pPage->pDbPage);
48394  if( rc!=SQLITE_OK ){
48395    goto freepage_out;
48396  }
48397  put4byte(pPage->aData, iTrunk);
48398  put4byte(&pPage->aData[4], 0);
48399  put4byte(&pPage1->aData[32], iPage);
48400  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
48401
48402freepage_out:
48403  if( pPage ){
48404    pPage->isInit = 0;
48405  }
48406  releasePage(pPage);
48407  releasePage(pTrunk);
48408  return rc;
48409}
48410static void freePage(MemPage *pPage, int *pRC){
48411  if( (*pRC)==SQLITE_OK ){
48412    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
48413  }
48414}
48415
48416/*
48417** Free any overflow pages associated with the given Cell.
48418*/
48419static int clearCell(MemPage *pPage, unsigned char *pCell){
48420  BtShared *pBt = pPage->pBt;
48421  CellInfo info;
48422  Pgno ovflPgno;
48423  int rc;
48424  int nOvfl;
48425  u16 ovflPageSize;
48426
48427  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48428  btreeParseCellPtr(pPage, pCell, &info);
48429  if( info.iOverflow==0 ){
48430    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
48431  }
48432  ovflPgno = get4byte(&pCell[info.iOverflow]);
48433  assert( pBt->usableSize > 4 );
48434  ovflPageSize = pBt->usableSize - 4;
48435  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
48436  assert( ovflPgno==0 || nOvfl>0 );
48437  while( nOvfl-- ){
48438    Pgno iNext = 0;
48439    MemPage *pOvfl = 0;
48440    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
48441      /* 0 is not a legal page number and page 1 cannot be an
48442      ** overflow page. Therefore if ovflPgno<2 or past the end of the
48443      ** file the database must be corrupt. */
48444      return SQLITE_CORRUPT_BKPT;
48445    }
48446    if( nOvfl ){
48447      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
48448      if( rc ) return rc;
48449    }
48450
48451    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
48452     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
48453    ){
48454      /* There is no reason any cursor should have an outstanding reference
48455      ** to an overflow page belonging to a cell that is being deleted/updated.
48456      ** So if there exists more than one reference to this page, then it
48457      ** must not really be an overflow page and the database must be corrupt.
48458      ** It is helpful to detect this before calling freePage2(), as
48459      ** freePage2() may zero the page contents if secure-delete mode is
48460      ** enabled. If this 'overflow' page happens to be a page that the
48461      ** caller is iterating through or using in some other way, this
48462      ** can be problematic.
48463      */
48464      rc = SQLITE_CORRUPT_BKPT;
48465    }else{
48466      rc = freePage2(pBt, pOvfl, ovflPgno);
48467    }
48468
48469    if( pOvfl ){
48470      sqlite3PagerUnref(pOvfl->pDbPage);
48471    }
48472    if( rc ) return rc;
48473    ovflPgno = iNext;
48474  }
48475  return SQLITE_OK;
48476}
48477
48478/*
48479** Create the byte sequence used to represent a cell on page pPage
48480** and write that byte sequence into pCell[].  Overflow pages are
48481** allocated and filled in as necessary.  The calling procedure
48482** is responsible for making sure sufficient space has been allocated
48483** for pCell[].
48484**
48485** Note that pCell does not necessary need to point to the pPage->aData
48486** area.  pCell might point to some temporary storage.  The cell will
48487** be constructed in this temporary area then copied into pPage->aData
48488** later.
48489*/
48490static int fillInCell(
48491  MemPage *pPage,                /* The page that contains the cell */
48492  unsigned char *pCell,          /* Complete text of the cell */
48493  const void *pKey, i64 nKey,    /* The key */
48494  const void *pData,int nData,   /* The data */
48495  int nZero,                     /* Extra zero bytes to append to pData */
48496  int *pnSize                    /* Write cell size here */
48497){
48498  int nPayload;
48499  const u8 *pSrc;
48500  int nSrc, n, rc;
48501  int spaceLeft;
48502  MemPage *pOvfl = 0;
48503  MemPage *pToRelease = 0;
48504  unsigned char *pPrior;
48505  unsigned char *pPayload;
48506  BtShared *pBt = pPage->pBt;
48507  Pgno pgnoOvfl = 0;
48508  int nHeader;
48509  CellInfo info;
48510
48511  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48512
48513  /* pPage is not necessarily writeable since pCell might be auxiliary
48514  ** buffer space that is separate from the pPage buffer area */
48515  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
48516            || sqlite3PagerIswriteable(pPage->pDbPage) );
48517
48518  /* Fill in the header. */
48519  nHeader = 0;
48520  if( !pPage->leaf ){
48521    nHeader += 4;
48522  }
48523  if( pPage->hasData ){
48524    nHeader += putVarint(&pCell[nHeader], nData+nZero);
48525  }else{
48526    nData = nZero = 0;
48527  }
48528  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
48529  btreeParseCellPtr(pPage, pCell, &info);
48530  assert( info.nHeader==nHeader );
48531  assert( info.nKey==nKey );
48532  assert( info.nData==(u32)(nData+nZero) );
48533
48534  /* Fill in the payload */
48535  nPayload = nData + nZero;
48536  if( pPage->intKey ){
48537    pSrc = pData;
48538    nSrc = nData;
48539    nData = 0;
48540  }else{
48541    if( NEVER(nKey>0x7fffffff || pKey==0) ){
48542      return SQLITE_CORRUPT_BKPT;
48543    }
48544    nPayload += (int)nKey;
48545    pSrc = pKey;
48546    nSrc = (int)nKey;
48547  }
48548  *pnSize = info.nSize;
48549  spaceLeft = info.nLocal;
48550  pPayload = &pCell[nHeader];
48551  pPrior = &pCell[info.iOverflow];
48552
48553  while( nPayload>0 ){
48554    if( spaceLeft==0 ){
48555#ifndef SQLITE_OMIT_AUTOVACUUM
48556      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
48557      if( pBt->autoVacuum ){
48558        do{
48559          pgnoOvfl++;
48560        } while(
48561          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
48562        );
48563      }
48564#endif
48565      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
48566#ifndef SQLITE_OMIT_AUTOVACUUM
48567      /* If the database supports auto-vacuum, and the second or subsequent
48568      ** overflow page is being allocated, add an entry to the pointer-map
48569      ** for that page now.
48570      **
48571      ** If this is the first overflow page, then write a partial entry
48572      ** to the pointer-map. If we write nothing to this pointer-map slot,
48573      ** then the optimistic overflow chain processing in clearCell()
48574      ** may misinterpret the uninitialised values and delete the
48575      ** wrong pages from the database.
48576      */
48577      if( pBt->autoVacuum && rc==SQLITE_OK ){
48578        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
48579        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
48580        if( rc ){
48581          releasePage(pOvfl);
48582        }
48583      }
48584#endif
48585      if( rc ){
48586        releasePage(pToRelease);
48587        return rc;
48588      }
48589
48590      /* If pToRelease is not zero than pPrior points into the data area
48591      ** of pToRelease.  Make sure pToRelease is still writeable. */
48592      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48593
48594      /* If pPrior is part of the data area of pPage, then make sure pPage
48595      ** is still writeable */
48596      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
48597            || sqlite3PagerIswriteable(pPage->pDbPage) );
48598
48599      put4byte(pPrior, pgnoOvfl);
48600      releasePage(pToRelease);
48601      pToRelease = pOvfl;
48602      pPrior = pOvfl->aData;
48603      put4byte(pPrior, 0);
48604      pPayload = &pOvfl->aData[4];
48605      spaceLeft = pBt->usableSize - 4;
48606    }
48607    n = nPayload;
48608    if( n>spaceLeft ) n = spaceLeft;
48609
48610    /* If pToRelease is not zero than pPayload points into the data area
48611    ** of pToRelease.  Make sure pToRelease is still writeable. */
48612    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48613
48614    /* If pPayload is part of the data area of pPage, then make sure pPage
48615    ** is still writeable */
48616    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
48617            || sqlite3PagerIswriteable(pPage->pDbPage) );
48618
48619    if( nSrc>0 ){
48620      if( n>nSrc ) n = nSrc;
48621      assert( pSrc );
48622      memcpy(pPayload, pSrc, n);
48623    }else{
48624      memset(pPayload, 0, n);
48625    }
48626    nPayload -= n;
48627    pPayload += n;
48628    pSrc += n;
48629    nSrc -= n;
48630    spaceLeft -= n;
48631    if( nSrc==0 ){
48632      nSrc = nData;
48633      pSrc = pData;
48634    }
48635  }
48636  releasePage(pToRelease);
48637  return SQLITE_OK;
48638}
48639
48640/*
48641** Remove the i-th cell from pPage.  This routine effects pPage only.
48642** The cell content is not freed or deallocated.  It is assumed that
48643** the cell content has been copied someplace else.  This routine just
48644** removes the reference to the cell from pPage.
48645**
48646** "sz" must be the number of bytes in the cell.
48647*/
48648static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
48649  int i;          /* Loop counter */
48650  int pc;         /* Offset to cell content of cell being deleted */
48651  u8 *data;       /* pPage->aData */
48652  u8 *ptr;        /* Used to move bytes around within data[] */
48653  int rc;         /* The return code */
48654  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
48655
48656  if( *pRC ) return;
48657
48658  assert( idx>=0 && idx<pPage->nCell );
48659  assert( sz==cellSize(pPage, idx) );
48660  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48661  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48662  data = pPage->aData;
48663  ptr = &data[pPage->cellOffset + 2*idx];
48664  pc = get2byte(ptr);
48665  hdr = pPage->hdrOffset;
48666  testcase( pc==get2byte(&data[hdr+5]) );
48667  testcase( pc+sz==pPage->pBt->usableSize );
48668  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
48669    *pRC = SQLITE_CORRUPT_BKPT;
48670    return;
48671  }
48672  rc = freeSpace(pPage, pc, sz);
48673  if( rc ){
48674    *pRC = rc;
48675    return;
48676  }
48677  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
48678    ptr[0] = ptr[2];
48679    ptr[1] = ptr[3];
48680  }
48681  pPage->nCell--;
48682  put2byte(&data[hdr+3], pPage->nCell);
48683  pPage->nFree += 2;
48684}
48685
48686/*
48687** Insert a new cell on pPage at cell index "i".  pCell points to the
48688** content of the cell.
48689**
48690** If the cell content will fit on the page, then put it there.  If it
48691** will not fit, then make a copy of the cell content into pTemp if
48692** pTemp is not null.  Regardless of pTemp, allocate a new entry
48693** in pPage->aOvfl[] and make it point to the cell content (either
48694** in pTemp or the original pCell) and also record its index.
48695** Allocating a new entry in pPage->aCell[] implies that
48696** pPage->nOverflow is incremented.
48697**
48698** If nSkip is non-zero, then do not copy the first nSkip bytes of the
48699** cell. The caller will overwrite them after this function returns. If
48700** nSkip is non-zero, then pCell may not point to an invalid memory location
48701** (but pCell+nSkip is always valid).
48702*/
48703static void insertCell(
48704  MemPage *pPage,   /* Page into which we are copying */
48705  int i,            /* New cell becomes the i-th cell of the page */
48706  u8 *pCell,        /* Content of the new cell */
48707  int sz,           /* Bytes of content in pCell */
48708  u8 *pTemp,        /* Temp storage space for pCell, if needed */
48709  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
48710  int *pRC          /* Read and write return code from here */
48711){
48712  int idx = 0;      /* Where to write new cell content in data[] */
48713  int j;            /* Loop counter */
48714  int end;          /* First byte past the last cell pointer in data[] */
48715  int ins;          /* Index in data[] where new cell pointer is inserted */
48716  int cellOffset;   /* Address of first cell pointer in data[] */
48717  u8 *data;         /* The content of the whole page */
48718  u8 *ptr;          /* Used for moving information around in data[] */
48719
48720  int nSkip = (iChild ? 4 : 0);
48721
48722  if( *pRC ) return;
48723
48724  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
48725  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
48726  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
48727  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48728  /* The cell should normally be sized correctly.  However, when moving a
48729  ** malformed cell from a leaf page to an interior page, if the cell size
48730  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
48731  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
48732  ** the term after the || in the following assert(). */
48733  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
48734  if( pPage->nOverflow || sz+2>pPage->nFree ){
48735    if( pTemp ){
48736      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
48737      pCell = pTemp;
48738    }
48739    if( iChild ){
48740      put4byte(pCell, iChild);
48741    }
48742    j = pPage->nOverflow++;
48743    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
48744    pPage->aOvfl[j].pCell = pCell;
48745    pPage->aOvfl[j].idx = (u16)i;
48746  }else{
48747    int rc = sqlite3PagerWrite(pPage->pDbPage);
48748    if( rc!=SQLITE_OK ){
48749      *pRC = rc;
48750      return;
48751    }
48752    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48753    data = pPage->aData;
48754    cellOffset = pPage->cellOffset;
48755    end = cellOffset + 2*pPage->nCell;
48756    ins = cellOffset + 2*i;
48757    rc = allocateSpace(pPage, sz, &idx);
48758    if( rc ){ *pRC = rc; return; }
48759    /* The allocateSpace() routine guarantees the following two properties
48760    ** if it returns success */
48761    assert( idx >= end+2 );
48762    assert( idx+sz <= pPage->pBt->usableSize );
48763    pPage->nCell++;
48764    pPage->nFree -= (u16)(2 + sz);
48765    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
48766    if( iChild ){
48767      put4byte(&data[idx], iChild);
48768    }
48769    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
48770      ptr[0] = ptr[-2];
48771      ptr[1] = ptr[-1];
48772    }
48773    put2byte(&data[ins], idx);
48774    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
48775#ifndef SQLITE_OMIT_AUTOVACUUM
48776    if( pPage->pBt->autoVacuum ){
48777      /* The cell may contain a pointer to an overflow page. If so, write
48778      ** the entry for the overflow page into the pointer map.
48779      */
48780      ptrmapPutOvflPtr(pPage, pCell, pRC);
48781    }
48782#endif
48783  }
48784}
48785
48786/*
48787** Add a list of cells to a page.  The page should be initially empty.
48788** The cells are guaranteed to fit on the page.
48789*/
48790static void assemblePage(
48791  MemPage *pPage,   /* The page to be assemblied */
48792  int nCell,        /* The number of cells to add to this page */
48793  u8 **apCell,      /* Pointers to cell bodies */
48794  u16 *aSize        /* Sizes of the cells */
48795){
48796  int i;            /* Loop counter */
48797  u8 *pCellptr;     /* Address of next cell pointer */
48798  int cellbody;     /* Address of next cell body */
48799  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
48800  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
48801  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
48802
48803  assert( pPage->nOverflow==0 );
48804  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48805  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
48806  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48807
48808  /* Check that the page has just been zeroed by zeroPage() */
48809  assert( pPage->nCell==0 );
48810  assert( get2byte(&data[hdr+5])==nUsable );
48811
48812  pCellptr = &data[pPage->cellOffset + nCell*2];
48813  cellbody = nUsable;
48814  for(i=nCell-1; i>=0; i--){
48815    pCellptr -= 2;
48816    cellbody -= aSize[i];
48817    put2byte(pCellptr, cellbody);
48818    memcpy(&data[cellbody], apCell[i], aSize[i]);
48819  }
48820  put2byte(&data[hdr+3], nCell);
48821  put2byte(&data[hdr+5], cellbody);
48822  pPage->nFree -= (nCell*2 + nUsable - cellbody);
48823  pPage->nCell = (u16)nCell;
48824}
48825
48826/*
48827** The following parameters determine how many adjacent pages get involved
48828** in a balancing operation.  NN is the number of neighbors on either side
48829** of the page that participate in the balancing operation.  NB is the
48830** total number of pages that participate, including the target page and
48831** NN neighbors on either side.
48832**
48833** The minimum value of NN is 1 (of course).  Increasing NN above 1
48834** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
48835** in exchange for a larger degradation in INSERT and UPDATE performance.
48836** The value of NN appears to give the best results overall.
48837*/
48838#define NN 1             /* Number of neighbors on either side of pPage */
48839#define NB (NN*2+1)      /* Total pages involved in the balance */
48840
48841
48842#ifndef SQLITE_OMIT_QUICKBALANCE
48843/*
48844** This version of balance() handles the common special case where
48845** a new entry is being inserted on the extreme right-end of the
48846** tree, in other words, when the new entry will become the largest
48847** entry in the tree.
48848**
48849** Instead of trying to balance the 3 right-most leaf pages, just add
48850** a new page to the right-hand side and put the one new entry in
48851** that page.  This leaves the right side of the tree somewhat
48852** unbalanced.  But odds are that we will be inserting new entries
48853** at the end soon afterwards so the nearly empty page will quickly
48854** fill up.  On average.
48855**
48856** pPage is the leaf page which is the right-most page in the tree.
48857** pParent is its parent.  pPage must have a single overflow entry
48858** which is also the right-most entry on the page.
48859**
48860** The pSpace buffer is used to store a temporary copy of the divider
48861** cell that will be inserted into pParent. Such a cell consists of a 4
48862** byte page number followed by a variable length integer. In other
48863** words, at most 13 bytes. Hence the pSpace buffer must be at
48864** least 13 bytes in size.
48865*/
48866static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
48867  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
48868  MemPage *pNew;                       /* Newly allocated page */
48869  int rc;                              /* Return Code */
48870  Pgno pgnoNew;                        /* Page number of pNew */
48871
48872  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48873  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
48874  assert( pPage->nOverflow==1 );
48875
48876  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
48877
48878  /* Allocate a new page. This page will become the right-sibling of
48879  ** pPage. Make the parent page writable, so that the new divider cell
48880  ** may be inserted. If both these operations are successful, proceed.
48881  */
48882  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
48883
48884  if( rc==SQLITE_OK ){
48885
48886    u8 *pOut = &pSpace[4];
48887    u8 *pCell = pPage->aOvfl[0].pCell;
48888    u16 szCell = cellSizePtr(pPage, pCell);
48889    u8 *pStop;
48890
48891    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
48892    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
48893    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
48894    assemblePage(pNew, 1, &pCell, &szCell);
48895
48896    /* If this is an auto-vacuum database, update the pointer map
48897    ** with entries for the new page, and any pointer from the
48898    ** cell on the page to an overflow page. If either of these
48899    ** operations fails, the return code is set, but the contents
48900    ** of the parent page are still manipulated by thh code below.
48901    ** That is Ok, at this point the parent page is guaranteed to
48902    ** be marked as dirty. Returning an error code will cause a
48903    ** rollback, undoing any changes made to the parent page.
48904    */
48905    if( ISAUTOVACUUM ){
48906      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
48907      if( szCell>pNew->minLocal ){
48908        ptrmapPutOvflPtr(pNew, pCell, &rc);
48909      }
48910    }
48911
48912    /* Create a divider cell to insert into pParent. The divider cell
48913    ** consists of a 4-byte page number (the page number of pPage) and
48914    ** a variable length key value (which must be the same value as the
48915    ** largest key on pPage).
48916    **
48917    ** To find the largest key value on pPage, first find the right-most
48918    ** cell on pPage. The first two fields of this cell are the
48919    ** record-length (a variable length integer at most 32-bits in size)
48920    ** and the key value (a variable length integer, may have any value).
48921    ** The first of the while(...) loops below skips over the record-length
48922    ** field. The second while(...) loop copies the key value from the
48923    ** cell on pPage into the pSpace buffer.
48924    */
48925    pCell = findCell(pPage, pPage->nCell-1);
48926    pStop = &pCell[9];
48927    while( (*(pCell++)&0x80) && pCell<pStop );
48928    pStop = &pCell[9];
48929    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
48930
48931    /* Insert the new divider cell into pParent. */
48932    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
48933               0, pPage->pgno, &rc);
48934
48935    /* Set the right-child pointer of pParent to point to the new page. */
48936    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
48937
48938    /* Release the reference to the new page. */
48939    releasePage(pNew);
48940  }
48941
48942  return rc;
48943}
48944#endif /* SQLITE_OMIT_QUICKBALANCE */
48945
48946#if 0
48947/*
48948** This function does not contribute anything to the operation of SQLite.
48949** it is sometimes activated temporarily while debugging code responsible
48950** for setting pointer-map entries.
48951*/
48952static int ptrmapCheckPages(MemPage **apPage, int nPage){
48953  int i, j;
48954  for(i=0; i<nPage; i++){
48955    Pgno n;
48956    u8 e;
48957    MemPage *pPage = apPage[i];
48958    BtShared *pBt = pPage->pBt;
48959    assert( pPage->isInit );
48960
48961    for(j=0; j<pPage->nCell; j++){
48962      CellInfo info;
48963      u8 *z;
48964
48965      z = findCell(pPage, j);
48966      btreeParseCellPtr(pPage, z, &info);
48967      if( info.iOverflow ){
48968        Pgno ovfl = get4byte(&z[info.iOverflow]);
48969        ptrmapGet(pBt, ovfl, &e, &n);
48970        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
48971      }
48972      if( !pPage->leaf ){
48973        Pgno child = get4byte(z);
48974        ptrmapGet(pBt, child, &e, &n);
48975        assert( n==pPage->pgno && e==PTRMAP_BTREE );
48976      }
48977    }
48978    if( !pPage->leaf ){
48979      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
48980      ptrmapGet(pBt, child, &e, &n);
48981      assert( n==pPage->pgno && e==PTRMAP_BTREE );
48982    }
48983  }
48984  return 1;
48985}
48986#endif
48987
48988/*
48989** This function is used to copy the contents of the b-tree node stored
48990** on page pFrom to page pTo. If page pFrom was not a leaf page, then
48991** the pointer-map entries for each child page are updated so that the
48992** parent page stored in the pointer map is page pTo. If pFrom contained
48993** any cells with overflow page pointers, then the corresponding pointer
48994** map entries are also updated so that the parent page is page pTo.
48995**
48996** If pFrom is currently carrying any overflow cells (entries in the
48997** MemPage.aOvfl[] array), they are not copied to pTo.
48998**
48999** Before returning, page pTo is reinitialized using btreeInitPage().
49000**
49001** The performance of this function is not critical. It is only used by
49002** the balance_shallower() and balance_deeper() procedures, neither of
49003** which are called often under normal circumstances.
49004*/
49005static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
49006  if( (*pRC)==SQLITE_OK ){
49007    BtShared * const pBt = pFrom->pBt;
49008    u8 * const aFrom = pFrom->aData;
49009    u8 * const aTo = pTo->aData;
49010    int const iFromHdr = pFrom->hdrOffset;
49011    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
49012    int rc;
49013    int iData;
49014
49015
49016    assert( pFrom->isInit );
49017    assert( pFrom->nFree>=iToHdr );
49018    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
49019
49020    /* Copy the b-tree node content from page pFrom to page pTo. */
49021    iData = get2byte(&aFrom[iFromHdr+5]);
49022    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
49023    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
49024
49025    /* Reinitialize page pTo so that the contents of the MemPage structure
49026    ** match the new data. The initialization of pTo can actually fail under
49027    ** fairly obscure circumstances, even though it is a copy of initialized
49028    ** page pFrom.
49029    */
49030    pTo->isInit = 0;
49031    rc = btreeInitPage(pTo);
49032    if( rc!=SQLITE_OK ){
49033      *pRC = rc;
49034      return;
49035    }
49036
49037    /* If this is an auto-vacuum database, update the pointer-map entries
49038    ** for any b-tree or overflow pages that pTo now contains the pointers to.
49039    */
49040    if( ISAUTOVACUUM ){
49041      *pRC = setChildPtrmaps(pTo);
49042    }
49043  }
49044}
49045
49046/*
49047** This routine redistributes cells on the iParentIdx'th child of pParent
49048** (hereafter "the page") and up to 2 siblings so that all pages have about the
49049** same amount of free space. Usually a single sibling on either side of the
49050** page are used in the balancing, though both siblings might come from one
49051** side if the page is the first or last child of its parent. If the page
49052** has fewer than 2 siblings (something which can only happen if the page
49053** is a root page or a child of a root page) then all available siblings
49054** participate in the balancing.
49055**
49056** The number of siblings of the page might be increased or decreased by
49057** one or two in an effort to keep pages nearly full but not over full.
49058**
49059** Note that when this routine is called, some of the cells on the page
49060** might not actually be stored in MemPage.aData[]. This can happen
49061** if the page is overfull. This routine ensures that all cells allocated
49062** to the page and its siblings fit into MemPage.aData[] before returning.
49063**
49064** In the course of balancing the page and its siblings, cells may be
49065** inserted into or removed from the parent page (pParent). Doing so
49066** may cause the parent page to become overfull or underfull. If this
49067** happens, it is the responsibility of the caller to invoke the correct
49068** balancing routine to fix this problem (see the balance() routine).
49069**
49070** If this routine fails for any reason, it might leave the database
49071** in a corrupted state. So if this routine fails, the database should
49072** be rolled back.
49073**
49074** The third argument to this function, aOvflSpace, is a pointer to a
49075** buffer big enough to hold one page. If while inserting cells into the parent
49076** page (pParent) the parent page becomes overfull, this buffer is
49077** used to store the parent's overflow cells. Because this function inserts
49078** a maximum of four divider cells into the parent page, and the maximum
49079** size of a cell stored within an internal node is always less than 1/4
49080** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
49081** enough for all overflow cells.
49082**
49083** If aOvflSpace is set to a null pointer, this function returns
49084** SQLITE_NOMEM.
49085*/
49086static int balance_nonroot(
49087  MemPage *pParent,               /* Parent page of siblings being balanced */
49088  int iParentIdx,                 /* Index of "the page" in pParent */
49089  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
49090  int isRoot                      /* True if pParent is a root-page */
49091){
49092  BtShared *pBt;               /* The whole database */
49093  int nCell = 0;               /* Number of cells in apCell[] */
49094  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
49095  int nNew = 0;                /* Number of pages in apNew[] */
49096  int nOld;                    /* Number of pages in apOld[] */
49097  int i, j, k;                 /* Loop counters */
49098  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
49099  int rc = SQLITE_OK;          /* The return code */
49100  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
49101  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
49102  int usableSpace;             /* Bytes in pPage beyond the header */
49103  int pageFlags;               /* Value of pPage->aData[0] */
49104  int subtotal;                /* Subtotal of bytes in cells on one page */
49105  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
49106  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
49107  int szScratch;               /* Size of scratch memory requested */
49108  MemPage *apOld[NB];          /* pPage and up to two siblings */
49109  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
49110  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
49111  u8 *pRight;                  /* Location in parent of right-sibling pointer */
49112  u8 *apDiv[NB-1];             /* Divider cells in pParent */
49113  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
49114  int szNew[NB+2];             /* Combined size of cells place on i-th page */
49115  u8 **apCell = 0;             /* All cells begin balanced */
49116  u16 *szCell;                 /* Local size of all cells in apCell[] */
49117  u8 *aSpace1;                 /* Space for copies of dividers cells */
49118  Pgno pgno;                   /* Temp var to store a page number in */
49119
49120  pBt = pParent->pBt;
49121  assert( sqlite3_mutex_held(pBt->mutex) );
49122  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49123
49124#if 0
49125  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
49126#endif
49127
49128  /* At this point pParent may have at most one overflow cell. And if
49129  ** this overflow cell is present, it must be the cell with
49130  ** index iParentIdx. This scenario comes about when this function
49131  ** is called (indirectly) from sqlite3BtreeDelete().
49132  */
49133  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
49134  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
49135
49136  if( !aOvflSpace ){
49137    return SQLITE_NOMEM;
49138  }
49139
49140  /* Find the sibling pages to balance. Also locate the cells in pParent
49141  ** that divide the siblings. An attempt is made to find NN siblings on
49142  ** either side of pPage. More siblings are taken from one side, however,
49143  ** if there are fewer than NN siblings on the other side. If pParent
49144  ** has NB or fewer children then all children of pParent are taken.
49145  **
49146  ** This loop also drops the divider cells from the parent page. This
49147  ** way, the remainder of the function does not have to deal with any
49148  ** overflow cells in the parent page, since if any existed they will
49149  ** have already been removed.
49150  */
49151  i = pParent->nOverflow + pParent->nCell;
49152  if( i<2 ){
49153    nxDiv = 0;
49154    nOld = i+1;
49155  }else{
49156    nOld = 3;
49157    if( iParentIdx==0 ){
49158      nxDiv = 0;
49159    }else if( iParentIdx==i ){
49160      nxDiv = i-2;
49161    }else{
49162      nxDiv = iParentIdx-1;
49163    }
49164    i = 2;
49165  }
49166  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
49167    pRight = &pParent->aData[pParent->hdrOffset+8];
49168  }else{
49169    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
49170  }
49171  pgno = get4byte(pRight);
49172  while( 1 ){
49173    rc = getAndInitPage(pBt, pgno, &apOld[i]);
49174    if( rc ){
49175      memset(apOld, 0, (i+1)*sizeof(MemPage*));
49176      goto balance_cleanup;
49177    }
49178    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
49179    if( (i--)==0 ) break;
49180
49181    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
49182      apDiv[i] = pParent->aOvfl[0].pCell;
49183      pgno = get4byte(apDiv[i]);
49184      szNew[i] = cellSizePtr(pParent, apDiv[i]);
49185      pParent->nOverflow = 0;
49186    }else{
49187      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
49188      pgno = get4byte(apDiv[i]);
49189      szNew[i] = cellSizePtr(pParent, apDiv[i]);
49190
49191      /* Drop the cell from the parent page. apDiv[i] still points to
49192      ** the cell within the parent, even though it has been dropped.
49193      ** This is safe because dropping a cell only overwrites the first
49194      ** four bytes of it, and this function does not need the first
49195      ** four bytes of the divider cell. So the pointer is safe to use
49196      ** later on.
49197      **
49198      ** Unless SQLite is compiled in secure-delete mode. In this case,
49199      ** the dropCell() routine will overwrite the entire cell with zeroes.
49200      ** In this case, temporarily copy the cell into the aOvflSpace[]
49201      ** buffer. It will be copied out again as soon as the aSpace[] buffer
49202      ** is allocated.  */
49203      if( pBt->secureDelete ){
49204        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
49205        if( (iOff+szNew[i])>pBt->usableSize ){
49206          rc = SQLITE_CORRUPT_BKPT;
49207          memset(apOld, 0, (i+1)*sizeof(MemPage*));
49208          goto balance_cleanup;
49209        }else{
49210          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
49211          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
49212        }
49213      }
49214      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
49215    }
49216  }
49217
49218  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
49219  ** alignment */
49220  nMaxCells = (nMaxCells + 3)&~3;
49221
49222  /*
49223  ** Allocate space for memory structures
49224  */
49225  k = pBt->pageSize + ROUND8(sizeof(MemPage));
49226  szScratch =
49227       nMaxCells*sizeof(u8*)                       /* apCell */
49228     + nMaxCells*sizeof(u16)                       /* szCell */
49229     + pBt->pageSize                               /* aSpace1 */
49230     + k*nOld;                                     /* Page copies (apCopy) */
49231  apCell = sqlite3ScratchMalloc( szScratch );
49232  if( apCell==0 ){
49233    rc = SQLITE_NOMEM;
49234    goto balance_cleanup;
49235  }
49236  szCell = (u16*)&apCell[nMaxCells];
49237  aSpace1 = (u8*)&szCell[nMaxCells];
49238  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
49239
49240  /*
49241  ** Load pointers to all cells on sibling pages and the divider cells
49242  ** into the local apCell[] array.  Make copies of the divider cells
49243  ** into space obtained from aSpace1[] and remove the the divider Cells
49244  ** from pParent.
49245  **
49246  ** If the siblings are on leaf pages, then the child pointers of the
49247  ** divider cells are stripped from the cells before they are copied
49248  ** into aSpace1[].  In this way, all cells in apCell[] are without
49249  ** child pointers.  If siblings are not leaves, then all cell in
49250  ** apCell[] include child pointers.  Either way, all cells in apCell[]
49251  ** are alike.
49252  **
49253  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
49254  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
49255  */
49256  leafCorrection = apOld[0]->leaf*4;
49257  leafData = apOld[0]->hasData;
49258  for(i=0; i<nOld; i++){
49259    int limit;
49260
49261    /* Before doing anything else, take a copy of the i'th original sibling
49262    ** The rest of this function will use data from the copies rather
49263    ** that the original pages since the original pages will be in the
49264    ** process of being overwritten.  */
49265    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
49266    memcpy(pOld, apOld[i], sizeof(MemPage));
49267    pOld->aData = (void*)&pOld[1];
49268    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
49269
49270    limit = pOld->nCell+pOld->nOverflow;
49271    for(j=0; j<limit; j++){
49272      assert( nCell<nMaxCells );
49273      apCell[nCell] = findOverflowCell(pOld, j);
49274      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
49275      nCell++;
49276    }
49277    if( i<nOld-1 && !leafData){
49278      u16 sz = (u16)szNew[i];
49279      u8 *pTemp;
49280      assert( nCell<nMaxCells );
49281      szCell[nCell] = sz;
49282      pTemp = &aSpace1[iSpace1];
49283      iSpace1 += sz;
49284      assert( sz<=pBt->pageSize/4 );
49285      assert( iSpace1<=pBt->pageSize );
49286      memcpy(pTemp, apDiv[i], sz);
49287      apCell[nCell] = pTemp+leafCorrection;
49288      assert( leafCorrection==0 || leafCorrection==4 );
49289      szCell[nCell] = szCell[nCell] - leafCorrection;
49290      if( !pOld->leaf ){
49291        assert( leafCorrection==0 );
49292        assert( pOld->hdrOffset==0 );
49293        /* The right pointer of the child page pOld becomes the left
49294        ** pointer of the divider cell */
49295        memcpy(apCell[nCell], &pOld->aData[8], 4);
49296      }else{
49297        assert( leafCorrection==4 );
49298        if( szCell[nCell]<4 ){
49299          /* Do not allow any cells smaller than 4 bytes. */
49300          szCell[nCell] = 4;
49301        }
49302      }
49303      nCell++;
49304    }
49305  }
49306
49307  /*
49308  ** Figure out the number of pages needed to hold all nCell cells.
49309  ** Store this number in "k".  Also compute szNew[] which is the total
49310  ** size of all cells on the i-th page and cntNew[] which is the index
49311  ** in apCell[] of the cell that divides page i from page i+1.
49312  ** cntNew[k] should equal nCell.
49313  **
49314  ** Values computed by this block:
49315  **
49316  **           k: The total number of sibling pages
49317  **    szNew[i]: Spaced used on the i-th sibling page.
49318  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
49319  **              the right of the i-th sibling page.
49320  ** usableSpace: Number of bytes of space available on each sibling.
49321  **
49322  */
49323  usableSpace = pBt->usableSize - 12 + leafCorrection;
49324  for(subtotal=k=i=0; i<nCell; i++){
49325    assert( i<nMaxCells );
49326    subtotal += szCell[i] + 2;
49327    if( subtotal > usableSpace ){
49328      szNew[k] = subtotal - szCell[i];
49329      cntNew[k] = i;
49330      if( leafData ){ i--; }
49331      subtotal = 0;
49332      k++;
49333      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
49334    }
49335  }
49336  szNew[k] = subtotal;
49337  cntNew[k] = nCell;
49338  k++;
49339
49340  /*
49341  ** The packing computed by the previous block is biased toward the siblings
49342  ** on the left side.  The left siblings are always nearly full, while the
49343  ** right-most sibling might be nearly empty.  This block of code attempts
49344  ** to adjust the packing of siblings to get a better balance.
49345  **
49346  ** This adjustment is more than an optimization.  The packing above might
49347  ** be so out of balance as to be illegal.  For example, the right-most
49348  ** sibling might be completely empty.  This adjustment is not optional.
49349  */
49350  for(i=k-1; i>0; i--){
49351    int szRight = szNew[i];  /* Size of sibling on the right */
49352    int szLeft = szNew[i-1]; /* Size of sibling on the left */
49353    int r;              /* Index of right-most cell in left sibling */
49354    int d;              /* Index of first cell to the left of right sibling */
49355
49356    r = cntNew[i-1] - 1;
49357    d = r + 1 - leafData;
49358    assert( d<nMaxCells );
49359    assert( r<nMaxCells );
49360    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
49361      szRight += szCell[d] + 2;
49362      szLeft -= szCell[r] + 2;
49363      cntNew[i-1]--;
49364      r = cntNew[i-1] - 1;
49365      d = r + 1 - leafData;
49366    }
49367    szNew[i] = szRight;
49368    szNew[i-1] = szLeft;
49369  }
49370
49371  /* Either we found one or more cells (cntnew[0])>0) or pPage is
49372  ** a virtual root page.  A virtual root page is when the real root
49373  ** page is page 1 and we are the only child of that page.
49374  */
49375  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
49376
49377  TRACE(("BALANCE: old: %d %d %d  ",
49378    apOld[0]->pgno,
49379    nOld>=2 ? apOld[1]->pgno : 0,
49380    nOld>=3 ? apOld[2]->pgno : 0
49381  ));
49382
49383  /*
49384  ** Allocate k new pages.  Reuse old pages where possible.
49385  */
49386  if( apOld[0]->pgno<=1 ){
49387    rc = SQLITE_CORRUPT_BKPT;
49388    goto balance_cleanup;
49389  }
49390  pageFlags = apOld[0]->aData[0];
49391  for(i=0; i<k; i++){
49392    MemPage *pNew;
49393    if( i<nOld ){
49394      pNew = apNew[i] = apOld[i];
49395      apOld[i] = 0;
49396      rc = sqlite3PagerWrite(pNew->pDbPage);
49397      nNew++;
49398      if( rc ) goto balance_cleanup;
49399    }else{
49400      assert( i>0 );
49401      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
49402      if( rc ) goto balance_cleanup;
49403      apNew[i] = pNew;
49404      nNew++;
49405
49406      /* Set the pointer-map entry for the new sibling page. */
49407      if( ISAUTOVACUUM ){
49408        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
49409        if( rc!=SQLITE_OK ){
49410          goto balance_cleanup;
49411        }
49412      }
49413    }
49414  }
49415
49416  /* Free any old pages that were not reused as new pages.
49417  */
49418  while( i<nOld ){
49419    freePage(apOld[i], &rc);
49420    if( rc ) goto balance_cleanup;
49421    releasePage(apOld[i]);
49422    apOld[i] = 0;
49423    i++;
49424  }
49425
49426  /*
49427  ** Put the new pages in accending order.  This helps to
49428  ** keep entries in the disk file in order so that a scan
49429  ** of the table is a linear scan through the file.  That
49430  ** in turn helps the operating system to deliver pages
49431  ** from the disk more rapidly.
49432  **
49433  ** An O(n^2) insertion sort algorithm is used, but since
49434  ** n is never more than NB (a small constant), that should
49435  ** not be a problem.
49436  **
49437  ** When NB==3, this one optimization makes the database
49438  ** about 25% faster for large insertions and deletions.
49439  */
49440  for(i=0; i<k-1; i++){
49441    int minV = apNew[i]->pgno;
49442    int minI = i;
49443    for(j=i+1; j<k; j++){
49444      if( apNew[j]->pgno<(unsigned)minV ){
49445        minI = j;
49446        minV = apNew[j]->pgno;
49447      }
49448    }
49449    if( minI>i ){
49450      int t;
49451      MemPage *pT;
49452      t = apNew[i]->pgno;
49453      pT = apNew[i];
49454      apNew[i] = apNew[minI];
49455      apNew[minI] = pT;
49456    }
49457  }
49458  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
49459    apNew[0]->pgno, szNew[0],
49460    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
49461    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
49462    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
49463    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
49464
49465  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49466  put4byte(pRight, apNew[nNew-1]->pgno);
49467
49468  /*
49469  ** Evenly distribute the data in apCell[] across the new pages.
49470  ** Insert divider cells into pParent as necessary.
49471  */
49472  j = 0;
49473  for(i=0; i<nNew; i++){
49474    /* Assemble the new sibling page. */
49475    MemPage *pNew = apNew[i];
49476    assert( j<nMaxCells );
49477    zeroPage(pNew, pageFlags);
49478    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
49479    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
49480    assert( pNew->nOverflow==0 );
49481
49482    j = cntNew[i];
49483
49484    /* If the sibling page assembled above was not the right-most sibling,
49485    ** insert a divider cell into the parent page.
49486    */
49487    assert( i<nNew-1 || j==nCell );
49488    if( j<nCell ){
49489      u8 *pCell;
49490      u8 *pTemp;
49491      int sz;
49492
49493      assert( j<nMaxCells );
49494      pCell = apCell[j];
49495      sz = szCell[j] + leafCorrection;
49496      pTemp = &aOvflSpace[iOvflSpace];
49497      if( !pNew->leaf ){
49498        memcpy(&pNew->aData[8], pCell, 4);
49499      }else if( leafData ){
49500        /* If the tree is a leaf-data tree, and the siblings are leaves,
49501        ** then there is no divider cell in apCell[]. Instead, the divider
49502        ** cell consists of the integer key for the right-most cell of
49503        ** the sibling-page assembled above only.
49504        */
49505        CellInfo info;
49506        j--;
49507        btreeParseCellPtr(pNew, apCell[j], &info);
49508        pCell = pTemp;
49509        sz = 4 + putVarint(&pCell[4], info.nKey);
49510        pTemp = 0;
49511      }else{
49512        pCell -= 4;
49513        /* Obscure case for non-leaf-data trees: If the cell at pCell was
49514        ** previously stored on a leaf node, and its reported size was 4
49515        ** bytes, then it may actually be smaller than this
49516        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
49517        ** any cell). But it is important to pass the correct size to
49518        ** insertCell(), so reparse the cell now.
49519        **
49520        ** Note that this can never happen in an SQLite data file, as all
49521        ** cells are at least 4 bytes. It only happens in b-trees used
49522        ** to evaluate "IN (SELECT ...)" and similar clauses.
49523        */
49524        if( szCell[j]==4 ){
49525          assert(leafCorrection==4);
49526          sz = cellSizePtr(pParent, pCell);
49527        }
49528      }
49529      iOvflSpace += sz;
49530      assert( sz<=pBt->pageSize/4 );
49531      assert( iOvflSpace<=pBt->pageSize );
49532      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
49533      if( rc!=SQLITE_OK ) goto balance_cleanup;
49534      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49535
49536      j++;
49537      nxDiv++;
49538    }
49539  }
49540  assert( j==nCell );
49541  assert( nOld>0 );
49542  assert( nNew>0 );
49543  if( (pageFlags & PTF_LEAF)==0 ){
49544    u8 *zChild = &apCopy[nOld-1]->aData[8];
49545    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
49546  }
49547
49548  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
49549    /* The root page of the b-tree now contains no cells. The only sibling
49550    ** page is the right-child of the parent. Copy the contents of the
49551    ** child page into the parent, decreasing the overall height of the
49552    ** b-tree structure by one. This is described as the "balance-shallower"
49553    ** sub-algorithm in some documentation.
49554    **
49555    ** If this is an auto-vacuum database, the call to copyNodeContent()
49556    ** sets all pointer-map entries corresponding to database image pages
49557    ** for which the pointer is stored within the content being copied.
49558    **
49559    ** The second assert below verifies that the child page is defragmented
49560    ** (it must be, as it was just reconstructed using assemblePage()). This
49561    ** is important if the parent page happens to be page 1 of the database
49562    ** image.  */
49563    assert( nNew==1 );
49564    assert( apNew[0]->nFree ==
49565        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
49566    );
49567    copyNodeContent(apNew[0], pParent, &rc);
49568    freePage(apNew[0], &rc);
49569  }else if( ISAUTOVACUUM ){
49570    /* Fix the pointer-map entries for all the cells that were shifted around.
49571    ** There are several different types of pointer-map entries that need to
49572    ** be dealt with by this routine. Some of these have been set already, but
49573    ** many have not. The following is a summary:
49574    **
49575    **   1) The entries associated with new sibling pages that were not
49576    **      siblings when this function was called. These have already
49577    **      been set. We don't need to worry about old siblings that were
49578    **      moved to the free-list - the freePage() code has taken care
49579    **      of those.
49580    **
49581    **   2) The pointer-map entries associated with the first overflow
49582    **      page in any overflow chains used by new divider cells. These
49583    **      have also already been taken care of by the insertCell() code.
49584    **
49585    **   3) If the sibling pages are not leaves, then the child pages of
49586    **      cells stored on the sibling pages may need to be updated.
49587    **
49588    **   4) If the sibling pages are not internal intkey nodes, then any
49589    **      overflow pages used by these cells may need to be updated
49590    **      (internal intkey nodes never contain pointers to overflow pages).
49591    **
49592    **   5) If the sibling pages are not leaves, then the pointer-map
49593    **      entries for the right-child pages of each sibling may need
49594    **      to be updated.
49595    **
49596    ** Cases 1 and 2 are dealt with above by other code. The next
49597    ** block deals with cases 3 and 4 and the one after that, case 5. Since
49598    ** setting a pointer map entry is a relatively expensive operation, this
49599    ** code only sets pointer map entries for child or overflow pages that have
49600    ** actually moved between pages.  */
49601    MemPage *pNew = apNew[0];
49602    MemPage *pOld = apCopy[0];
49603    int nOverflow = pOld->nOverflow;
49604    int iNextOld = pOld->nCell + nOverflow;
49605    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
49606    j = 0;                             /* Current 'old' sibling page */
49607    k = 0;                             /* Current 'new' sibling page */
49608    for(i=0; i<nCell; i++){
49609      int isDivider = 0;
49610      while( i==iNextOld ){
49611        /* Cell i is the cell immediately following the last cell on old
49612        ** sibling page j. If the siblings are not leaf pages of an
49613        ** intkey b-tree, then cell i was a divider cell. */
49614        pOld = apCopy[++j];
49615        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
49616        if( pOld->nOverflow ){
49617          nOverflow = pOld->nOverflow;
49618          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
49619        }
49620        isDivider = !leafData;
49621      }
49622
49623      assert(nOverflow>0 || iOverflow<i );
49624      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
49625      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
49626      if( i==iOverflow ){
49627        isDivider = 1;
49628        if( (--nOverflow)>0 ){
49629          iOverflow++;
49630        }
49631      }
49632
49633      if( i==cntNew[k] ){
49634        /* Cell i is the cell immediately following the last cell on new
49635        ** sibling page k. If the siblings are not leaf pages of an
49636        ** intkey b-tree, then cell i is a divider cell.  */
49637        pNew = apNew[++k];
49638        if( !leafData ) continue;
49639      }
49640      assert( j<nOld );
49641      assert( k<nNew );
49642
49643      /* If the cell was originally divider cell (and is not now) or
49644      ** an overflow cell, or if the cell was located on a different sibling
49645      ** page before the balancing, then the pointer map entries associated
49646      ** with any child or overflow pages need to be updated.  */
49647      if( isDivider || pOld->pgno!=pNew->pgno ){
49648        if( !leafCorrection ){
49649          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
49650        }
49651        if( szCell[i]>pNew->minLocal ){
49652          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
49653        }
49654      }
49655    }
49656
49657    if( !leafCorrection ){
49658      for(i=0; i<nNew; i++){
49659        u32 key = get4byte(&apNew[i]->aData[8]);
49660        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
49661      }
49662    }
49663
49664#if 0
49665    /* The ptrmapCheckPages() contains assert() statements that verify that
49666    ** all pointer map pages are set correctly. This is helpful while
49667    ** debugging. This is usually disabled because a corrupt database may
49668    ** cause an assert() statement to fail.  */
49669    ptrmapCheckPages(apNew, nNew);
49670    ptrmapCheckPages(&pParent, 1);
49671#endif
49672  }
49673
49674  assert( pParent->isInit );
49675  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
49676          nOld, nNew, nCell));
49677
49678  /*
49679  ** Cleanup before returning.
49680  */
49681balance_cleanup:
49682  sqlite3ScratchFree(apCell);
49683  for(i=0; i<nOld; i++){
49684    releasePage(apOld[i]);
49685  }
49686  for(i=0; i<nNew; i++){
49687    releasePage(apNew[i]);
49688  }
49689
49690  return rc;
49691}
49692
49693
49694/*
49695** This function is called when the root page of a b-tree structure is
49696** overfull (has one or more overflow pages).
49697**
49698** A new child page is allocated and the contents of the current root
49699** page, including overflow cells, are copied into the child. The root
49700** page is then overwritten to make it an empty page with the right-child
49701** pointer pointing to the new page.
49702**
49703** Before returning, all pointer-map entries corresponding to pages
49704** that the new child-page now contains pointers to are updated. The
49705** entry corresponding to the new right-child pointer of the root
49706** page is also updated.
49707**
49708** If successful, *ppChild is set to contain a reference to the child
49709** page and SQLITE_OK is returned. In this case the caller is required
49710** to call releasePage() on *ppChild exactly once. If an error occurs,
49711** an error code is returned and *ppChild is set to 0.
49712*/
49713static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
49714  int rc;                        /* Return value from subprocedures */
49715  MemPage *pChild = 0;           /* Pointer to a new child page */
49716  Pgno pgnoChild = 0;            /* Page number of the new child page */
49717  BtShared *pBt = pRoot->pBt;    /* The BTree */
49718
49719  assert( pRoot->nOverflow>0 );
49720  assert( sqlite3_mutex_held(pBt->mutex) );
49721
49722  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
49723  ** page that will become the new right-child of pPage. Copy the contents
49724  ** of the node stored on pRoot into the new child page.
49725  */
49726  rc = sqlite3PagerWrite(pRoot->pDbPage);
49727  if( rc==SQLITE_OK ){
49728    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
49729    copyNodeContent(pRoot, pChild, &rc);
49730    if( ISAUTOVACUUM ){
49731      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
49732    }
49733  }
49734  if( rc ){
49735    *ppChild = 0;
49736    releasePage(pChild);
49737    return rc;
49738  }
49739  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
49740  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
49741  assert( pChild->nCell==pRoot->nCell );
49742
49743  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
49744
49745  /* Copy the overflow cells from pRoot to pChild */
49746  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
49747  pChild->nOverflow = pRoot->nOverflow;
49748
49749  /* Zero the contents of pRoot. Then install pChild as the right-child. */
49750  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
49751  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
49752
49753  *ppChild = pChild;
49754  return SQLITE_OK;
49755}
49756
49757/*
49758** The page that pCur currently points to has just been modified in
49759** some way. This function figures out if this modification means the
49760** tree needs to be balanced, and if so calls the appropriate balancing
49761** routine. Balancing routines are:
49762**
49763**   balance_quick()
49764**   balance_deeper()
49765**   balance_nonroot()
49766*/
49767static int balance(BtCursor *pCur){
49768  int rc = SQLITE_OK;
49769  const int nMin = pCur->pBt->usableSize * 2 / 3;
49770  u8 aBalanceQuickSpace[13];
49771  u8 *pFree = 0;
49772
49773  TESTONLY( int balance_quick_called = 0 );
49774  TESTONLY( int balance_deeper_called = 0 );
49775
49776  do {
49777    int iPage = pCur->iPage;
49778    MemPage *pPage = pCur->apPage[iPage];
49779
49780    if( iPage==0 ){
49781      if( pPage->nOverflow ){
49782        /* The root page of the b-tree is overfull. In this case call the
49783        ** balance_deeper() function to create a new child for the root-page
49784        ** and copy the current contents of the root-page to it. The
49785        ** next iteration of the do-loop will balance the child page.
49786        */
49787        assert( (balance_deeper_called++)==0 );
49788        rc = balance_deeper(pPage, &pCur->apPage[1]);
49789        if( rc==SQLITE_OK ){
49790          pCur->iPage = 1;
49791          pCur->aiIdx[0] = 0;
49792          pCur->aiIdx[1] = 0;
49793          assert( pCur->apPage[1]->nOverflow );
49794        }
49795      }else{
49796        break;
49797      }
49798    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
49799      break;
49800    }else{
49801      MemPage * const pParent = pCur->apPage[iPage-1];
49802      int const iIdx = pCur->aiIdx[iPage-1];
49803
49804      rc = sqlite3PagerWrite(pParent->pDbPage);
49805      if( rc==SQLITE_OK ){
49806#ifndef SQLITE_OMIT_QUICKBALANCE
49807        if( pPage->hasData
49808         && pPage->nOverflow==1
49809         && pPage->aOvfl[0].idx==pPage->nCell
49810         && pParent->pgno!=1
49811         && pParent->nCell==iIdx
49812        ){
49813          /* Call balance_quick() to create a new sibling of pPage on which
49814          ** to store the overflow cell. balance_quick() inserts a new cell
49815          ** into pParent, which may cause pParent overflow. If this
49816          ** happens, the next interation of the do-loop will balance pParent
49817          ** use either balance_nonroot() or balance_deeper(). Until this
49818          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
49819          ** buffer.
49820          **
49821          ** The purpose of the following assert() is to check that only a
49822          ** single call to balance_quick() is made for each call to this
49823          ** function. If this were not verified, a subtle bug involving reuse
49824          ** of the aBalanceQuickSpace[] might sneak in.
49825          */
49826          assert( (balance_quick_called++)==0 );
49827          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
49828        }else
49829#endif
49830        {
49831          /* In this case, call balance_nonroot() to redistribute cells
49832          ** between pPage and up to 2 of its sibling pages. This involves
49833          ** modifying the contents of pParent, which may cause pParent to
49834          ** become overfull or underfull. The next iteration of the do-loop
49835          ** will balance the parent page to correct this.
49836          **
49837          ** If the parent page becomes overfull, the overflow cell or cells
49838          ** are stored in the pSpace buffer allocated immediately below.
49839          ** A subsequent iteration of the do-loop will deal with this by
49840          ** calling balance_nonroot() (balance_deeper() may be called first,
49841          ** but it doesn't deal with overflow cells - just moves them to a
49842          ** different page). Once this subsequent call to balance_nonroot()
49843          ** has completed, it is safe to release the pSpace buffer used by
49844          ** the previous call, as the overflow cell data will have been
49845          ** copied either into the body of a database page or into the new
49846          ** pSpace buffer passed to the latter call to balance_nonroot().
49847          */
49848          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
49849          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
49850          if( pFree ){
49851            /* If pFree is not NULL, it points to the pSpace buffer used
49852            ** by a previous call to balance_nonroot(). Its contents are
49853            ** now stored either on real database pages or within the
49854            ** new pSpace buffer, so it may be safely freed here. */
49855            sqlite3PageFree(pFree);
49856          }
49857
49858          /* The pSpace buffer will be freed after the next call to
49859          ** balance_nonroot(), or just before this function returns, whichever
49860          ** comes first. */
49861          pFree = pSpace;
49862        }
49863      }
49864
49865      pPage->nOverflow = 0;
49866
49867      /* The next iteration of the do-loop balances the parent page. */
49868      releasePage(pPage);
49869      pCur->iPage--;
49870    }
49871  }while( rc==SQLITE_OK );
49872
49873  if( pFree ){
49874    sqlite3PageFree(pFree);
49875  }
49876  return rc;
49877}
49878
49879
49880/*
49881** Insert a new record into the BTree.  The key is given by (pKey,nKey)
49882** and the data is given by (pData,nData).  The cursor is used only to
49883** define what table the record should be inserted into.  The cursor
49884** is left pointing at a random location.
49885**
49886** For an INTKEY table, only the nKey value of the key is used.  pKey is
49887** ignored.  For a ZERODATA table, the pData and nData are both ignored.
49888**
49889** If the seekResult parameter is non-zero, then a successful call to
49890** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
49891** been performed. seekResult is the search result returned (a negative
49892** number if pCur points at an entry that is smaller than (pKey, nKey), or
49893** a positive value if pCur points at an etry that is larger than
49894** (pKey, nKey)).
49895**
49896** If the seekResult parameter is non-zero, then the caller guarantees that
49897** cursor pCur is pointing at the existing copy of a row that is to be
49898** overwritten.  If the seekResult parameter is 0, then cursor pCur may
49899** point to any entry or to no entry at all and so this function has to seek
49900** the cursor before the new key can be inserted.
49901*/
49902SQLITE_PRIVATE int sqlite3BtreeInsert(
49903  BtCursor *pCur,                /* Insert data into the table of this cursor */
49904  const void *pKey, i64 nKey,    /* The key of the new record */
49905  const void *pData, int nData,  /* The data of the new record */
49906  int nZero,                     /* Number of extra 0 bytes to append to data */
49907  int appendBias,                /* True if this is likely an append */
49908  int seekResult                 /* Result of prior MovetoUnpacked() call */
49909){
49910  int rc;
49911  int loc = seekResult;          /* -1: before desired location  +1: after */
49912  int szNew = 0;
49913  int idx;
49914  MemPage *pPage;
49915  Btree *p = pCur->pBtree;
49916  BtShared *pBt = p->pBt;
49917  unsigned char *oldCell;
49918  unsigned char *newCell = 0;
49919
49920  if( pCur->eState==CURSOR_FAULT ){
49921    assert( pCur->skipNext!=SQLITE_OK );
49922    return pCur->skipNext;
49923  }
49924
49925  assert( cursorHoldsMutex(pCur) );
49926  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
49927  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
49928
49929  /* Assert that the caller has been consistent. If this cursor was opened
49930  ** expecting an index b-tree, then the caller should be inserting blob
49931  ** keys with no associated data. If the cursor was opened expecting an
49932  ** intkey table, the caller should be inserting integer keys with a
49933  ** blob of associated data.  */
49934  assert( (pKey==0)==(pCur->pKeyInfo==0) );
49935
49936  /* If this is an insert into a table b-tree, invalidate any incrblob
49937  ** cursors open on the row being replaced (assuming this is a replace
49938  ** operation - if it is not, the following is a no-op).  */
49939  if( pCur->pKeyInfo==0 ){
49940    invalidateIncrblobCursors(p, nKey, 0);
49941  }
49942
49943  /* Save the positions of any other cursors open on this table.
49944  **
49945  ** In some cases, the call to btreeMoveto() below is a no-op. For
49946  ** example, when inserting data into a table with auto-generated integer
49947  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
49948  ** integer key to use. It then calls this function to actually insert the
49949  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
49950  ** that the cursor is already where it needs to be and returns without
49951  ** doing any work. To avoid thwarting these optimizations, it is important
49952  ** not to clear the cursor here.
49953  */
49954  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
49955  if( rc ) return rc;
49956  if( !loc ){
49957    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
49958    if( rc ) return rc;
49959  }
49960  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
49961
49962  pPage = pCur->apPage[pCur->iPage];
49963  assert( pPage->intKey || nKey>=0 );
49964  assert( pPage->leaf || !pPage->intKey );
49965
49966  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
49967          pCur->pgnoRoot, nKey, nData, pPage->pgno,
49968          loc==0 ? "overwrite" : "new entry"));
49969  assert( pPage->isInit );
49970  allocateTempSpace(pBt);
49971  newCell = pBt->pTmpSpace;
49972  if( newCell==0 ) return SQLITE_NOMEM;
49973  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
49974  if( rc ) goto end_insert;
49975  assert( szNew==cellSizePtr(pPage, newCell) );
49976  assert( szNew<=MX_CELL_SIZE(pBt) );
49977  idx = pCur->aiIdx[pCur->iPage];
49978  if( loc==0 ){
49979    u16 szOld;
49980    assert( idx<pPage->nCell );
49981    rc = sqlite3PagerWrite(pPage->pDbPage);
49982    if( rc ){
49983      goto end_insert;
49984    }
49985    oldCell = findCell(pPage, idx);
49986    if( !pPage->leaf ){
49987      memcpy(newCell, oldCell, 4);
49988    }
49989    szOld = cellSizePtr(pPage, oldCell);
49990    rc = clearCell(pPage, oldCell);
49991    dropCell(pPage, idx, szOld, &rc);
49992    if( rc ) goto end_insert;
49993  }else if( loc<0 && pPage->nCell>0 ){
49994    assert( pPage->leaf );
49995    idx = ++pCur->aiIdx[pCur->iPage];
49996  }else{
49997    assert( pPage->leaf );
49998  }
49999  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
50000  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
50001
50002  /* If no error has occured and pPage has an overflow cell, call balance()
50003  ** to redistribute the cells within the tree. Since balance() may move
50004  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
50005  ** variables.
50006  **
50007  ** Previous versions of SQLite called moveToRoot() to move the cursor
50008  ** back to the root page as balance() used to invalidate the contents
50009  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
50010  ** set the cursor state to "invalid". This makes common insert operations
50011  ** slightly faster.
50012  **
50013  ** There is a subtle but important optimization here too. When inserting
50014  ** multiple records into an intkey b-tree using a single cursor (as can
50015  ** happen while processing an "INSERT INTO ... SELECT" statement), it
50016  ** is advantageous to leave the cursor pointing to the last entry in
50017  ** the b-tree if possible. If the cursor is left pointing to the last
50018  ** entry in the table, and the next row inserted has an integer key
50019  ** larger than the largest existing key, it is possible to insert the
50020  ** row without seeking the cursor. This can be a big performance boost.
50021  */
50022  pCur->info.nSize = 0;
50023  pCur->validNKey = 0;
50024  if( rc==SQLITE_OK && pPage->nOverflow ){
50025    rc = balance(pCur);
50026
50027    /* Must make sure nOverflow is reset to zero even if the balance()
50028    ** fails. Internal data structure corruption will result otherwise.
50029    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
50030    ** from trying to save the current position of the cursor.  */
50031    pCur->apPage[pCur->iPage]->nOverflow = 0;
50032    pCur->eState = CURSOR_INVALID;
50033  }
50034  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
50035
50036end_insert:
50037  return rc;
50038}
50039
50040/*
50041** Delete the entry that the cursor is pointing to.  The cursor
50042** is left pointing at a arbitrary location.
50043*/
50044SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
50045  Btree *p = pCur->pBtree;
50046  BtShared *pBt = p->pBt;
50047  int rc;                              /* Return code */
50048  MemPage *pPage;                      /* Page to delete cell from */
50049  unsigned char *pCell;                /* Pointer to cell to delete */
50050  int iCellIdx;                        /* Index of cell to delete */
50051  int iCellDepth;                      /* Depth of node containing pCell */
50052
50053  assert( cursorHoldsMutex(pCur) );
50054  assert( pBt->inTransaction==TRANS_WRITE );
50055  assert( !pBt->readOnly );
50056  assert( pCur->wrFlag );
50057  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
50058  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
50059
50060  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
50061   || NEVER(pCur->eState!=CURSOR_VALID)
50062  ){
50063    return SQLITE_ERROR;  /* Something has gone awry. */
50064  }
50065
50066  /* If this is a delete operation to remove a row from a table b-tree,
50067  ** invalidate any incrblob cursors open on the row being deleted.  */
50068  if( pCur->pKeyInfo==0 ){
50069    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
50070  }
50071
50072  iCellDepth = pCur->iPage;
50073  iCellIdx = pCur->aiIdx[iCellDepth];
50074  pPage = pCur->apPage[iCellDepth];
50075  pCell = findCell(pPage, iCellIdx);
50076
50077  /* If the page containing the entry to delete is not a leaf page, move
50078  ** the cursor to the largest entry in the tree that is smaller than
50079  ** the entry being deleted. This cell will replace the cell being deleted
50080  ** from the internal node. The 'previous' entry is used for this instead
50081  ** of the 'next' entry, as the previous entry is always a part of the
50082  ** sub-tree headed by the child page of the cell being deleted. This makes
50083  ** balancing the tree following the delete operation easier.  */
50084  if( !pPage->leaf ){
50085    int notUsed;
50086    rc = sqlite3BtreePrevious(pCur, &notUsed);
50087    if( rc ) return rc;
50088  }
50089
50090  /* Save the positions of any other cursors open on this table before
50091  ** making any modifications. Make the page containing the entry to be
50092  ** deleted writable. Then free any overflow pages associated with the
50093  ** entry and finally remove the cell itself from within the page.
50094  */
50095  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
50096  if( rc ) return rc;
50097  rc = sqlite3PagerWrite(pPage->pDbPage);
50098  if( rc ) return rc;
50099  rc = clearCell(pPage, pCell);
50100  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
50101  if( rc ) return rc;
50102
50103  /* If the cell deleted was not located on a leaf page, then the cursor
50104  ** is currently pointing to the largest entry in the sub-tree headed
50105  ** by the child-page of the cell that was just deleted from an internal
50106  ** node. The cell from the leaf node needs to be moved to the internal
50107  ** node to replace the deleted cell.  */
50108  if( !pPage->leaf ){
50109    MemPage *pLeaf = pCur->apPage[pCur->iPage];
50110    int nCell;
50111    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
50112    unsigned char *pTmp;
50113
50114    pCell = findCell(pLeaf, pLeaf->nCell-1);
50115    nCell = cellSizePtr(pLeaf, pCell);
50116    assert( MX_CELL_SIZE(pBt)>=nCell );
50117
50118    allocateTempSpace(pBt);
50119    pTmp = pBt->pTmpSpace;
50120
50121    rc = sqlite3PagerWrite(pLeaf->pDbPage);
50122    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
50123    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
50124    if( rc ) return rc;
50125  }
50126
50127  /* Balance the tree. If the entry deleted was located on a leaf page,
50128  ** then the cursor still points to that page. In this case the first
50129  ** call to balance() repairs the tree, and the if(...) condition is
50130  ** never true.
50131  **
50132  ** Otherwise, if the entry deleted was on an internal node page, then
50133  ** pCur is pointing to the leaf page from which a cell was removed to
50134  ** replace the cell deleted from the internal node. This is slightly
50135  ** tricky as the leaf node may be underfull, and the internal node may
50136  ** be either under or overfull. In this case run the balancing algorithm
50137  ** on the leaf node first. If the balance proceeds far enough up the
50138  ** tree that we can be sure that any problem in the internal node has
50139  ** been corrected, so be it. Otherwise, after balancing the leaf node,
50140  ** walk the cursor up the tree to the internal node and balance it as
50141  ** well.  */
50142  rc = balance(pCur);
50143  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
50144    while( pCur->iPage>iCellDepth ){
50145      releasePage(pCur->apPage[pCur->iPage--]);
50146    }
50147    rc = balance(pCur);
50148  }
50149
50150  if( rc==SQLITE_OK ){
50151    moveToRoot(pCur);
50152  }
50153  return rc;
50154}
50155
50156/*
50157** Create a new BTree table.  Write into *piTable the page
50158** number for the root page of the new table.
50159**
50160** The type of type is determined by the flags parameter.  Only the
50161** following values of flags are currently in use.  Other values for
50162** flags might not work:
50163**
50164**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
50165**     BTREE_ZERODATA                  Used for SQL indices
50166*/
50167static int btreeCreateTable(Btree *p, int *piTable, int flags){
50168  BtShared *pBt = p->pBt;
50169  MemPage *pRoot;
50170  Pgno pgnoRoot;
50171  int rc;
50172
50173  assert( sqlite3BtreeHoldsMutex(p) );
50174  assert( pBt->inTransaction==TRANS_WRITE );
50175  assert( !pBt->readOnly );
50176
50177#ifdef SQLITE_OMIT_AUTOVACUUM
50178  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50179  if( rc ){
50180    return rc;
50181  }
50182#else
50183  if( pBt->autoVacuum ){
50184    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
50185    MemPage *pPageMove; /* The page to move to. */
50186
50187    /* Creating a new table may probably require moving an existing database
50188    ** to make room for the new tables root page. In case this page turns
50189    ** out to be an overflow page, delete all overflow page-map caches
50190    ** held by open cursors.
50191    */
50192    invalidateAllOverflowCache(pBt);
50193
50194    /* Read the value of meta[3] from the database to determine where the
50195    ** root page of the new table should go. meta[3] is the largest root-page
50196    ** created so far, so the new root-page is (meta[3]+1).
50197    */
50198    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
50199    pgnoRoot++;
50200
50201    /* The new root-page may not be allocated on a pointer-map page, or the
50202    ** PENDING_BYTE page.
50203    */
50204    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
50205        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
50206      pgnoRoot++;
50207    }
50208    assert( pgnoRoot>=3 );
50209
50210    /* Allocate a page. The page that currently resides at pgnoRoot will
50211    ** be moved to the allocated page (unless the allocated page happens
50212    ** to reside at pgnoRoot).
50213    */
50214    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
50215    if( rc!=SQLITE_OK ){
50216      return rc;
50217    }
50218
50219    if( pgnoMove!=pgnoRoot ){
50220      /* pgnoRoot is the page that will be used for the root-page of
50221      ** the new table (assuming an error did not occur). But we were
50222      ** allocated pgnoMove. If required (i.e. if it was not allocated
50223      ** by extending the file), the current page at position pgnoMove
50224      ** is already journaled.
50225      */
50226      u8 eType = 0;
50227      Pgno iPtrPage = 0;
50228
50229      releasePage(pPageMove);
50230
50231      /* Move the page currently at pgnoRoot to pgnoMove. */
50232      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50233      if( rc!=SQLITE_OK ){
50234        return rc;
50235      }
50236      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
50237      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
50238        rc = SQLITE_CORRUPT_BKPT;
50239      }
50240      if( rc!=SQLITE_OK ){
50241        releasePage(pRoot);
50242        return rc;
50243      }
50244      assert( eType!=PTRMAP_ROOTPAGE );
50245      assert( eType!=PTRMAP_FREEPAGE );
50246      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
50247      releasePage(pRoot);
50248
50249      /* Obtain the page at pgnoRoot */
50250      if( rc!=SQLITE_OK ){
50251        return rc;
50252      }
50253      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50254      if( rc!=SQLITE_OK ){
50255        return rc;
50256      }
50257      rc = sqlite3PagerWrite(pRoot->pDbPage);
50258      if( rc!=SQLITE_OK ){
50259        releasePage(pRoot);
50260        return rc;
50261      }
50262    }else{
50263      pRoot = pPageMove;
50264    }
50265
50266    /* Update the pointer-map and meta-data with the new root-page number. */
50267    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
50268    if( rc ){
50269      releasePage(pRoot);
50270      return rc;
50271    }
50272
50273    /* When the new root page was allocated, page 1 was made writable in
50274    ** order either to increase the database filesize, or to decrement the
50275    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
50276    */
50277    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
50278    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
50279    if( NEVER(rc) ){
50280      releasePage(pRoot);
50281      return rc;
50282    }
50283
50284  }else{
50285    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50286    if( rc ) return rc;
50287  }
50288#endif
50289  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50290  zeroPage(pRoot, flags | PTF_LEAF);
50291  sqlite3PagerUnref(pRoot->pDbPage);
50292  *piTable = (int)pgnoRoot;
50293  return SQLITE_OK;
50294}
50295SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
50296  int rc;
50297  sqlite3BtreeEnter(p);
50298  rc = btreeCreateTable(p, piTable, flags);
50299  sqlite3BtreeLeave(p);
50300  return rc;
50301}
50302
50303/*
50304** Erase the given database page and all its children.  Return
50305** the page to the freelist.
50306*/
50307static int clearDatabasePage(
50308  BtShared *pBt,           /* The BTree that contains the table */
50309  Pgno pgno,               /* Page number to clear */
50310  int freePageFlag,        /* Deallocate page if true */
50311  int *pnChange            /* Add number of Cells freed to this counter */
50312){
50313  MemPage *pPage;
50314  int rc;
50315  unsigned char *pCell;
50316  int i;
50317
50318  assert( sqlite3_mutex_held(pBt->mutex) );
50319  if( pgno>btreePagecount(pBt) ){
50320    return SQLITE_CORRUPT_BKPT;
50321  }
50322
50323  rc = getAndInitPage(pBt, pgno, &pPage);
50324  if( rc ) return rc;
50325  for(i=0; i<pPage->nCell; i++){
50326    pCell = findCell(pPage, i);
50327    if( !pPage->leaf ){
50328      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
50329      if( rc ) goto cleardatabasepage_out;
50330    }
50331    rc = clearCell(pPage, pCell);
50332    if( rc ) goto cleardatabasepage_out;
50333  }
50334  if( !pPage->leaf ){
50335    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
50336    if( rc ) goto cleardatabasepage_out;
50337  }else if( pnChange ){
50338    assert( pPage->intKey );
50339    *pnChange += pPage->nCell;
50340  }
50341  if( freePageFlag ){
50342    freePage(pPage, &rc);
50343  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
50344    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
50345  }
50346
50347cleardatabasepage_out:
50348  releasePage(pPage);
50349  return rc;
50350}
50351
50352/*
50353** Delete all information from a single table in the database.  iTable is
50354** the page number of the root of the table.  After this routine returns,
50355** the root page is empty, but still exists.
50356**
50357** This routine will fail with SQLITE_LOCKED if there are any open
50358** read cursors on the table.  Open write cursors are moved to the
50359** root of the table.
50360**
50361** If pnChange is not NULL, then table iTable must be an intkey table. The
50362** integer value pointed to by pnChange is incremented by the number of
50363** entries in the table.
50364*/
50365SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
50366  int rc;
50367  BtShared *pBt = p->pBt;
50368  sqlite3BtreeEnter(p);
50369  assert( p->inTrans==TRANS_WRITE );
50370
50371  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
50372  ** is the root of a table b-tree - if it is not, the following call is
50373  ** a no-op).  */
50374  invalidateIncrblobCursors(p, 0, 1);
50375
50376  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
50377  if( SQLITE_OK==rc ){
50378    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
50379  }
50380  sqlite3BtreeLeave(p);
50381  return rc;
50382}
50383
50384/*
50385** Erase all information in a table and add the root of the table to
50386** the freelist.  Except, the root of the principle table (the one on
50387** page 1) is never added to the freelist.
50388**
50389** This routine will fail with SQLITE_LOCKED if there are any open
50390** cursors on the table.
50391**
50392** If AUTOVACUUM is enabled and the page at iTable is not the last
50393** root page in the database file, then the last root page
50394** in the database file is moved into the slot formerly occupied by
50395** iTable and that last slot formerly occupied by the last root page
50396** is added to the freelist instead of iTable.  In this say, all
50397** root pages are kept at the beginning of the database file, which
50398** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
50399** page number that used to be the last root page in the file before
50400** the move.  If no page gets moved, *piMoved is set to 0.
50401** The last root page is recorded in meta[3] and the value of
50402** meta[3] is updated by this procedure.
50403*/
50404static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
50405  int rc;
50406  MemPage *pPage = 0;
50407  BtShared *pBt = p->pBt;
50408
50409  assert( sqlite3BtreeHoldsMutex(p) );
50410  assert( p->inTrans==TRANS_WRITE );
50411
50412  /* It is illegal to drop a table if any cursors are open on the
50413  ** database. This is because in auto-vacuum mode the backend may
50414  ** need to move another root-page to fill a gap left by the deleted
50415  ** root page. If an open cursor was using this page a problem would
50416  ** occur.
50417  **
50418  ** This error is caught long before control reaches this point.
50419  */
50420  if( NEVER(pBt->pCursor) ){
50421    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
50422    return SQLITE_LOCKED_SHAREDCACHE;
50423  }
50424
50425  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
50426  if( rc ) return rc;
50427  rc = sqlite3BtreeClearTable(p, iTable, 0);
50428  if( rc ){
50429    releasePage(pPage);
50430    return rc;
50431  }
50432
50433  *piMoved = 0;
50434
50435  if( iTable>1 ){
50436#ifdef SQLITE_OMIT_AUTOVACUUM
50437    freePage(pPage, &rc);
50438    releasePage(pPage);
50439#else
50440    if( pBt->autoVacuum ){
50441      Pgno maxRootPgno;
50442      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
50443
50444      if( iTable==maxRootPgno ){
50445        /* If the table being dropped is the table with the largest root-page
50446        ** number in the database, put the root page on the free list.
50447        */
50448        freePage(pPage, &rc);
50449        releasePage(pPage);
50450        if( rc!=SQLITE_OK ){
50451          return rc;
50452        }
50453      }else{
50454        /* The table being dropped does not have the largest root-page
50455        ** number in the database. So move the page that does into the
50456        ** gap left by the deleted root-page.
50457        */
50458        MemPage *pMove;
50459        releasePage(pPage);
50460        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50461        if( rc!=SQLITE_OK ){
50462          return rc;
50463        }
50464        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
50465        releasePage(pMove);
50466        if( rc!=SQLITE_OK ){
50467          return rc;
50468        }
50469        pMove = 0;
50470        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50471        freePage(pMove, &rc);
50472        releasePage(pMove);
50473        if( rc!=SQLITE_OK ){
50474          return rc;
50475        }
50476        *piMoved = maxRootPgno;
50477      }
50478
50479      /* Set the new 'max-root-page' value in the database header. This
50480      ** is the old value less one, less one more if that happens to
50481      ** be a root-page number, less one again if that is the
50482      ** PENDING_BYTE_PAGE.
50483      */
50484      maxRootPgno--;
50485      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
50486             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
50487        maxRootPgno--;
50488      }
50489      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
50490
50491      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
50492    }else{
50493      freePage(pPage, &rc);
50494      releasePage(pPage);
50495    }
50496#endif
50497  }else{
50498    /* If sqlite3BtreeDropTable was called on page 1.
50499    ** This really never should happen except in a corrupt
50500    ** database.
50501    */
50502    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
50503    releasePage(pPage);
50504  }
50505  return rc;
50506}
50507SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
50508  int rc;
50509  sqlite3BtreeEnter(p);
50510  rc = btreeDropTable(p, iTable, piMoved);
50511  sqlite3BtreeLeave(p);
50512  return rc;
50513}
50514
50515
50516/*
50517** This function may only be called if the b-tree connection already
50518** has a read or write transaction open on the database.
50519**
50520** Read the meta-information out of a database file.  Meta[0]
50521** is the number of free pages currently in the database.  Meta[1]
50522** through meta[15] are available for use by higher layers.  Meta[0]
50523** is read-only, the others are read/write.
50524**
50525** The schema layer numbers meta values differently.  At the schema
50526** layer (and the SetCookie and ReadCookie opcodes) the number of
50527** free pages is not visible.  So Cookie[0] is the same as Meta[1].
50528*/
50529SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
50530  BtShared *pBt = p->pBt;
50531
50532  sqlite3BtreeEnter(p);
50533  assert( p->inTrans>TRANS_NONE );
50534  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
50535  assert( pBt->pPage1 );
50536  assert( idx>=0 && idx<=15 );
50537
50538  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
50539
50540  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
50541  ** database, mark the database as read-only.  */
50542#ifdef SQLITE_OMIT_AUTOVACUUM
50543  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
50544#endif
50545
50546  sqlite3BtreeLeave(p);
50547}
50548
50549/*
50550** Write meta-information back into the database.  Meta[0] is
50551** read-only and may not be written.
50552*/
50553SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
50554  BtShared *pBt = p->pBt;
50555  unsigned char *pP1;
50556  int rc;
50557  assert( idx>=1 && idx<=15 );
50558  sqlite3BtreeEnter(p);
50559  assert( p->inTrans==TRANS_WRITE );
50560  assert( pBt->pPage1!=0 );
50561  pP1 = pBt->pPage1->aData;
50562  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50563  if( rc==SQLITE_OK ){
50564    put4byte(&pP1[36 + idx*4], iMeta);
50565#ifndef SQLITE_OMIT_AUTOVACUUM
50566    if( idx==BTREE_INCR_VACUUM ){
50567      assert( pBt->autoVacuum || iMeta==0 );
50568      assert( iMeta==0 || iMeta==1 );
50569      pBt->incrVacuum = (u8)iMeta;
50570    }
50571#endif
50572  }
50573  sqlite3BtreeLeave(p);
50574  return rc;
50575}
50576
50577#ifndef SQLITE_OMIT_BTREECOUNT
50578/*
50579** The first argument, pCur, is a cursor opened on some b-tree. Count the
50580** number of entries in the b-tree and write the result to *pnEntry.
50581**
50582** SQLITE_OK is returned if the operation is successfully executed.
50583** Otherwise, if an error is encountered (i.e. an IO error or database
50584** corruption) an SQLite error code is returned.
50585*/
50586SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
50587  i64 nEntry = 0;                      /* Value to return in *pnEntry */
50588  int rc;                              /* Return code */
50589  rc = moveToRoot(pCur);
50590
50591  /* Unless an error occurs, the following loop runs one iteration for each
50592  ** page in the B-Tree structure (not including overflow pages).
50593  */
50594  while( rc==SQLITE_OK ){
50595    int iIdx;                          /* Index of child node in parent */
50596    MemPage *pPage;                    /* Current page of the b-tree */
50597
50598    /* If this is a leaf page or the tree is not an int-key tree, then
50599    ** this page contains countable entries. Increment the entry counter
50600    ** accordingly.
50601    */
50602    pPage = pCur->apPage[pCur->iPage];
50603    if( pPage->leaf || !pPage->intKey ){
50604      nEntry += pPage->nCell;
50605    }
50606
50607    /* pPage is a leaf node. This loop navigates the cursor so that it
50608    ** points to the first interior cell that it points to the parent of
50609    ** the next page in the tree that has not yet been visited. The
50610    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
50611    ** of the page, or to the number of cells in the page if the next page
50612    ** to visit is the right-child of its parent.
50613    **
50614    ** If all pages in the tree have been visited, return SQLITE_OK to the
50615    ** caller.
50616    */
50617    if( pPage->leaf ){
50618      do {
50619        if( pCur->iPage==0 ){
50620          /* All pages of the b-tree have been visited. Return successfully. */
50621          *pnEntry = nEntry;
50622          return SQLITE_OK;
50623        }
50624        moveToParent(pCur);
50625      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
50626
50627      pCur->aiIdx[pCur->iPage]++;
50628      pPage = pCur->apPage[pCur->iPage];
50629    }
50630
50631    /* Descend to the child node of the cell that the cursor currently
50632    ** points at. This is the right-child if (iIdx==pPage->nCell).
50633    */
50634    iIdx = pCur->aiIdx[pCur->iPage];
50635    if( iIdx==pPage->nCell ){
50636      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
50637    }else{
50638      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
50639    }
50640  }
50641
50642  /* An error has occurred. Return an error code. */
50643  return rc;
50644}
50645#endif
50646
50647/*
50648** Return the pager associated with a BTree.  This routine is used for
50649** testing and debugging only.
50650*/
50651SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
50652  return p->pBt->pPager;
50653}
50654
50655#ifndef SQLITE_OMIT_INTEGRITY_CHECK
50656/*
50657** Append a message to the error message string.
50658*/
50659static void checkAppendMsg(
50660  IntegrityCk *pCheck,
50661  char *zMsg1,
50662  const char *zFormat,
50663  ...
50664){
50665  va_list ap;
50666  if( !pCheck->mxErr ) return;
50667  pCheck->mxErr--;
50668  pCheck->nErr++;
50669  va_start(ap, zFormat);
50670  if( pCheck->errMsg.nChar ){
50671    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
50672  }
50673  if( zMsg1 ){
50674    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
50675  }
50676  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
50677  va_end(ap);
50678  if( pCheck->errMsg.mallocFailed ){
50679    pCheck->mallocFailed = 1;
50680  }
50681}
50682#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
50683
50684#ifndef SQLITE_OMIT_INTEGRITY_CHECK
50685/*
50686** Add 1 to the reference count for page iPage.  If this is the second
50687** reference to the page, add an error message to pCheck->zErrMsg.
50688** Return 1 if there are 2 ore more references to the page and 0 if
50689** if this is the first reference to the page.
50690**
50691** Also check that the page number is in bounds.
50692*/
50693static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
50694  if( iPage==0 ) return 1;
50695  if( iPage>pCheck->nPage ){
50696    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
50697    return 1;
50698  }
50699  if( pCheck->anRef[iPage]==1 ){
50700    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
50701    return 1;
50702  }
50703  return  (pCheck->anRef[iPage]++)>1;
50704}
50705
50706#ifndef SQLITE_OMIT_AUTOVACUUM
50707/*
50708** Check that the entry in the pointer-map for page iChild maps to
50709** page iParent, pointer type ptrType. If not, append an error message
50710** to pCheck.
50711*/
50712static void checkPtrmap(
50713  IntegrityCk *pCheck,   /* Integrity check context */
50714  Pgno iChild,           /* Child page number */
50715  u8 eType,              /* Expected pointer map type */
50716  Pgno iParent,          /* Expected pointer map parent page number */
50717  char *zContext         /* Context description (used for error msg) */
50718){
50719  int rc;
50720  u8 ePtrmapType;
50721  Pgno iPtrmapParent;
50722
50723  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
50724  if( rc!=SQLITE_OK ){
50725    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
50726    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
50727    return;
50728  }
50729
50730  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
50731    checkAppendMsg(pCheck, zContext,
50732      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
50733      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
50734  }
50735}
50736#endif
50737
50738/*
50739** Check the integrity of the freelist or of an overflow page list.
50740** Verify that the number of pages on the list is N.
50741*/
50742static void checkList(
50743  IntegrityCk *pCheck,  /* Integrity checking context */
50744  int isFreeList,       /* True for a freelist.  False for overflow page list */
50745  int iPage,            /* Page number for first page in the list */
50746  int N,                /* Expected number of pages in the list */
50747  char *zContext        /* Context for error messages */
50748){
50749  int i;
50750  int expected = N;
50751  int iFirst = iPage;
50752  while( N-- > 0 && pCheck->mxErr ){
50753    DbPage *pOvflPage;
50754    unsigned char *pOvflData;
50755    if( iPage<1 ){
50756      checkAppendMsg(pCheck, zContext,
50757         "%d of %d pages missing from overflow list starting at %d",
50758          N+1, expected, iFirst);
50759      break;
50760    }
50761    if( checkRef(pCheck, iPage, zContext) ) break;
50762    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
50763      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
50764      break;
50765    }
50766    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
50767    if( isFreeList ){
50768      int n = get4byte(&pOvflData[4]);
50769#ifndef SQLITE_OMIT_AUTOVACUUM
50770      if( pCheck->pBt->autoVacuum ){
50771        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
50772      }
50773#endif
50774      if( n>pCheck->pBt->usableSize/4-2 ){
50775        checkAppendMsg(pCheck, zContext,
50776           "freelist leaf count too big on page %d", iPage);
50777        N--;
50778      }else{
50779        for(i=0; i<n; i++){
50780          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
50781#ifndef SQLITE_OMIT_AUTOVACUUM
50782          if( pCheck->pBt->autoVacuum ){
50783            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
50784          }
50785#endif
50786          checkRef(pCheck, iFreePage, zContext);
50787        }
50788        N -= n;
50789      }
50790    }
50791#ifndef SQLITE_OMIT_AUTOVACUUM
50792    else{
50793      /* If this database supports auto-vacuum and iPage is not the last
50794      ** page in this overflow list, check that the pointer-map entry for
50795      ** the following page matches iPage.
50796      */
50797      if( pCheck->pBt->autoVacuum && N>0 ){
50798        i = get4byte(pOvflData);
50799        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
50800      }
50801    }
50802#endif
50803    iPage = get4byte(pOvflData);
50804    sqlite3PagerUnref(pOvflPage);
50805  }
50806}
50807#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
50808
50809#ifndef SQLITE_OMIT_INTEGRITY_CHECK
50810/*
50811** Do various sanity checks on a single page of a tree.  Return
50812** the tree depth.  Root pages return 0.  Parents of root pages
50813** return 1, and so forth.
50814**
50815** These checks are done:
50816**
50817**      1.  Make sure that cells and freeblocks do not overlap
50818**          but combine to completely cover the page.
50819**  NO  2.  Make sure cell keys are in order.
50820**  NO  3.  Make sure no key is less than or equal to zLowerBound.
50821**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
50822**      5.  Check the integrity of overflow pages.
50823**      6.  Recursively call checkTreePage on all children.
50824**      7.  Verify that the depth of all children is the same.
50825**      8.  Make sure this page is at least 33% full or else it is
50826**          the root of the tree.
50827*/
50828static int checkTreePage(
50829  IntegrityCk *pCheck,  /* Context for the sanity check */
50830  int iPage,            /* Page number of the page to check */
50831  char *zParentContext, /* Parent context */
50832  i64 *pnParentMinKey,
50833  i64 *pnParentMaxKey
50834){
50835  MemPage *pPage;
50836  int i, rc, depth, d2, pgno, cnt;
50837  int hdr, cellStart;
50838  int nCell;
50839  u8 *data;
50840  BtShared *pBt;
50841  int usableSize;
50842  char zContext[100];
50843  char *hit = 0;
50844  i64 nMinKey = 0;
50845  i64 nMaxKey = 0;
50846
50847  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
50848
50849  /* Check that the page exists
50850  */
50851  pBt = pCheck->pBt;
50852  usableSize = pBt->usableSize;
50853  if( iPage==0 ) return 0;
50854  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
50855  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
50856    checkAppendMsg(pCheck, zContext,
50857       "unable to get the page. error code=%d", rc);
50858    return 0;
50859  }
50860
50861  /* Clear MemPage.isInit to make sure the corruption detection code in
50862  ** btreeInitPage() is executed.  */
50863  pPage->isInit = 0;
50864  if( (rc = btreeInitPage(pPage))!=0 ){
50865    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
50866    checkAppendMsg(pCheck, zContext,
50867                   "btreeInitPage() returns error code %d", rc);
50868    releasePage(pPage);
50869    return 0;
50870  }
50871
50872  /* Check out all the cells.
50873  */
50874  depth = 0;
50875  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
50876    u8 *pCell;
50877    u32 sz;
50878    CellInfo info;
50879
50880    /* Check payload overflow pages
50881    */
50882    sqlite3_snprintf(sizeof(zContext), zContext,
50883             "On tree page %d cell %d: ", iPage, i);
50884    pCell = findCell(pPage,i);
50885    btreeParseCellPtr(pPage, pCell, &info);
50886    sz = info.nData;
50887    if( !pPage->intKey ) sz += (int)info.nKey;
50888    /* For intKey pages, check that the keys are in order.
50889    */
50890    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
50891    else{
50892      if( info.nKey <= nMaxKey ){
50893        checkAppendMsg(pCheck, zContext,
50894            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
50895      }
50896      nMaxKey = info.nKey;
50897    }
50898    assert( sz==info.nPayload );
50899    if( (sz>info.nLocal)
50900     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
50901    ){
50902      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
50903      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
50904#ifndef SQLITE_OMIT_AUTOVACUUM
50905      if( pBt->autoVacuum ){
50906        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
50907      }
50908#endif
50909      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
50910    }
50911
50912    /* Check sanity of left child page.
50913    */
50914    if( !pPage->leaf ){
50915      pgno = get4byte(pCell);
50916#ifndef SQLITE_OMIT_AUTOVACUUM
50917      if( pBt->autoVacuum ){
50918        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
50919      }
50920#endif
50921      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
50922      if( i>0 && d2!=depth ){
50923        checkAppendMsg(pCheck, zContext, "Child page depth differs");
50924      }
50925      depth = d2;
50926    }
50927  }
50928
50929  if( !pPage->leaf ){
50930    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50931    sqlite3_snprintf(sizeof(zContext), zContext,
50932                     "On page %d at right child: ", iPage);
50933#ifndef SQLITE_OMIT_AUTOVACUUM
50934    if( pBt->autoVacuum ){
50935      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
50936    }
50937#endif
50938    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
50939  }
50940
50941  /* For intKey leaf pages, check that the min/max keys are in order
50942  ** with any left/parent/right pages.
50943  */
50944  if( pPage->leaf && pPage->intKey ){
50945    /* if we are a left child page */
50946    if( pnParentMinKey ){
50947      /* if we are the left most child page */
50948      if( !pnParentMaxKey ){
50949        if( nMaxKey > *pnParentMinKey ){
50950          checkAppendMsg(pCheck, zContext,
50951              "Rowid %lld out of order (max larger than parent min of %lld)",
50952              nMaxKey, *pnParentMinKey);
50953        }
50954      }else{
50955        if( nMinKey <= *pnParentMinKey ){
50956          checkAppendMsg(pCheck, zContext,
50957              "Rowid %lld out of order (min less than parent min of %lld)",
50958              nMinKey, *pnParentMinKey);
50959        }
50960        if( nMaxKey > *pnParentMaxKey ){
50961          checkAppendMsg(pCheck, zContext,
50962              "Rowid %lld out of order (max larger than parent max of %lld)",
50963              nMaxKey, *pnParentMaxKey);
50964        }
50965        *pnParentMinKey = nMaxKey;
50966      }
50967    /* else if we're a right child page */
50968    } else if( pnParentMaxKey ){
50969      if( nMinKey <= *pnParentMaxKey ){
50970        checkAppendMsg(pCheck, zContext,
50971            "Rowid %lld out of order (min less than parent max of %lld)",
50972            nMinKey, *pnParentMaxKey);
50973      }
50974    }
50975  }
50976
50977  /* Check for complete coverage of the page
50978  */
50979  data = pPage->aData;
50980  hdr = pPage->hdrOffset;
50981  hit = sqlite3PageMalloc( pBt->pageSize );
50982  if( hit==0 ){
50983    pCheck->mallocFailed = 1;
50984  }else{
50985    u16 contentOffset = get2byte(&data[hdr+5]);
50986    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
50987    memset(hit+contentOffset, 0, usableSize-contentOffset);
50988    memset(hit, 1, contentOffset);
50989    nCell = get2byte(&data[hdr+3]);
50990    cellStart = hdr + 12 - 4*pPage->leaf;
50991    for(i=0; i<nCell; i++){
50992      int pc = get2byte(&data[cellStart+i*2]);
50993      u16 size = 1024;
50994      int j;
50995      if( pc<=usableSize-4 ){
50996        size = cellSizePtr(pPage, &data[pc]);
50997      }
50998      if( (pc+size-1)>=usableSize ){
50999        checkAppendMsg(pCheck, 0,
51000            "Corruption detected in cell %d on page %d",i,iPage);
51001      }else{
51002        for(j=pc+size-1; j>=pc; j--) hit[j]++;
51003      }
51004    }
51005    i = get2byte(&data[hdr+1]);
51006    while( i>0 ){
51007      int size, j;
51008      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
51009      size = get2byte(&data[i+2]);
51010      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
51011      for(j=i+size-1; j>=i; j--) hit[j]++;
51012      j = get2byte(&data[i]);
51013      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
51014      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
51015      i = j;
51016    }
51017    for(i=cnt=0; i<usableSize; i++){
51018      if( hit[i]==0 ){
51019        cnt++;
51020      }else if( hit[i]>1 ){
51021        checkAppendMsg(pCheck, 0,
51022          "Multiple uses for byte %d of page %d", i, iPage);
51023        break;
51024      }
51025    }
51026    if( cnt!=data[hdr+7] ){
51027      checkAppendMsg(pCheck, 0,
51028          "Fragmentation of %d bytes reported as %d on page %d",
51029          cnt, data[hdr+7], iPage);
51030    }
51031  }
51032  sqlite3PageFree(hit);
51033  releasePage(pPage);
51034  return depth+1;
51035}
51036#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51037
51038#ifndef SQLITE_OMIT_INTEGRITY_CHECK
51039/*
51040** This routine does a complete check of the given BTree file.  aRoot[] is
51041** an array of pages numbers were each page number is the root page of
51042** a table.  nRoot is the number of entries in aRoot.
51043**
51044** A read-only or read-write transaction must be opened before calling
51045** this function.
51046**
51047** Write the number of error seen in *pnErr.  Except for some memory
51048** allocation errors,  an error message held in memory obtained from
51049** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
51050** returned.  If a memory allocation error occurs, NULL is returned.
51051*/
51052SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
51053  Btree *p,     /* The btree to be checked */
51054  int *aRoot,   /* An array of root pages numbers for individual trees */
51055  int nRoot,    /* Number of entries in aRoot[] */
51056  int mxErr,    /* Stop reporting errors after this many */
51057  int *pnErr    /* Write number of errors seen to this variable */
51058){
51059  Pgno i;
51060  int nRef;
51061  IntegrityCk sCheck;
51062  BtShared *pBt = p->pBt;
51063  char zErr[100];
51064
51065  sqlite3BtreeEnter(p);
51066  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
51067  nRef = sqlite3PagerRefcount(pBt->pPager);
51068  sCheck.pBt = pBt;
51069  sCheck.pPager = pBt->pPager;
51070  sCheck.nPage = btreePagecount(sCheck.pBt);
51071  sCheck.mxErr = mxErr;
51072  sCheck.nErr = 0;
51073  sCheck.mallocFailed = 0;
51074  *pnErr = 0;
51075  if( sCheck.nPage==0 ){
51076    sqlite3BtreeLeave(p);
51077    return 0;
51078  }
51079  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
51080  if( !sCheck.anRef ){
51081    *pnErr = 1;
51082    sqlite3BtreeLeave(p);
51083    return 0;
51084  }
51085  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
51086  i = PENDING_BYTE_PAGE(pBt);
51087  if( i<=sCheck.nPage ){
51088    sCheck.anRef[i] = 1;
51089  }
51090  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
51091
51092  /* Check the integrity of the freelist
51093  */
51094  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
51095            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
51096
51097  /* Check all the tables.
51098  */
51099  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
51100    if( aRoot[i]==0 ) continue;
51101#ifndef SQLITE_OMIT_AUTOVACUUM
51102    if( pBt->autoVacuum && aRoot[i]>1 ){
51103      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
51104    }
51105#endif
51106    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
51107  }
51108
51109  /* Make sure every page in the file is referenced
51110  */
51111  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
51112#ifdef SQLITE_OMIT_AUTOVACUUM
51113    if( sCheck.anRef[i]==0 ){
51114      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51115    }
51116#else
51117    /* If the database supports auto-vacuum, make sure no tables contain
51118    ** references to pointer-map pages.
51119    */
51120    if( sCheck.anRef[i]==0 &&
51121       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
51122      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51123    }
51124    if( sCheck.anRef[i]!=0 &&
51125       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
51126      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
51127    }
51128#endif
51129  }
51130
51131  /* Make sure this analysis did not leave any unref() pages.
51132  ** This is an internal consistency check; an integrity check
51133  ** of the integrity check.
51134  */
51135  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
51136    checkAppendMsg(&sCheck, 0,
51137      "Outstanding page count goes from %d to %d during this analysis",
51138      nRef, sqlite3PagerRefcount(pBt->pPager)
51139    );
51140  }
51141
51142  /* Clean  up and report errors.
51143  */
51144  sqlite3BtreeLeave(p);
51145  sqlite3_free(sCheck.anRef);
51146  if( sCheck.mallocFailed ){
51147    sqlite3StrAccumReset(&sCheck.errMsg);
51148    *pnErr = sCheck.nErr+1;
51149    return 0;
51150  }
51151  *pnErr = sCheck.nErr;
51152  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
51153  return sqlite3StrAccumFinish(&sCheck.errMsg);
51154}
51155#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51156
51157/*
51158** Return the full pathname of the underlying database file.
51159**
51160** The pager filename is invariant as long as the pager is
51161** open so it is safe to access without the BtShared mutex.
51162*/
51163SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
51164  assert( p->pBt->pPager!=0 );
51165  return sqlite3PagerFilename(p->pBt->pPager);
51166}
51167
51168/*
51169** Return the pathname of the journal file for this database. The return
51170** value of this routine is the same regardless of whether the journal file
51171** has been created or not.
51172**
51173** The pager journal filename is invariant as long as the pager is
51174** open so it is safe to access without the BtShared mutex.
51175*/
51176SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
51177  assert( p->pBt->pPager!=0 );
51178  return sqlite3PagerJournalname(p->pBt->pPager);
51179}
51180
51181/*
51182** Return non-zero if a transaction is active.
51183*/
51184SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
51185  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
51186  return (p && (p->inTrans==TRANS_WRITE));
51187}
51188
51189/*
51190** Return non-zero if a read (or write) transaction is active.
51191*/
51192SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
51193  assert( p );
51194  assert( sqlite3_mutex_held(p->db->mutex) );
51195  return p->inTrans!=TRANS_NONE;
51196}
51197
51198SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
51199  assert( p );
51200  assert( sqlite3_mutex_held(p->db->mutex) );
51201  return p->nBackup!=0;
51202}
51203
51204/*
51205** This function returns a pointer to a blob of memory associated with
51206** a single shared-btree. The memory is used by client code for its own
51207** purposes (for example, to store a high-level schema associated with
51208** the shared-btree). The btree layer manages reference counting issues.
51209**
51210** The first time this is called on a shared-btree, nBytes bytes of memory
51211** are allocated, zeroed, and returned to the caller. For each subsequent
51212** call the nBytes parameter is ignored and a pointer to the same blob
51213** of memory returned.
51214**
51215** If the nBytes parameter is 0 and the blob of memory has not yet been
51216** allocated, a null pointer is returned. If the blob has already been
51217** allocated, it is returned as normal.
51218**
51219** Just before the shared-btree is closed, the function passed as the
51220** xFree argument when the memory allocation was made is invoked on the
51221** blob of allocated memory. This function should not call sqlite3_free()
51222** on the memory, the btree layer does that.
51223*/
51224SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
51225  BtShared *pBt = p->pBt;
51226  sqlite3BtreeEnter(p);
51227  if( !pBt->pSchema && nBytes ){
51228    pBt->pSchema = sqlite3MallocZero(nBytes);
51229    pBt->xFreeSchema = xFree;
51230  }
51231  sqlite3BtreeLeave(p);
51232  return pBt->pSchema;
51233}
51234
51235/*
51236** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
51237** btree as the argument handle holds an exclusive lock on the
51238** sqlite_master table. Otherwise SQLITE_OK.
51239*/
51240SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
51241  int rc;
51242  assert( sqlite3_mutex_held(p->db->mutex) );
51243  sqlite3BtreeEnter(p);
51244  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51245  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
51246  sqlite3BtreeLeave(p);
51247  return rc;
51248}
51249
51250
51251#ifndef SQLITE_OMIT_SHARED_CACHE
51252/*
51253** Obtain a lock on the table whose root page is iTab.  The
51254** lock is a write lock if isWritelock is true or a read lock
51255** if it is false.
51256*/
51257SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
51258  int rc = SQLITE_OK;
51259  assert( p->inTrans!=TRANS_NONE );
51260  if( p->sharable ){
51261    u8 lockType = READ_LOCK + isWriteLock;
51262    assert( READ_LOCK+1==WRITE_LOCK );
51263    assert( isWriteLock==0 || isWriteLock==1 );
51264
51265    sqlite3BtreeEnter(p);
51266    rc = querySharedCacheTableLock(p, iTab, lockType);
51267    if( rc==SQLITE_OK ){
51268      rc = setSharedCacheTableLock(p, iTab, lockType);
51269    }
51270    sqlite3BtreeLeave(p);
51271  }
51272  return rc;
51273}
51274#endif
51275
51276#ifndef SQLITE_OMIT_INCRBLOB
51277/*
51278** Argument pCsr must be a cursor opened for writing on an
51279** INTKEY table currently pointing at a valid table entry.
51280** This function modifies the data stored as part of that entry.
51281**
51282** Only the data content may only be modified, it is not possible to
51283** change the length of the data stored. If this function is called with
51284** parameters that attempt to write past the end of the existing data,
51285** no modifications are made and SQLITE_CORRUPT is returned.
51286*/
51287SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
51288  int rc;
51289  assert( cursorHoldsMutex(pCsr) );
51290  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
51291  assert( pCsr->isIncrblobHandle );
51292
51293  rc = restoreCursorPosition(pCsr);
51294  if( rc!=SQLITE_OK ){
51295    return rc;
51296  }
51297  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
51298  if( pCsr->eState!=CURSOR_VALID ){
51299    return SQLITE_ABORT;
51300  }
51301
51302  /* Check some assumptions:
51303  **   (a) the cursor is open for writing,
51304  **   (b) there is a read/write transaction open,
51305  **   (c) the connection holds a write-lock on the table (if required),
51306  **   (d) there are no conflicting read-locks, and
51307  **   (e) the cursor points at a valid row of an intKey table.
51308  */
51309  if( !pCsr->wrFlag ){
51310    return SQLITE_READONLY;
51311  }
51312  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
51313  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
51314  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
51315  assert( pCsr->apPage[pCsr->iPage]->intKey );
51316
51317  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
51318}
51319
51320/*
51321** Set a flag on this cursor to cache the locations of pages from the
51322** overflow list for the current row. This is used by cursors opened
51323** for incremental blob IO only.
51324**
51325** This function sets a flag only. The actual page location cache
51326** (stored in BtCursor.aOverflow[]) is allocated and used by function
51327** accessPayload() (the worker function for sqlite3BtreeData() and
51328** sqlite3BtreePutData()).
51329*/
51330SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
51331  assert( cursorHoldsMutex(pCur) );
51332  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51333  assert(!pCur->isIncrblobHandle);
51334  assert(!pCur->aOverflow);
51335  pCur->isIncrblobHandle = 1;
51336}
51337#endif
51338
51339/*
51340** Set both the "read version" (single byte at byte offset 18) and
51341** "write version" (single byte at byte offset 19) fields in the database
51342** header to iVersion.
51343*/
51344SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
51345  BtShared *pBt = pBtree->pBt;
51346  int rc;                         /* Return code */
51347
51348  assert( pBtree->inTrans==TRANS_NONE );
51349  assert( iVersion==1 || iVersion==2 );
51350
51351  /* If setting the version fields to 1, do not automatically open the
51352  ** WAL connection, even if the version fields are currently set to 2.
51353  */
51354  pBt->doNotUseWAL = (iVersion==1);
51355
51356  rc = sqlite3BtreeBeginTrans(pBtree, 0);
51357  if( rc==SQLITE_OK ){
51358    u8 *aData = pBt->pPage1->aData;
51359    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
51360      rc = sqlite3BtreeBeginTrans(pBtree, 2);
51361      if( rc==SQLITE_OK ){
51362        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51363        if( rc==SQLITE_OK ){
51364          aData[18] = (u8)iVersion;
51365          aData[19] = (u8)iVersion;
51366        }
51367      }
51368    }
51369  }
51370
51371  pBt->doNotUseWAL = 0;
51372  return rc;
51373}
51374
51375/************** End of btree.c ***********************************************/
51376/************** Begin file backup.c ******************************************/
51377/*
51378** 2009 January 28
51379**
51380** The author disclaims copyright to this source code.  In place of
51381** a legal notice, here is a blessing:
51382**
51383**    May you do good and not evil.
51384**    May you find forgiveness for yourself and forgive others.
51385**    May you share freely, never taking more than you give.
51386**
51387*************************************************************************
51388** This file contains the implementation of the sqlite3_backup_XXX()
51389** API functions and the related features.
51390*/
51391
51392/* Macro to find the minimum of two numeric values.
51393*/
51394#ifndef MIN
51395# define MIN(x,y) ((x)<(y)?(x):(y))
51396#endif
51397
51398/*
51399** Structure allocated for each backup operation.
51400*/
51401struct sqlite3_backup {
51402  sqlite3* pDestDb;        /* Destination database handle */
51403  Btree *pDest;            /* Destination b-tree file */
51404  u32 iDestSchema;         /* Original schema cookie in destination */
51405  int bDestLocked;         /* True once a write-transaction is open on pDest */
51406
51407  Pgno iNext;              /* Page number of the next source page to copy */
51408  sqlite3* pSrcDb;         /* Source database handle */
51409  Btree *pSrc;             /* Source b-tree file */
51410
51411  int rc;                  /* Backup process error code */
51412
51413  /* These two variables are set by every call to backup_step(). They are
51414  ** read by calls to backup_remaining() and backup_pagecount().
51415  */
51416  Pgno nRemaining;         /* Number of pages left to copy */
51417  Pgno nPagecount;         /* Total number of pages to copy */
51418
51419  int isAttached;          /* True once backup has been registered with pager */
51420  sqlite3_backup *pNext;   /* Next backup associated with source pager */
51421};
51422
51423/*
51424** THREAD SAFETY NOTES:
51425**
51426**   Once it has been created using backup_init(), a single sqlite3_backup
51427**   structure may be accessed via two groups of thread-safe entry points:
51428**
51429**     * Via the sqlite3_backup_XXX() API function backup_step() and
51430**       backup_finish(). Both these functions obtain the source database
51431**       handle mutex and the mutex associated with the source BtShared
51432**       structure, in that order.
51433**
51434**     * Via the BackupUpdate() and BackupRestart() functions, which are
51435**       invoked by the pager layer to report various state changes in
51436**       the page cache associated with the source database. The mutex
51437**       associated with the source database BtShared structure will always
51438**       be held when either of these functions are invoked.
51439**
51440**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
51441**   backup_pagecount() are not thread-safe functions. If they are called
51442**   while some other thread is calling backup_step() or backup_finish(),
51443**   the values returned may be invalid. There is no way for a call to
51444**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
51445**   or backup_pagecount().
51446**
51447**   Depending on the SQLite configuration, the database handles and/or
51448**   the Btree objects may have their own mutexes that require locking.
51449**   Non-sharable Btrees (in-memory databases for example), do not have
51450**   associated mutexes.
51451*/
51452
51453/*
51454** Return a pointer corresponding to database zDb (i.e. "main", "temp")
51455** in connection handle pDb. If such a database cannot be found, return
51456** a NULL pointer and write an error message to pErrorDb.
51457**
51458** If the "temp" database is requested, it may need to be opened by this
51459** function. If an error occurs while doing so, return 0 and write an
51460** error message to pErrorDb.
51461*/
51462static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
51463  int i = sqlite3FindDbName(pDb, zDb);
51464
51465  if( i==1 ){
51466    Parse *pParse;
51467    int rc = 0;
51468    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
51469    if( pParse==0 ){
51470      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
51471      rc = SQLITE_NOMEM;
51472    }else{
51473      pParse->db = pDb;
51474      if( sqlite3OpenTempDatabase(pParse) ){
51475        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
51476        rc = SQLITE_ERROR;
51477      }
51478      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
51479      sqlite3StackFree(pErrorDb, pParse);
51480    }
51481    if( rc ){
51482      return 0;
51483    }
51484  }
51485
51486  if( i<0 ){
51487    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
51488    return 0;
51489  }
51490
51491  return pDb->aDb[i].pBt;
51492}
51493
51494/*
51495** Create an sqlite3_backup process to copy the contents of zSrcDb from
51496** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
51497** a pointer to the new sqlite3_backup object.
51498**
51499** If an error occurs, NULL is returned and an error code and error message
51500** stored in database handle pDestDb.
51501*/
51502SQLITE_API sqlite3_backup *sqlite3_backup_init(
51503  sqlite3* pDestDb,                     /* Database to write to */
51504  const char *zDestDb,                  /* Name of database within pDestDb */
51505  sqlite3* pSrcDb,                      /* Database connection to read from */
51506  const char *zSrcDb                    /* Name of database within pSrcDb */
51507){
51508  sqlite3_backup *p;                    /* Value to return */
51509
51510  /* Lock the source database handle. The destination database
51511  ** handle is not locked in this routine, but it is locked in
51512  ** sqlite3_backup_step(). The user is required to ensure that no
51513  ** other thread accesses the destination handle for the duration
51514  ** of the backup operation.  Any attempt to use the destination
51515  ** database connection while a backup is in progress may cause
51516  ** a malfunction or a deadlock.
51517  */
51518  sqlite3_mutex_enter(pSrcDb->mutex);
51519  sqlite3_mutex_enter(pDestDb->mutex);
51520
51521  if( pSrcDb==pDestDb ){
51522    sqlite3Error(
51523        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
51524    );
51525    p = 0;
51526  }else {
51527    /* Allocate space for a new sqlite3_backup object */
51528    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
51529    if( !p ){
51530      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
51531    }
51532  }
51533
51534  /* If the allocation succeeded, populate the new object. */
51535  if( p ){
51536    memset(p, 0, sizeof(sqlite3_backup));
51537    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
51538    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
51539    p->pDestDb = pDestDb;
51540    p->pSrcDb = pSrcDb;
51541    p->iNext = 1;
51542    p->isAttached = 0;
51543
51544    if( 0==p->pSrc || 0==p->pDest ){
51545      /* One (or both) of the named databases did not exist. An error has
51546      ** already been written into the pDestDb handle. All that is left
51547      ** to do here is free the sqlite3_backup structure.
51548      */
51549      sqlite3_free(p);
51550      p = 0;
51551    }
51552  }
51553  if( p ){
51554    p->pSrc->nBackup++;
51555  }
51556
51557  sqlite3_mutex_leave(pDestDb->mutex);
51558  sqlite3_mutex_leave(pSrcDb->mutex);
51559  return p;
51560}
51561
51562/*
51563** Argument rc is an SQLite error code. Return true if this error is
51564** considered fatal if encountered during a backup operation. All errors
51565** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
51566*/
51567static int isFatalError(int rc){
51568  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
51569}
51570
51571/*
51572** Parameter zSrcData points to a buffer containing the data for
51573** page iSrcPg from the source database. Copy this data into the
51574** destination database.
51575*/
51576static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
51577  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
51578  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
51579  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
51580  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
51581  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
51582
51583  int rc = SQLITE_OK;
51584  i64 iOff;
51585
51586  assert( p->bDestLocked );
51587  assert( !isFatalError(p->rc) );
51588  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
51589  assert( zSrcData );
51590
51591  /* Catch the case where the destination is an in-memory database and the
51592  ** page sizes of the source and destination differ.
51593  */
51594  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
51595    rc = SQLITE_READONLY;
51596  }
51597
51598  /* This loop runs once for each destination page spanned by the source
51599  ** page. For each iteration, variable iOff is set to the byte offset
51600  ** of the destination page.
51601  */
51602  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
51603    DbPage *pDestPg = 0;
51604    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
51605    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
51606    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
51607     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
51608    ){
51609      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
51610      u8 *zDestData = sqlite3PagerGetData(pDestPg);
51611      u8 *zOut = &zDestData[iOff%nDestPgsz];
51612
51613      /* Copy the data from the source page into the destination page.
51614      ** Then clear the Btree layer MemPage.isInit flag. Both this module
51615      ** and the pager code use this trick (clearing the first byte
51616      ** of the page 'extra' space to invalidate the Btree layers
51617      ** cached parse of the page). MemPage.isInit is marked
51618      ** "MUST BE FIRST" for this purpose.
51619      */
51620      memcpy(zOut, zIn, nCopy);
51621      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
51622    }
51623    sqlite3PagerUnref(pDestPg);
51624  }
51625
51626  return rc;
51627}
51628
51629/*
51630** If pFile is currently larger than iSize bytes, then truncate it to
51631** exactly iSize bytes. If pFile is not larger than iSize bytes, then
51632** this function is a no-op.
51633**
51634** Return SQLITE_OK if everything is successful, or an SQLite error
51635** code if an error occurs.
51636*/
51637static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
51638  i64 iCurrent;
51639  int rc = sqlite3OsFileSize(pFile, &iCurrent);
51640  if( rc==SQLITE_OK && iCurrent>iSize ){
51641    rc = sqlite3OsTruncate(pFile, iSize);
51642  }
51643  return rc;
51644}
51645
51646/*
51647** Register this backup object with the associated source pager for
51648** callbacks when pages are changed or the cache invalidated.
51649*/
51650static void attachBackupObject(sqlite3_backup *p){
51651  sqlite3_backup **pp;
51652  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
51653  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
51654  p->pNext = *pp;
51655  *pp = p;
51656  p->isAttached = 1;
51657}
51658
51659/*
51660** Copy nPage pages from the source b-tree to the destination.
51661*/
51662SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
51663  int rc;
51664  int destMode;       /* Destination journal mode */
51665  int pgszSrc = 0;    /* Source page size */
51666  int pgszDest = 0;   /* Destination page size */
51667
51668  sqlite3_mutex_enter(p->pSrcDb->mutex);
51669  sqlite3BtreeEnter(p->pSrc);
51670  if( p->pDestDb ){
51671    sqlite3_mutex_enter(p->pDestDb->mutex);
51672  }
51673
51674  rc = p->rc;
51675  if( !isFatalError(rc) ){
51676    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
51677    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
51678    int ii;                            /* Iterator variable */
51679    int nSrcPage = -1;                 /* Size of source db in pages */
51680    int bCloseTrans = 0;               /* True if src db requires unlocking */
51681
51682    /* If the source pager is currently in a write-transaction, return
51683    ** SQLITE_BUSY immediately.
51684    */
51685    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
51686      rc = SQLITE_BUSY;
51687    }else{
51688      rc = SQLITE_OK;
51689    }
51690
51691    /* Lock the destination database, if it is not locked already. */
51692    if( SQLITE_OK==rc && p->bDestLocked==0
51693     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
51694    ){
51695      p->bDestLocked = 1;
51696      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
51697    }
51698
51699    /* If there is no open read-transaction on the source database, open
51700    ** one now. If a transaction is opened here, then it will be closed
51701    ** before this function exits.
51702    */
51703    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
51704      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
51705      bCloseTrans = 1;
51706    }
51707
51708    /* Do not allow backup if the destination database is in WAL mode
51709    ** and the page sizes are different between source and destination */
51710    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
51711    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
51712    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
51713    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
51714      rc = SQLITE_READONLY;
51715    }
51716
51717    /* Now that there is a read-lock on the source database, query the
51718    ** source pager for the number of pages in the database.
51719    */
51720    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
51721    assert( nSrcPage>=0 );
51722    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
51723      const Pgno iSrcPg = p->iNext;                 /* Source page number */
51724      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
51725        DbPage *pSrcPg;                             /* Source page object */
51726        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
51727        if( rc==SQLITE_OK ){
51728          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
51729          sqlite3PagerUnref(pSrcPg);
51730        }
51731      }
51732      p->iNext++;
51733    }
51734    if( rc==SQLITE_OK ){
51735      p->nPagecount = nSrcPage;
51736      p->nRemaining = nSrcPage+1-p->iNext;
51737      if( p->iNext>(Pgno)nSrcPage ){
51738        rc = SQLITE_DONE;
51739      }else if( !p->isAttached ){
51740        attachBackupObject(p);
51741      }
51742    }
51743
51744    /* Update the schema version field in the destination database. This
51745    ** is to make sure that the schema-version really does change in
51746    ** the case where the source and destination databases have the
51747    ** same schema version.
51748    */
51749    if( rc==SQLITE_DONE
51750     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
51751    ){
51752      int nDestTruncate;
51753
51754      if( p->pDestDb ){
51755        sqlite3ResetInternalSchema(p->pDestDb, 0);
51756      }
51757
51758      /* Set nDestTruncate to the final number of pages in the destination
51759      ** database. The complication here is that the destination page
51760      ** size may be different to the source page size.
51761      **
51762      ** If the source page size is smaller than the destination page size,
51763      ** round up. In this case the call to sqlite3OsTruncate() below will
51764      ** fix the size of the file. However it is important to call
51765      ** sqlite3PagerTruncateImage() here so that any pages in the
51766      ** destination file that lie beyond the nDestTruncate page mark are
51767      ** journalled by PagerCommitPhaseOne() before they are destroyed
51768      ** by the file truncation.
51769      */
51770      assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
51771      assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
51772      if( pgszSrc<pgszDest ){
51773        int ratio = pgszDest/pgszSrc;
51774        nDestTruncate = (nSrcPage+ratio-1)/ratio;
51775        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
51776          nDestTruncate--;
51777        }
51778      }else{
51779        nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
51780      }
51781      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
51782
51783      if( pgszSrc<pgszDest ){
51784        /* If the source page-size is smaller than the destination page-size,
51785        ** two extra things may need to happen:
51786        **
51787        **   * The destination may need to be truncated, and
51788        **
51789        **   * Data stored on the pages immediately following the
51790        **     pending-byte page in the source database may need to be
51791        **     copied into the destination database.
51792        */
51793        const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
51794        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
51795
51796        assert( pFile );
51797        assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
51798              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
51799           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
51800        ));
51801        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
51802         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
51803         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
51804        ){
51805          i64 iOff;
51806          i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
51807          for(
51808            iOff=PENDING_BYTE+pgszSrc;
51809            rc==SQLITE_OK && iOff<iEnd;
51810            iOff+=pgszSrc
51811          ){
51812            PgHdr *pSrcPg = 0;
51813            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
51814            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
51815            if( rc==SQLITE_OK ){
51816              u8 *zData = sqlite3PagerGetData(pSrcPg);
51817              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
51818            }
51819            sqlite3PagerUnref(pSrcPg);
51820          }
51821        }
51822      }else{
51823        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
51824      }
51825
51826      /* Finish committing the transaction to the destination database. */
51827      if( SQLITE_OK==rc
51828       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
51829      ){
51830        rc = SQLITE_DONE;
51831      }
51832    }
51833
51834    /* If bCloseTrans is true, then this function opened a read transaction
51835    ** on the source database. Close the read transaction here. There is
51836    ** no need to check the return values of the btree methods here, as
51837    ** "committing" a read-only transaction cannot fail.
51838    */
51839    if( bCloseTrans ){
51840      TESTONLY( int rc2 );
51841      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
51842      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
51843      assert( rc2==SQLITE_OK );
51844    }
51845
51846    p->rc = rc;
51847  }
51848  if( p->pDestDb ){
51849    sqlite3_mutex_leave(p->pDestDb->mutex);
51850  }
51851  sqlite3BtreeLeave(p->pSrc);
51852  sqlite3_mutex_leave(p->pSrcDb->mutex);
51853  return rc;
51854}
51855
51856/*
51857** Release all resources associated with an sqlite3_backup* handle.
51858*/
51859SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
51860  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
51861  sqlite3_mutex *mutex;                /* Mutex to protect source database */
51862  int rc;                              /* Value to return */
51863
51864  /* Enter the mutexes */
51865  if( p==0 ) return SQLITE_OK;
51866  sqlite3_mutex_enter(p->pSrcDb->mutex);
51867  sqlite3BtreeEnter(p->pSrc);
51868  mutex = p->pSrcDb->mutex;
51869  if( p->pDestDb ){
51870    sqlite3_mutex_enter(p->pDestDb->mutex);
51871  }
51872
51873  /* Detach this backup from the source pager. */
51874  if( p->pDestDb ){
51875    p->pSrc->nBackup--;
51876  }
51877  if( p->isAttached ){
51878    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
51879    while( *pp!=p ){
51880      pp = &(*pp)->pNext;
51881    }
51882    *pp = p->pNext;
51883  }
51884
51885  /* If a transaction is still open on the Btree, roll it back. */
51886  sqlite3BtreeRollback(p->pDest);
51887
51888  /* Set the error code of the destination database handle. */
51889  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
51890  sqlite3Error(p->pDestDb, rc, 0);
51891
51892  /* Exit the mutexes and free the backup context structure. */
51893  if( p->pDestDb ){
51894    sqlite3_mutex_leave(p->pDestDb->mutex);
51895  }
51896  sqlite3BtreeLeave(p->pSrc);
51897  if( p->pDestDb ){
51898    sqlite3_free(p);
51899  }
51900  sqlite3_mutex_leave(mutex);
51901  return rc;
51902}
51903
51904/*
51905** Return the number of pages still to be backed up as of the most recent
51906** call to sqlite3_backup_step().
51907*/
51908SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
51909  return p->nRemaining;
51910}
51911
51912/*
51913** Return the total number of pages in the source database as of the most
51914** recent call to sqlite3_backup_step().
51915*/
51916SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
51917  return p->nPagecount;
51918}
51919
51920/*
51921** This function is called after the contents of page iPage of the
51922** source database have been modified. If page iPage has already been
51923** copied into the destination database, then the data written to the
51924** destination is now invalidated. The destination copy of iPage needs
51925** to be updated with the new data before the backup operation is
51926** complete.
51927**
51928** It is assumed that the mutex associated with the BtShared object
51929** corresponding to the source database is held when this function is
51930** called.
51931*/
51932SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
51933  sqlite3_backup *p;                   /* Iterator variable */
51934  for(p=pBackup; p; p=p->pNext){
51935    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
51936    if( !isFatalError(p->rc) && iPage<p->iNext ){
51937      /* The backup process p has already copied page iPage. But now it
51938      ** has been modified by a transaction on the source pager. Copy
51939      ** the new data into the backup.
51940      */
51941      int rc = backupOnePage(p, iPage, aData);
51942      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
51943      if( rc!=SQLITE_OK ){
51944        p->rc = rc;
51945      }
51946    }
51947  }
51948}
51949
51950/*
51951** Restart the backup process. This is called when the pager layer
51952** detects that the database has been modified by an external database
51953** connection. In this case there is no way of knowing which of the
51954** pages that have been copied into the destination database are still
51955** valid and which are not, so the entire process needs to be restarted.
51956**
51957** It is assumed that the mutex associated with the BtShared object
51958** corresponding to the source database is held when this function is
51959** called.
51960*/
51961SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
51962  sqlite3_backup *p;                   /* Iterator variable */
51963  for(p=pBackup; p; p=p->pNext){
51964    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
51965    p->iNext = 1;
51966  }
51967}
51968
51969#ifndef SQLITE_OMIT_VACUUM
51970/*
51971** Copy the complete content of pBtFrom into pBtTo.  A transaction
51972** must be active for both files.
51973**
51974** The size of file pTo may be reduced by this operation. If anything
51975** goes wrong, the transaction on pTo is rolled back. If successful, the
51976** transaction is committed before returning.
51977*/
51978SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
51979  int rc;
51980  sqlite3_backup b;
51981  sqlite3BtreeEnter(pTo);
51982  sqlite3BtreeEnter(pFrom);
51983
51984  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
51985  ** to 0. This is used by the implementations of sqlite3_backup_step()
51986  ** and sqlite3_backup_finish() to detect that they are being called
51987  ** from this function, not directly by the user.
51988  */
51989  memset(&b, 0, sizeof(b));
51990  b.pSrcDb = pFrom->db;
51991  b.pSrc = pFrom;
51992  b.pDest = pTo;
51993  b.iNext = 1;
51994
51995  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
51996  ** file. By passing this as the number of pages to copy to
51997  ** sqlite3_backup_step(), we can guarantee that the copy finishes
51998  ** within a single call (unless an error occurs). The assert() statement
51999  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
52000  ** or an error code.
52001  */
52002  sqlite3_backup_step(&b, 0x7FFFFFFF);
52003  assert( b.rc!=SQLITE_OK );
52004  rc = sqlite3_backup_finish(&b);
52005  if( rc==SQLITE_OK ){
52006    pTo->pBt->pageSizeFixed = 0;
52007  }
52008
52009  sqlite3BtreeLeave(pFrom);
52010  sqlite3BtreeLeave(pTo);
52011  return rc;
52012}
52013#endif /* SQLITE_OMIT_VACUUM */
52014
52015/************** End of backup.c **********************************************/
52016/************** Begin file vdbemem.c *****************************************/
52017/*
52018** 2004 May 26
52019**
52020** The author disclaims copyright to this source code.  In place of
52021** a legal notice, here is a blessing:
52022**
52023**    May you do good and not evil.
52024**    May you find forgiveness for yourself and forgive others.
52025**    May you share freely, never taking more than you give.
52026**
52027*************************************************************************
52028**
52029** This file contains code use to manipulate "Mem" structure.  A "Mem"
52030** stores a single value in the VDBE.  Mem is an opaque structure visible
52031** only within the VDBE.  Interface routines refer to a Mem using the
52032** name sqlite_value
52033*/
52034
52035/*
52036** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52037** P if required.
52038*/
52039#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52040
52041/*
52042** If pMem is an object with a valid string representation, this routine
52043** ensures the internal encoding for the string representation is
52044** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
52045**
52046** If pMem is not a string object, or the encoding of the string
52047** representation is already stored using the requested encoding, then this
52048** routine is a no-op.
52049**
52050** SQLITE_OK is returned if the conversion is successful (or not required).
52051** SQLITE_NOMEM may be returned if a malloc() fails during conversion
52052** between formats.
52053*/
52054SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
52055  int rc;
52056  assert( (pMem->flags&MEM_RowSet)==0 );
52057  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
52058           || desiredEnc==SQLITE_UTF16BE );
52059  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
52060    return SQLITE_OK;
52061  }
52062  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52063#ifdef SQLITE_OMIT_UTF16
52064  return SQLITE_ERROR;
52065#else
52066
52067  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
52068  ** then the encoding of the value may not have changed.
52069  */
52070  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
52071  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
52072  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
52073  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
52074  return rc;
52075#endif
52076}
52077
52078/*
52079** Make sure pMem->z points to a writable allocation of at least
52080** n bytes.
52081**
52082** If the memory cell currently contains string or blob data
52083** and the third argument passed to this function is true, the
52084** current content of the cell is preserved. Otherwise, it may
52085** be discarded.
52086**
52087** This function sets the MEM_Dyn flag and clears any xDel callback.
52088** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
52089** not set, Mem.n is zeroed.
52090*/
52091SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
52092  assert( 1 >=
52093    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
52094    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
52095    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
52096    ((pMem->flags&MEM_Static) ? 1 : 0)
52097  );
52098  assert( (pMem->flags&MEM_RowSet)==0 );
52099
52100  if( n<32 ) n = 32;
52101  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
52102    if( preserve && pMem->z==pMem->zMalloc ){
52103      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
52104      preserve = 0;
52105    }else{
52106      sqlite3DbFree(pMem->db, pMem->zMalloc);
52107      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
52108    }
52109  }
52110
52111  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
52112    memcpy(pMem->zMalloc, pMem->z, pMem->n);
52113  }
52114  if( pMem->flags&MEM_Dyn && pMem->xDel ){
52115    pMem->xDel((void *)(pMem->z));
52116  }
52117
52118  pMem->z = pMem->zMalloc;
52119  if( pMem->z==0 ){
52120    pMem->flags = MEM_Null;
52121  }else{
52122    pMem->flags &= ~(MEM_Ephem|MEM_Static);
52123  }
52124  pMem->xDel = 0;
52125  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
52126}
52127
52128/*
52129** Make the given Mem object MEM_Dyn.  In other words, make it so
52130** that any TEXT or BLOB content is stored in memory obtained from
52131** malloc().  In this way, we know that the memory is safe to be
52132** overwritten or altered.
52133**
52134** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
52135*/
52136SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
52137  int f;
52138  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52139  assert( (pMem->flags&MEM_RowSet)==0 );
52140  expandBlob(pMem);
52141  f = pMem->flags;
52142  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
52143    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
52144      return SQLITE_NOMEM;
52145    }
52146    pMem->z[pMem->n] = 0;
52147    pMem->z[pMem->n+1] = 0;
52148    pMem->flags |= MEM_Term;
52149  }
52150
52151  return SQLITE_OK;
52152}
52153
52154/*
52155** If the given Mem* has a zero-filled tail, turn it into an ordinary
52156** blob stored in dynamically allocated space.
52157*/
52158#ifndef SQLITE_OMIT_INCRBLOB
52159SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
52160  if( pMem->flags & MEM_Zero ){
52161    int nByte;
52162    assert( pMem->flags&MEM_Blob );
52163    assert( (pMem->flags&MEM_RowSet)==0 );
52164    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52165
52166    /* Set nByte to the number of bytes required to store the expanded blob. */
52167    nByte = pMem->n + pMem->u.nZero;
52168    if( nByte<=0 ){
52169      nByte = 1;
52170    }
52171    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
52172      return SQLITE_NOMEM;
52173    }
52174
52175    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
52176    pMem->n += pMem->u.nZero;
52177    pMem->flags &= ~(MEM_Zero|MEM_Term);
52178  }
52179  return SQLITE_OK;
52180}
52181#endif
52182
52183
52184/*
52185** Make sure the given Mem is \u0000 terminated.
52186*/
52187SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
52188  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52189  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
52190    return SQLITE_OK;   /* Nothing to do */
52191  }
52192  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
52193    return SQLITE_NOMEM;
52194  }
52195  pMem->z[pMem->n] = 0;
52196  pMem->z[pMem->n+1] = 0;
52197  pMem->flags |= MEM_Term;
52198  return SQLITE_OK;
52199}
52200
52201/*
52202** Add MEM_Str to the set of representations for the given Mem.  Numbers
52203** are converted using sqlite3_snprintf().  Converting a BLOB to a string
52204** is a no-op.
52205**
52206** Existing representations MEM_Int and MEM_Real are *not* invalidated.
52207**
52208** A MEM_Null value will never be passed to this function. This function is
52209** used for converting values to text for returning to the user (i.e. via
52210** sqlite3_value_text()), or for ensuring that values to be used as btree
52211** keys are strings. In the former case a NULL pointer is returned the
52212** user and the later is an internal programming error.
52213*/
52214SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
52215  int rc = SQLITE_OK;
52216  int fg = pMem->flags;
52217  const int nByte = 32;
52218
52219  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52220  assert( !(fg&MEM_Zero) );
52221  assert( !(fg&(MEM_Str|MEM_Blob)) );
52222  assert( fg&(MEM_Int|MEM_Real) );
52223  assert( (pMem->flags&MEM_RowSet)==0 );
52224  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52225
52226
52227  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52228    return SQLITE_NOMEM;
52229  }
52230
52231  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
52232  ** string representation of the value. Then, if the required encoding
52233  ** is UTF-16le or UTF-16be do a translation.
52234  **
52235  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
52236  */
52237  if( fg & MEM_Int ){
52238    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
52239  }else{
52240    assert( fg & MEM_Real );
52241    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
52242  }
52243  pMem->n = sqlite3Strlen30(pMem->z);
52244  pMem->enc = SQLITE_UTF8;
52245  pMem->flags |= MEM_Str|MEM_Term;
52246  sqlite3VdbeChangeEncoding(pMem, enc);
52247  return rc;
52248}
52249
52250/*
52251** Memory cell pMem contains the context of an aggregate function.
52252** This routine calls the finalize method for that function.  The
52253** result of the aggregate is stored back into pMem.
52254**
52255** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
52256** otherwise.
52257*/
52258SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
52259  int rc = SQLITE_OK;
52260  if( ALWAYS(pFunc && pFunc->xFinalize) ){
52261    sqlite3_context ctx;
52262    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
52263    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52264    memset(&ctx, 0, sizeof(ctx));
52265    ctx.s.flags = MEM_Null;
52266    ctx.s.db = pMem->db;
52267    ctx.pMem = pMem;
52268    ctx.pFunc = pFunc;
52269    pFunc->xFinalize(&ctx);
52270    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
52271    sqlite3DbFree(pMem->db, pMem->zMalloc);
52272    memcpy(pMem, &ctx.s, sizeof(ctx.s));
52273    rc = ctx.isError;
52274  }
52275  return rc;
52276}
52277
52278/*
52279** If the memory cell contains a string value that must be freed by
52280** invoking an external callback, free it now. Calling this function
52281** does not free any Mem.zMalloc buffer.
52282*/
52283SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
52284  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
52285  testcase( p->flags & MEM_Agg );
52286  testcase( p->flags & MEM_Dyn );
52287  testcase( p->flags & MEM_RowSet );
52288  testcase( p->flags & MEM_Frame );
52289  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
52290    if( p->flags&MEM_Agg ){
52291      sqlite3VdbeMemFinalize(p, p->u.pDef);
52292      assert( (p->flags & MEM_Agg)==0 );
52293      sqlite3VdbeMemRelease(p);
52294    }else if( p->flags&MEM_Dyn && p->xDel ){
52295      assert( (p->flags&MEM_RowSet)==0 );
52296      p->xDel((void *)p->z);
52297      p->xDel = 0;
52298    }else if( p->flags&MEM_RowSet ){
52299      sqlite3RowSetClear(p->u.pRowSet);
52300    }else if( p->flags&MEM_Frame ){
52301      sqlite3VdbeMemSetNull(p);
52302    }
52303  }
52304}
52305
52306/*
52307** Release any memory held by the Mem. This may leave the Mem in an
52308** inconsistent state, for example with (Mem.z==0) and
52309** (Mem.type==SQLITE_TEXT).
52310*/
52311SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
52312  sqlite3VdbeMemReleaseExternal(p);
52313  sqlite3DbFree(p->db, p->zMalloc);
52314  p->z = 0;
52315  p->zMalloc = 0;
52316  p->xDel = 0;
52317}
52318
52319/*
52320** Convert a 64-bit IEEE double into a 64-bit signed integer.
52321** If the double is too large, return 0x8000000000000000.
52322**
52323** Most systems appear to do this simply by assigning
52324** variables and without the extra range tests.  But
52325** there are reports that windows throws an expection
52326** if the floating point value is out of range. (See ticket #2880.)
52327** Because we do not completely understand the problem, we will
52328** take the conservative approach and always do range tests
52329** before attempting the conversion.
52330*/
52331static i64 doubleToInt64(double r){
52332#ifdef SQLITE_OMIT_FLOATING_POINT
52333  /* When floating-point is omitted, double and int64 are the same thing */
52334  return r;
52335#else
52336  /*
52337  ** Many compilers we encounter do not define constants for the
52338  ** minimum and maximum 64-bit integers, or they define them
52339  ** inconsistently.  And many do not understand the "LL" notation.
52340  ** So we define our own static constants here using nothing
52341  ** larger than a 32-bit integer constant.
52342  */
52343  static const i64 maxInt = LARGEST_INT64;
52344  static const i64 minInt = SMALLEST_INT64;
52345
52346  if( r<(double)minInt ){
52347    return minInt;
52348  }else if( r>(double)maxInt ){
52349    /* minInt is correct here - not maxInt.  It turns out that assigning
52350    ** a very large positive number to an integer results in a very large
52351    ** negative integer.  This makes no sense, but it is what x86 hardware
52352    ** does so for compatibility we will do the same in software. */
52353    return minInt;
52354  }else{
52355    return (i64)r;
52356  }
52357#endif
52358}
52359
52360/*
52361** Return some kind of integer value which is the best we can do
52362** at representing the value that *pMem describes as an integer.
52363** If pMem is an integer, then the value is exact.  If pMem is
52364** a floating-point then the value returned is the integer part.
52365** If pMem is a string or blob, then we make an attempt to convert
52366** it into a integer and return that.  If pMem represents an
52367** an SQL-NULL value, return 0.
52368**
52369** If pMem represents a string value, its encoding might be changed.
52370*/
52371SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
52372  int flags;
52373  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52374  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52375  flags = pMem->flags;
52376  if( flags & MEM_Int ){
52377    return pMem->u.i;
52378  }else if( flags & MEM_Real ){
52379    return doubleToInt64(pMem->r);
52380  }else if( flags & (MEM_Str|MEM_Blob) ){
52381    i64 value;
52382    pMem->flags |= MEM_Str;
52383    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52384       || sqlite3VdbeMemNulTerminate(pMem) ){
52385      return 0;
52386    }
52387    assert( pMem->z );
52388    sqlite3Atoi64(pMem->z, &value);
52389    return value;
52390  }else{
52391    return 0;
52392  }
52393}
52394
52395/*
52396** Return the best representation of pMem that we can get into a
52397** double.  If pMem is already a double or an integer, return its
52398** value.  If it is a string or blob, try to convert it to a double.
52399** If it is a NULL, return 0.0.
52400*/
52401SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
52402  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52403  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52404  if( pMem->flags & MEM_Real ){
52405    return pMem->r;
52406  }else if( pMem->flags & MEM_Int ){
52407    return (double)pMem->u.i;
52408  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
52409    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52410    double val = (double)0;
52411    pMem->flags |= MEM_Str;
52412    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52413       || sqlite3VdbeMemNulTerminate(pMem) ){
52414      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52415      return (double)0;
52416    }
52417    assert( pMem->z );
52418    sqlite3AtoF(pMem->z, &val);
52419    return val;
52420  }else{
52421    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52422    return (double)0;
52423  }
52424}
52425
52426/*
52427** The MEM structure is already a MEM_Real.  Try to also make it a
52428** MEM_Int if we can.
52429*/
52430SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
52431  assert( pMem->flags & MEM_Real );
52432  assert( (pMem->flags & MEM_RowSet)==0 );
52433  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52434  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52435
52436  pMem->u.i = doubleToInt64(pMem->r);
52437
52438  /* Only mark the value as an integer if
52439  **
52440  **    (1) the round-trip conversion real->int->real is a no-op, and
52441  **    (2) The integer is neither the largest nor the smallest
52442  **        possible integer (ticket #3922)
52443  **
52444  ** The second and third terms in the following conditional enforces
52445  ** the second condition under the assumption that addition overflow causes
52446  ** values to wrap around.  On x86 hardware, the third term is always
52447  ** true and could be omitted.  But we leave it in because other
52448  ** architectures might behave differently.
52449  */
52450  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
52451      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
52452    pMem->flags |= MEM_Int;
52453  }
52454}
52455
52456/*
52457** Convert pMem to type integer.  Invalidate any prior representations.
52458*/
52459SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
52460  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52461  assert( (pMem->flags & MEM_RowSet)==0 );
52462  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52463
52464  pMem->u.i = sqlite3VdbeIntValue(pMem);
52465  MemSetTypeFlag(pMem, MEM_Int);
52466  return SQLITE_OK;
52467}
52468
52469/*
52470** Convert pMem so that it is of type MEM_Real.
52471** Invalidate any prior representations.
52472*/
52473SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
52474  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52475  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52476
52477  pMem->r = sqlite3VdbeRealValue(pMem);
52478  MemSetTypeFlag(pMem, MEM_Real);
52479  return SQLITE_OK;
52480}
52481
52482/*
52483** Convert pMem so that it has types MEM_Real or MEM_Int or both.
52484** Invalidate any prior representations.
52485**
52486** Every effort is made to force the conversion, even if the input
52487** is a string that does not look completely like a number.  Convert
52488** as much of the string as we can and ignore the rest.
52489*/
52490SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
52491  int rc;
52492  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
52493  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
52494  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52495  rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8);
52496  if( rc ) return rc;
52497  rc = sqlite3VdbeMemNulTerminate(pMem);
52498  if( rc ) return rc;
52499  if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){
52500    MemSetTypeFlag(pMem, MEM_Int);
52501  }else{
52502    pMem->r = sqlite3VdbeRealValue(pMem);
52503    MemSetTypeFlag(pMem, MEM_Real);
52504    sqlite3VdbeIntegerAffinity(pMem);
52505  }
52506  return SQLITE_OK;
52507}
52508
52509/*
52510** Delete any previous value and set the value stored in *pMem to NULL.
52511*/
52512SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
52513  if( pMem->flags & MEM_Frame ){
52514    sqlite3VdbeFrameDelete(pMem->u.pFrame);
52515  }
52516  if( pMem->flags & MEM_RowSet ){
52517    sqlite3RowSetClear(pMem->u.pRowSet);
52518  }
52519  MemSetTypeFlag(pMem, MEM_Null);
52520  pMem->type = SQLITE_NULL;
52521}
52522
52523/*
52524** Delete any previous value and set the value to be a BLOB of length
52525** n containing all zeros.
52526*/
52527SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
52528  sqlite3VdbeMemRelease(pMem);
52529  pMem->flags = MEM_Blob|MEM_Zero;
52530  pMem->type = SQLITE_BLOB;
52531  pMem->n = 0;
52532  if( n<0 ) n = 0;
52533  pMem->u.nZero = n;
52534  pMem->enc = SQLITE_UTF8;
52535
52536#ifdef SQLITE_OMIT_INCRBLOB
52537  sqlite3VdbeMemGrow(pMem, n, 0);
52538  if( pMem->z ){
52539    pMem->n = n;
52540    memset(pMem->z, 0, n);
52541  }
52542#endif
52543}
52544
52545/*
52546** Delete any previous value and set the value stored in *pMem to val,
52547** manifest type INTEGER.
52548*/
52549SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
52550  sqlite3VdbeMemRelease(pMem);
52551  pMem->u.i = val;
52552  pMem->flags = MEM_Int;
52553  pMem->type = SQLITE_INTEGER;
52554}
52555
52556#ifndef SQLITE_OMIT_FLOATING_POINT
52557/*
52558** Delete any previous value and set the value stored in *pMem to val,
52559** manifest type REAL.
52560*/
52561SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
52562  if( sqlite3IsNaN(val) ){
52563    sqlite3VdbeMemSetNull(pMem);
52564  }else{
52565    sqlite3VdbeMemRelease(pMem);
52566    pMem->r = val;
52567    pMem->flags = MEM_Real;
52568    pMem->type = SQLITE_FLOAT;
52569  }
52570}
52571#endif
52572
52573/*
52574** Delete any previous value and set the value of pMem to be an
52575** empty boolean index.
52576*/
52577SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
52578  sqlite3 *db = pMem->db;
52579  assert( db!=0 );
52580  assert( (pMem->flags & MEM_RowSet)==0 );
52581  sqlite3VdbeMemRelease(pMem);
52582  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
52583  if( db->mallocFailed ){
52584    pMem->flags = MEM_Null;
52585  }else{
52586    assert( pMem->zMalloc );
52587    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
52588                                       sqlite3DbMallocSize(db, pMem->zMalloc));
52589    assert( pMem->u.pRowSet!=0 );
52590    pMem->flags = MEM_RowSet;
52591  }
52592}
52593
52594/*
52595** Return true if the Mem object contains a TEXT or BLOB that is
52596** too large - whose size exceeds SQLITE_MAX_LENGTH.
52597*/
52598SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
52599  assert( p->db!=0 );
52600  if( p->flags & (MEM_Str|MEM_Blob) ){
52601    int n = p->n;
52602    if( p->flags & MEM_Zero ){
52603      n += p->u.nZero;
52604    }
52605    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
52606  }
52607  return 0;
52608}
52609
52610/*
52611** Size of struct Mem not including the Mem.zMalloc member.
52612*/
52613#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
52614
52615/*
52616** Make an shallow copy of pFrom into pTo.  Prior contents of
52617** pTo are freed.  The pFrom->z field is not duplicated.  If
52618** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
52619** and flags gets srcType (either MEM_Ephem or MEM_Static).
52620*/
52621SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
52622  assert( (pFrom->flags & MEM_RowSet)==0 );
52623  sqlite3VdbeMemReleaseExternal(pTo);
52624  memcpy(pTo, pFrom, MEMCELLSIZE);
52625  pTo->xDel = 0;
52626  if( (pFrom->flags&MEM_Static)==0 ){
52627    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
52628    assert( srcType==MEM_Ephem || srcType==MEM_Static );
52629    pTo->flags |= srcType;
52630  }
52631}
52632
52633/*
52634** Make a full copy of pFrom into pTo.  Prior contents of pTo are
52635** freed before the copy is made.
52636*/
52637SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
52638  int rc = SQLITE_OK;
52639
52640  assert( (pFrom->flags & MEM_RowSet)==0 );
52641  sqlite3VdbeMemReleaseExternal(pTo);
52642  memcpy(pTo, pFrom, MEMCELLSIZE);
52643  pTo->flags &= ~MEM_Dyn;
52644
52645  if( pTo->flags&(MEM_Str|MEM_Blob) ){
52646    if( 0==(pFrom->flags&MEM_Static) ){
52647      pTo->flags |= MEM_Ephem;
52648      rc = sqlite3VdbeMemMakeWriteable(pTo);
52649    }
52650  }
52651
52652  return rc;
52653}
52654
52655/*
52656** Transfer the contents of pFrom to pTo. Any existing value in pTo is
52657** freed. If pFrom contains ephemeral data, a copy is made.
52658**
52659** pFrom contains an SQL NULL when this routine returns.
52660*/
52661SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
52662  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
52663  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
52664  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
52665
52666  sqlite3VdbeMemRelease(pTo);
52667  memcpy(pTo, pFrom, sizeof(Mem));
52668  pFrom->flags = MEM_Null;
52669  pFrom->xDel = 0;
52670  pFrom->zMalloc = 0;
52671}
52672
52673/*
52674** Change the value of a Mem to be a string or a BLOB.
52675**
52676** The memory management strategy depends on the value of the xDel
52677** parameter. If the value passed is SQLITE_TRANSIENT, then the
52678** string is copied into a (possibly existing) buffer managed by the
52679** Mem structure. Otherwise, any existing buffer is freed and the
52680** pointer copied.
52681**
52682** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
52683** size limit) then no memory allocation occurs.  If the string can be
52684** stored without allocating memory, then it is.  If a memory allocation
52685** is required to store the string, then value of pMem is unchanged.  In
52686** either case, SQLITE_TOOBIG is returned.
52687*/
52688SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
52689  Mem *pMem,          /* Memory cell to set to string value */
52690  const char *z,      /* String pointer */
52691  int n,              /* Bytes in string, or negative */
52692  u8 enc,             /* Encoding of z.  0 for BLOBs */
52693  void (*xDel)(void*) /* Destructor function */
52694){
52695  int nByte = n;      /* New value for pMem->n */
52696  int iLimit;         /* Maximum allowed string or blob size */
52697  u16 flags = 0;      /* New value for pMem->flags */
52698
52699  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52700  assert( (pMem->flags & MEM_RowSet)==0 );
52701
52702  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
52703  if( !z ){
52704    sqlite3VdbeMemSetNull(pMem);
52705    return SQLITE_OK;
52706  }
52707
52708  if( pMem->db ){
52709    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
52710  }else{
52711    iLimit = SQLITE_MAX_LENGTH;
52712  }
52713  flags = (enc==0?MEM_Blob:MEM_Str);
52714  if( nByte<0 ){
52715    assert( enc!=0 );
52716    if( enc==SQLITE_UTF8 ){
52717      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
52718    }else{
52719      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
52720    }
52721    flags |= MEM_Term;
52722  }
52723
52724  /* The following block sets the new values of Mem.z and Mem.xDel. It
52725  ** also sets a flag in local variable "flags" to indicate the memory
52726  ** management (one of MEM_Dyn or MEM_Static).
52727  */
52728  if( xDel==SQLITE_TRANSIENT ){
52729    int nAlloc = nByte;
52730    if( flags&MEM_Term ){
52731      nAlloc += (enc==SQLITE_UTF8?1:2);
52732    }
52733    if( nByte>iLimit ){
52734      return SQLITE_TOOBIG;
52735    }
52736    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
52737      return SQLITE_NOMEM;
52738    }
52739    memcpy(pMem->z, z, nAlloc);
52740  }else if( xDel==SQLITE_DYNAMIC ){
52741    sqlite3VdbeMemRelease(pMem);
52742    pMem->zMalloc = pMem->z = (char *)z;
52743    pMem->xDel = 0;
52744  }else{
52745    sqlite3VdbeMemRelease(pMem);
52746    pMem->z = (char *)z;
52747    pMem->xDel = xDel;
52748    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
52749  }
52750
52751  pMem->n = nByte;
52752  pMem->flags = flags;
52753  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
52754  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
52755
52756#ifndef SQLITE_OMIT_UTF16
52757  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
52758    return SQLITE_NOMEM;
52759  }
52760#endif
52761
52762  if( nByte>iLimit ){
52763    return SQLITE_TOOBIG;
52764  }
52765
52766  return SQLITE_OK;
52767}
52768
52769/*
52770** Compare the values contained by the two memory cells, returning
52771** negative, zero or positive if pMem1 is less than, equal to, or greater
52772** than pMem2. Sorting order is NULL's first, followed by numbers (integers
52773** and reals) sorted numerically, followed by text ordered by the collating
52774** sequence pColl and finally blob's ordered by memcmp().
52775**
52776** Two NULL values are considered equal by this function.
52777*/
52778SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
52779  int rc;
52780  int f1, f2;
52781  int combined_flags;
52782
52783  f1 = pMem1->flags;
52784  f2 = pMem2->flags;
52785  combined_flags = f1|f2;
52786  assert( (combined_flags & MEM_RowSet)==0 );
52787
52788  /* If one value is NULL, it is less than the other. If both values
52789  ** are NULL, return 0.
52790  */
52791  if( combined_flags&MEM_Null ){
52792    return (f2&MEM_Null) - (f1&MEM_Null);
52793  }
52794
52795  /* If one value is a number and the other is not, the number is less.
52796  ** If both are numbers, compare as reals if one is a real, or as integers
52797  ** if both values are integers.
52798  */
52799  if( combined_flags&(MEM_Int|MEM_Real) ){
52800    if( !(f1&(MEM_Int|MEM_Real)) ){
52801      return 1;
52802    }
52803    if( !(f2&(MEM_Int|MEM_Real)) ){
52804      return -1;
52805    }
52806    if( (f1 & f2 & MEM_Int)==0 ){
52807      double r1, r2;
52808      if( (f1&MEM_Real)==0 ){
52809        r1 = (double)pMem1->u.i;
52810      }else{
52811        r1 = pMem1->r;
52812      }
52813      if( (f2&MEM_Real)==0 ){
52814        r2 = (double)pMem2->u.i;
52815      }else{
52816        r2 = pMem2->r;
52817      }
52818      if( r1<r2 ) return -1;
52819      if( r1>r2 ) return 1;
52820      return 0;
52821    }else{
52822      assert( f1&MEM_Int );
52823      assert( f2&MEM_Int );
52824      if( pMem1->u.i < pMem2->u.i ) return -1;
52825      if( pMem1->u.i > pMem2->u.i ) return 1;
52826      return 0;
52827    }
52828  }
52829
52830  /* If one value is a string and the other is a blob, the string is less.
52831  ** If both are strings, compare using the collating functions.
52832  */
52833  if( combined_flags&MEM_Str ){
52834    if( (f1 & MEM_Str)==0 ){
52835      return 1;
52836    }
52837    if( (f2 & MEM_Str)==0 ){
52838      return -1;
52839    }
52840
52841    assert( pMem1->enc==pMem2->enc );
52842    assert( pMem1->enc==SQLITE_UTF8 ||
52843            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
52844
52845    /* The collation sequence must be defined at this point, even if
52846    ** the user deletes the collation sequence after the vdbe program is
52847    ** compiled (this was not always the case).
52848    */
52849    assert( !pColl || pColl->xCmp );
52850
52851    if( pColl ){
52852      if( pMem1->enc==pColl->enc ){
52853        /* The strings are already in the correct encoding.  Call the
52854        ** comparison function directly */
52855        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
52856      }else{
52857        const void *v1, *v2;
52858        int n1, n2;
52859        Mem c1;
52860        Mem c2;
52861        memset(&c1, 0, sizeof(c1));
52862        memset(&c2, 0, sizeof(c2));
52863        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
52864        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
52865        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
52866        n1 = v1==0 ? 0 : c1.n;
52867        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
52868        n2 = v2==0 ? 0 : c2.n;
52869        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
52870        sqlite3VdbeMemRelease(&c1);
52871        sqlite3VdbeMemRelease(&c2);
52872        return rc;
52873      }
52874    }
52875    /* If a NULL pointer was passed as the collate function, fall through
52876    ** to the blob case and use memcmp().  */
52877  }
52878
52879  /* Both values must be blobs.  Compare using memcmp().  */
52880  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
52881  if( rc==0 ){
52882    rc = pMem1->n - pMem2->n;
52883  }
52884  return rc;
52885}
52886
52887/*
52888** Move data out of a btree key or data field and into a Mem structure.
52889** The data or key is taken from the entry that pCur is currently pointing
52890** to.  offset and amt determine what portion of the data or key to retrieve.
52891** key is true to get the key or false to get data.  The result is written
52892** into the pMem element.
52893**
52894** The pMem structure is assumed to be uninitialized.  Any prior content
52895** is overwritten without being freed.
52896**
52897** If this routine fails for any reason (malloc returns NULL or unable
52898** to read from the disk) then the pMem is left in an inconsistent state.
52899*/
52900SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
52901  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
52902  int offset,       /* Offset from the start of data to return bytes from. */
52903  int amt,          /* Number of bytes to return. */
52904  int key,          /* If true, retrieve from the btree key, not data. */
52905  Mem *pMem         /* OUT: Return data in this Mem structure. */
52906){
52907  char *zData;        /* Data from the btree layer */
52908  int available = 0;  /* Number of bytes available on the local btree page */
52909  int rc = SQLITE_OK; /* Return code */
52910
52911  assert( sqlite3BtreeCursorIsValid(pCur) );
52912
52913  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
52914  ** that both the BtShared and database handle mutexes are held. */
52915  assert( (pMem->flags & MEM_RowSet)==0 );
52916  if( key ){
52917    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
52918  }else{
52919    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
52920  }
52921  assert( zData!=0 );
52922
52923  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
52924    sqlite3VdbeMemRelease(pMem);
52925    pMem->z = &zData[offset];
52926    pMem->flags = MEM_Blob|MEM_Ephem;
52927  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
52928    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
52929    pMem->enc = 0;
52930    pMem->type = SQLITE_BLOB;
52931    if( key ){
52932      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
52933    }else{
52934      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
52935    }
52936    pMem->z[amt] = 0;
52937    pMem->z[amt+1] = 0;
52938    if( rc!=SQLITE_OK ){
52939      sqlite3VdbeMemRelease(pMem);
52940    }
52941  }
52942  pMem->n = amt;
52943
52944  return rc;
52945}
52946
52947/* This function is only available internally, it is not part of the
52948** external API. It works in a similar way to sqlite3_value_text(),
52949** except the data returned is in the encoding specified by the second
52950** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
52951** SQLITE_UTF8.
52952**
52953** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
52954** If that is the case, then the result must be aligned on an even byte
52955** boundary.
52956*/
52957SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
52958  if( !pVal ) return 0;
52959
52960  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
52961  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
52962  assert( (pVal->flags & MEM_RowSet)==0 );
52963
52964  if( pVal->flags&MEM_Null ){
52965    return 0;
52966  }
52967  assert( (MEM_Blob>>3) == MEM_Str );
52968  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
52969  expandBlob(pVal);
52970  if( pVal->flags&MEM_Str ){
52971    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
52972    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
52973      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
52974      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
52975        return 0;
52976      }
52977    }
52978    sqlite3VdbeMemNulTerminate(pVal);
52979  }else{
52980    assert( (pVal->flags&MEM_Blob)==0 );
52981    sqlite3VdbeMemStringify(pVal, enc);
52982    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
52983  }
52984  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
52985              || pVal->db->mallocFailed );
52986  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
52987    return pVal->z;
52988  }else{
52989    return 0;
52990  }
52991}
52992
52993/*
52994** Create a new sqlite3_value object.
52995*/
52996SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
52997  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
52998  if( p ){
52999    p->flags = MEM_Null;
53000    p->type = SQLITE_NULL;
53001    p->db = db;
53002  }
53003  return p;
53004}
53005
53006/*
53007** Create a new sqlite3_value object, containing the value of pExpr.
53008**
53009** This only works for very simple expressions that consist of one constant
53010** token (i.e. "5", "5.1", "'a string'"). If the expression can
53011** be converted directly into a value, then the value is allocated and
53012** a pointer written to *ppVal. The caller is responsible for deallocating
53013** the value by passing it to sqlite3ValueFree() later on. If the expression
53014** cannot be converted to a value, then *ppVal is set to NULL.
53015*/
53016SQLITE_PRIVATE int sqlite3ValueFromExpr(
53017  sqlite3 *db,              /* The database connection */
53018  Expr *pExpr,              /* The expression to evaluate */
53019  u8 enc,                   /* Encoding to use */
53020  u8 affinity,              /* Affinity to use */
53021  sqlite3_value **ppVal     /* Write the new value here */
53022){
53023  int op;
53024  char *zVal = 0;
53025  sqlite3_value *pVal = 0;
53026
53027  if( !pExpr ){
53028    *ppVal = 0;
53029    return SQLITE_OK;
53030  }
53031  op = pExpr->op;
53032
53033  /* op can only be TK_REGISTER is we have compiled with SQLITE_ENABLE_STAT2.
53034  ** The ifdef here is to enable us to achieve 100% branch test coverage even
53035  ** when SQLITE_ENABLE_STAT2 is omitted.
53036  */
53037#ifdef SQLITE_ENABLE_STAT2
53038  if( op==TK_REGISTER ) op = pExpr->op2;
53039#else
53040  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
53041#endif
53042
53043  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
53044    pVal = sqlite3ValueNew(db);
53045    if( pVal==0 ) goto no_mem;
53046    if( ExprHasProperty(pExpr, EP_IntValue) ){
53047      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
53048    }else{
53049      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
53050      if( zVal==0 ) goto no_mem;
53051      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
53052      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
53053    }
53054    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
53055      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
53056    }else{
53057      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
53058    }
53059    if( enc!=SQLITE_UTF8 ){
53060      sqlite3VdbeChangeEncoding(pVal, enc);
53061    }
53062  }else if( op==TK_UMINUS ) {
53063    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
53064      pVal->u.i = -1 * pVal->u.i;
53065      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
53066      pVal->r = (double)-1 * pVal->r;
53067    }
53068  }
53069#ifndef SQLITE_OMIT_BLOB_LITERAL
53070  else if( op==TK_BLOB ){
53071    int nVal;
53072    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
53073    assert( pExpr->u.zToken[1]=='\'' );
53074    pVal = sqlite3ValueNew(db);
53075    if( !pVal ) goto no_mem;
53076    zVal = &pExpr->u.zToken[2];
53077    nVal = sqlite3Strlen30(zVal)-1;
53078    assert( zVal[nVal]=='\'' );
53079    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
53080                         0, SQLITE_DYNAMIC);
53081  }
53082#endif
53083
53084  if( pVal ){
53085    sqlite3VdbeMemStoreType(pVal);
53086  }
53087  *ppVal = pVal;
53088  return SQLITE_OK;
53089
53090no_mem:
53091  db->mallocFailed = 1;
53092  sqlite3DbFree(db, zVal);
53093  sqlite3ValueFree(pVal);
53094  *ppVal = 0;
53095  return SQLITE_NOMEM;
53096}
53097
53098/*
53099** Change the string value of an sqlite3_value object
53100*/
53101SQLITE_PRIVATE void sqlite3ValueSetStr(
53102  sqlite3_value *v,     /* Value to be set */
53103  int n,                /* Length of string z */
53104  const void *z,        /* Text of the new string */
53105  u8 enc,               /* Encoding to use */
53106  void (*xDel)(void*)   /* Destructor for the string */
53107){
53108  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
53109}
53110
53111/*
53112** Free an sqlite3_value object
53113*/
53114SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
53115  if( !v ) return;
53116  sqlite3VdbeMemRelease((Mem *)v);
53117  sqlite3DbFree(((Mem*)v)->db, v);
53118}
53119
53120/*
53121** Return the number of bytes in the sqlite3_value object assuming
53122** that it uses the encoding "enc"
53123*/
53124SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
53125  Mem *p = (Mem*)pVal;
53126  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
53127    if( p->flags & MEM_Zero ){
53128      return p->n + p->u.nZero;
53129    }else{
53130      return p->n;
53131    }
53132  }
53133  return 0;
53134}
53135
53136/************** End of vdbemem.c *********************************************/
53137/************** Begin file vdbeaux.c *****************************************/
53138/*
53139** 2003 September 6
53140**
53141** The author disclaims copyright to this source code.  In place of
53142** a legal notice, here is a blessing:
53143**
53144**    May you do good and not evil.
53145**    May you find forgiveness for yourself and forgive others.
53146**    May you share freely, never taking more than you give.
53147**
53148*************************************************************************
53149** This file contains code used for creating, destroying, and populating
53150** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
53151** to version 2.8.7, all this code was combined into the vdbe.c source file.
53152** But that file was getting too big so this subroutines were split out.
53153*/
53154
53155
53156
53157/*
53158** When debugging the code generator in a symbolic debugger, one can
53159** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
53160** as they are added to the instruction stream.
53161*/
53162#ifdef SQLITE_DEBUG
53163SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
53164#endif
53165
53166
53167/*
53168** Create a new virtual database engine.
53169*/
53170SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
53171  Vdbe *p;
53172  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
53173  if( p==0 ) return 0;
53174  p->db = db;
53175  if( db->pVdbe ){
53176    db->pVdbe->pPrev = p;
53177  }
53178  p->pNext = db->pVdbe;
53179  p->pPrev = 0;
53180  db->pVdbe = p;
53181  p->magic = VDBE_MAGIC_INIT;
53182  return p;
53183}
53184
53185/*
53186** Remember the SQL string for a prepared statement.
53187*/
53188SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
53189  assert( isPrepareV2==1 || isPrepareV2==0 );
53190  if( p==0 ) return;
53191#ifdef SQLITE_OMIT_TRACE
53192  if( !isPrepareV2 ) return;
53193#endif
53194  assert( p->zSql==0 );
53195  p->zSql = sqlite3DbStrNDup(p->db, z, n);
53196  p->isPrepareV2 = (u8)isPrepareV2;
53197}
53198
53199/*
53200** Return the SQL associated with a prepared statement
53201*/
53202SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
53203  Vdbe *p = (Vdbe *)pStmt;
53204  return (p && p->isPrepareV2) ? p->zSql : 0;
53205}
53206
53207/*
53208** Swap all content between two VDBE structures.
53209*/
53210SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
53211  Vdbe tmp, *pTmp;
53212  char *zTmp;
53213  tmp = *pA;
53214  *pA = *pB;
53215  *pB = tmp;
53216  pTmp = pA->pNext;
53217  pA->pNext = pB->pNext;
53218  pB->pNext = pTmp;
53219  pTmp = pA->pPrev;
53220  pA->pPrev = pB->pPrev;
53221  pB->pPrev = pTmp;
53222  zTmp = pA->zSql;
53223  pA->zSql = pB->zSql;
53224  pB->zSql = zTmp;
53225  pB->isPrepareV2 = pA->isPrepareV2;
53226}
53227
53228#ifdef SQLITE_DEBUG
53229/*
53230** Turn tracing on or off
53231*/
53232SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
53233  p->trace = trace;
53234}
53235#endif
53236
53237/*
53238** Resize the Vdbe.aOp array so that it is at least one op larger than
53239** it was.
53240**
53241** If an out-of-memory error occurs while resizing the array, return
53242** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
53243** unchanged (this is so that any opcodes already allocated can be
53244** correctly deallocated along with the rest of the Vdbe).
53245*/
53246static int growOpArray(Vdbe *p){
53247  VdbeOp *pNew;
53248  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
53249  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
53250  if( pNew ){
53251    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
53252    p->aOp = pNew;
53253  }
53254  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
53255}
53256
53257/*
53258** Add a new instruction to the list of instructions current in the
53259** VDBE.  Return the address of the new instruction.
53260**
53261** Parameters:
53262**
53263**    p               Pointer to the VDBE
53264**
53265**    op              The opcode for this instruction
53266**
53267**    p1, p2, p3      Operands
53268**
53269** Use the sqlite3VdbeResolveLabel() function to fix an address and
53270** the sqlite3VdbeChangeP4() function to change the value of the P4
53271** operand.
53272*/
53273SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
53274  int i;
53275  VdbeOp *pOp;
53276
53277  i = p->nOp;
53278  assert( p->magic==VDBE_MAGIC_INIT );
53279  assert( op>0 && op<0xff );
53280  if( p->nOpAlloc<=i ){
53281    if( growOpArray(p) ){
53282      return 1;
53283    }
53284  }
53285  p->nOp++;
53286  pOp = &p->aOp[i];
53287  pOp->opcode = (u8)op;
53288  pOp->p5 = 0;
53289  pOp->p1 = p1;
53290  pOp->p2 = p2;
53291  pOp->p3 = p3;
53292  pOp->p4.p = 0;
53293  pOp->p4type = P4_NOTUSED;
53294  p->expired = 0;
53295#ifdef SQLITE_DEBUG
53296  pOp->zComment = 0;
53297  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
53298#endif
53299#ifdef VDBE_PROFILE
53300  pOp->cycles = 0;
53301  pOp->cnt = 0;
53302#endif
53303  return i;
53304}
53305SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
53306  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
53307}
53308SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
53309  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
53310}
53311SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
53312  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
53313}
53314
53315
53316/*
53317** Add an opcode that includes the p4 value as a pointer.
53318*/
53319SQLITE_PRIVATE int sqlite3VdbeAddOp4(
53320  Vdbe *p,            /* Add the opcode to this VM */
53321  int op,             /* The new opcode */
53322  int p1,             /* The P1 operand */
53323  int p2,             /* The P2 operand */
53324  int p3,             /* The P3 operand */
53325  const char *zP4,    /* The P4 operand */
53326  int p4type          /* P4 operand type */
53327){
53328  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53329  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
53330  return addr;
53331}
53332
53333/*
53334** Add an opcode that includes the p4 value as an integer.
53335*/
53336SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
53337  Vdbe *p,            /* Add the opcode to this VM */
53338  int op,             /* The new opcode */
53339  int p1,             /* The P1 operand */
53340  int p2,             /* The P2 operand */
53341  int p3,             /* The P3 operand */
53342  int p4              /* The P4 operand as an integer */
53343){
53344  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53345  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
53346  return addr;
53347}
53348
53349/*
53350** Create a new symbolic label for an instruction that has yet to be
53351** coded.  The symbolic label is really just a negative number.  The
53352** label can be used as the P2 value of an operation.  Later, when
53353** the label is resolved to a specific address, the VDBE will scan
53354** through its operation list and change all values of P2 which match
53355** the label into the resolved address.
53356**
53357** The VDBE knows that a P2 value is a label because labels are
53358** always negative and P2 values are suppose to be non-negative.
53359** Hence, a negative P2 value is a label that has yet to be resolved.
53360**
53361** Zero is returned if a malloc() fails.
53362*/
53363SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
53364  int i;
53365  i = p->nLabel++;
53366  assert( p->magic==VDBE_MAGIC_INIT );
53367  if( i>=p->nLabelAlloc ){
53368    int n = p->nLabelAlloc*2 + 5;
53369    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
53370                                       n*sizeof(p->aLabel[0]));
53371    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
53372  }
53373  if( p->aLabel ){
53374    p->aLabel[i] = -1;
53375  }
53376  return -1-i;
53377}
53378
53379/*
53380** Resolve label "x" to be the address of the next instruction to
53381** be inserted.  The parameter "x" must have been obtained from
53382** a prior call to sqlite3VdbeMakeLabel().
53383*/
53384SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
53385  int j = -1-x;
53386  assert( p->magic==VDBE_MAGIC_INIT );
53387  assert( j>=0 && j<p->nLabel );
53388  if( p->aLabel ){
53389    p->aLabel[j] = p->nOp;
53390  }
53391}
53392
53393/*
53394** Mark the VDBE as one that can only be run one time.
53395*/
53396SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
53397  p->runOnlyOnce = 1;
53398}
53399
53400#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
53401
53402/*
53403** The following type and function are used to iterate through all opcodes
53404** in a Vdbe main program and each of the sub-programs (triggers) it may
53405** invoke directly or indirectly. It should be used as follows:
53406**
53407**   Op *pOp;
53408**   VdbeOpIter sIter;
53409**
53410**   memset(&sIter, 0, sizeof(sIter));
53411**   sIter.v = v;                            // v is of type Vdbe*
53412**   while( (pOp = opIterNext(&sIter)) ){
53413**     // Do something with pOp
53414**   }
53415**   sqlite3DbFree(v->db, sIter.apSub);
53416**
53417*/
53418typedef struct VdbeOpIter VdbeOpIter;
53419struct VdbeOpIter {
53420  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
53421  SubProgram **apSub;        /* Array of subprograms */
53422  int nSub;                  /* Number of entries in apSub */
53423  int iAddr;                 /* Address of next instruction to return */
53424  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
53425};
53426static Op *opIterNext(VdbeOpIter *p){
53427  Vdbe *v = p->v;
53428  Op *pRet = 0;
53429  Op *aOp;
53430  int nOp;
53431
53432  if( p->iSub<=p->nSub ){
53433
53434    if( p->iSub==0 ){
53435      aOp = v->aOp;
53436      nOp = v->nOp;
53437    }else{
53438      aOp = p->apSub[p->iSub-1]->aOp;
53439      nOp = p->apSub[p->iSub-1]->nOp;
53440    }
53441    assert( p->iAddr<nOp );
53442
53443    pRet = &aOp[p->iAddr];
53444    p->iAddr++;
53445    if( p->iAddr==nOp ){
53446      p->iSub++;
53447      p->iAddr = 0;
53448    }
53449
53450    if( pRet->p4type==P4_SUBPROGRAM ){
53451      int nByte = (p->nSub+1)*sizeof(SubProgram*);
53452      int j;
53453      for(j=0; j<p->nSub; j++){
53454        if( p->apSub[j]==pRet->p4.pProgram ) break;
53455      }
53456      if( j==p->nSub ){
53457        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
53458        if( !p->apSub ){
53459          pRet = 0;
53460        }else{
53461          p->apSub[p->nSub++] = pRet->p4.pProgram;
53462        }
53463      }
53464    }
53465  }
53466
53467  return pRet;
53468}
53469
53470/*
53471** Check if the program stored in the VM associated with pParse may
53472** throw an ABORT exception (causing the statement, but not entire transaction
53473** to be rolled back). This condition is true if the main program or any
53474** sub-programs contains any of the following:
53475**
53476**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53477**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53478**   *  OP_Destroy
53479**   *  OP_VUpdate
53480**   *  OP_VRename
53481**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
53482**
53483** Then check that the value of Parse.mayAbort is true if an
53484** ABORT may be thrown, or false otherwise. Return true if it does
53485** match, or false otherwise. This function is intended to be used as
53486** part of an assert statement in the compiler. Similar to:
53487**
53488**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
53489*/
53490SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
53491  int hasAbort = 0;
53492  Op *pOp;
53493  VdbeOpIter sIter;
53494  memset(&sIter, 0, sizeof(sIter));
53495  sIter.v = v;
53496
53497  while( (pOp = opIterNext(&sIter))!=0 ){
53498    int opcode = pOp->opcode;
53499    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
53500#ifndef SQLITE_OMIT_FOREIGN_KEY
53501     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
53502#endif
53503     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
53504      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
53505    ){
53506      hasAbort = 1;
53507      break;
53508    }
53509  }
53510  sqlite3DbFree(v->db, sIter.apSub);
53511
53512  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
53513  ** If malloc failed, then the while() loop above may not have iterated
53514  ** through all opcodes and hasAbort may be set incorrectly. Return
53515  ** true for this case to prevent the assert() in the callers frame
53516  ** from failing.  */
53517  return ( v->db->mallocFailed || hasAbort==mayAbort );
53518}
53519#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
53520
53521/*
53522** Loop through the program looking for P2 values that are negative
53523** on jump instructions.  Each such value is a label.  Resolve the
53524** label by setting the P2 value to its correct non-zero value.
53525**
53526** This routine is called once after all opcodes have been inserted.
53527**
53528** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
53529** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
53530** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
53531**
53532** The Op.opflags field is set on all opcodes.
53533*/
53534static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
53535  int i;
53536  int nMaxArgs = *pMaxFuncArgs;
53537  Op *pOp;
53538  int *aLabel = p->aLabel;
53539  p->readOnly = 1;
53540  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
53541    u8 opcode = pOp->opcode;
53542
53543    pOp->opflags = sqlite3OpcodeProperty[opcode];
53544    if( opcode==OP_Function || opcode==OP_AggStep ){
53545      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
53546    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
53547      p->readOnly = 0;
53548#ifndef SQLITE_OMIT_VIRTUALTABLE
53549    }else if( opcode==OP_VUpdate ){
53550      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
53551    }else if( opcode==OP_VFilter ){
53552      int n;
53553      assert( p->nOp - i >= 3 );
53554      assert( pOp[-1].opcode==OP_Integer );
53555      n = pOp[-1].p1;
53556      if( n>nMaxArgs ) nMaxArgs = n;
53557#endif
53558    }
53559
53560    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
53561      assert( -1-pOp->p2<p->nLabel );
53562      pOp->p2 = aLabel[-1-pOp->p2];
53563    }
53564  }
53565  sqlite3DbFree(p->db, p->aLabel);
53566  p->aLabel = 0;
53567
53568  *pMaxFuncArgs = nMaxArgs;
53569}
53570
53571/*
53572** Return the address of the next instruction to be inserted.
53573*/
53574SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
53575  assert( p->magic==VDBE_MAGIC_INIT );
53576  return p->nOp;
53577}
53578
53579/*
53580** This function returns a pointer to the array of opcodes associated with
53581** the Vdbe passed as the first argument. It is the callers responsibility
53582** to arrange for the returned array to be eventually freed using the
53583** vdbeFreeOpArray() function.
53584**
53585** Before returning, *pnOp is set to the number of entries in the returned
53586** array. Also, *pnMaxArg is set to the larger of its current value and
53587** the number of entries in the Vdbe.apArg[] array required to execute the
53588** returned program.
53589*/
53590SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
53591  VdbeOp *aOp = p->aOp;
53592  assert( aOp && !p->db->mallocFailed );
53593
53594  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
53595  assert( p->aMutex.nMutex==0 );
53596
53597  resolveP2Values(p, pnMaxArg);
53598  *pnOp = p->nOp;
53599  p->aOp = 0;
53600  return aOp;
53601}
53602
53603/*
53604** Add a whole list of operations to the operation stack.  Return the
53605** address of the first operation added.
53606*/
53607SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
53608  int addr;
53609  assert( p->magic==VDBE_MAGIC_INIT );
53610  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
53611    return 0;
53612  }
53613  addr = p->nOp;
53614  if( ALWAYS(nOp>0) ){
53615    int i;
53616    VdbeOpList const *pIn = aOp;
53617    for(i=0; i<nOp; i++, pIn++){
53618      int p2 = pIn->p2;
53619      VdbeOp *pOut = &p->aOp[i+addr];
53620      pOut->opcode = pIn->opcode;
53621      pOut->p1 = pIn->p1;
53622      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
53623        pOut->p2 = addr + ADDR(p2);
53624      }else{
53625        pOut->p2 = p2;
53626      }
53627      pOut->p3 = pIn->p3;
53628      pOut->p4type = P4_NOTUSED;
53629      pOut->p4.p = 0;
53630      pOut->p5 = 0;
53631#ifdef SQLITE_DEBUG
53632      pOut->zComment = 0;
53633      if( sqlite3VdbeAddopTrace ){
53634        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
53635      }
53636#endif
53637    }
53638    p->nOp += nOp;
53639  }
53640  return addr;
53641}
53642
53643/*
53644** Change the value of the P1 operand for a specific instruction.
53645** This routine is useful when a large program is loaded from a
53646** static array using sqlite3VdbeAddOpList but we want to make a
53647** few minor changes to the program.
53648*/
53649SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
53650  assert( p!=0 );
53651  assert( addr>=0 );
53652  if( p->nOp>addr ){
53653    p->aOp[addr].p1 = val;
53654  }
53655}
53656
53657/*
53658** Change the value of the P2 operand for a specific instruction.
53659** This routine is useful for setting a jump destination.
53660*/
53661SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
53662  assert( p!=0 );
53663  assert( addr>=0 );
53664  if( p->nOp>addr ){
53665    p->aOp[addr].p2 = val;
53666  }
53667}
53668
53669/*
53670** Change the value of the P3 operand for a specific instruction.
53671*/
53672SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
53673  assert( p!=0 );
53674  assert( addr>=0 );
53675  if( p->nOp>addr ){
53676    p->aOp[addr].p3 = val;
53677  }
53678}
53679
53680/*
53681** Change the value of the P5 operand for the most recently
53682** added operation.
53683*/
53684SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
53685  assert( p!=0 );
53686  if( p->aOp ){
53687    assert( p->nOp>0 );
53688    p->aOp[p->nOp-1].p5 = val;
53689  }
53690}
53691
53692/*
53693** Change the P2 operand of instruction addr so that it points to
53694** the address of the next instruction to be coded.
53695*/
53696SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
53697  sqlite3VdbeChangeP2(p, addr, p->nOp);
53698}
53699
53700
53701/*
53702** If the input FuncDef structure is ephemeral, then free it.  If
53703** the FuncDef is not ephermal, then do nothing.
53704*/
53705static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
53706  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
53707    sqlite3DbFree(db, pDef);
53708  }
53709}
53710
53711/*
53712** Delete a P4 value if necessary.
53713*/
53714static void freeP4(sqlite3 *db, int p4type, void *p4){
53715  if( p4 ){
53716    switch( p4type ){
53717      case P4_REAL:
53718      case P4_INT64:
53719      case P4_MPRINTF:
53720      case P4_DYNAMIC:
53721      case P4_KEYINFO:
53722      case P4_INTARRAY:
53723      case P4_KEYINFO_HANDOFF: {
53724        sqlite3DbFree(db, p4);
53725        break;
53726      }
53727      case P4_VDBEFUNC: {
53728        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
53729        freeEphemeralFunction(db, pVdbeFunc->pFunc);
53730        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
53731        sqlite3DbFree(db, pVdbeFunc);
53732        break;
53733      }
53734      case P4_FUNCDEF: {
53735        freeEphemeralFunction(db, (FuncDef*)p4);
53736        break;
53737      }
53738      case P4_MEM: {
53739        sqlite3ValueFree((sqlite3_value*)p4);
53740        break;
53741      }
53742      case P4_VTAB : {
53743        sqlite3VtabUnlock((VTable *)p4);
53744        break;
53745      }
53746      case P4_SUBPROGRAM : {
53747        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
53748        break;
53749      }
53750    }
53751  }
53752}
53753
53754/*
53755** Free the space allocated for aOp and any p4 values allocated for the
53756** opcodes contained within. If aOp is not NULL it is assumed to contain
53757** nOp entries.
53758*/
53759static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
53760  if( aOp ){
53761    Op *pOp;
53762    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
53763      freeP4(db, pOp->p4type, pOp->p4.p);
53764#ifdef SQLITE_DEBUG
53765      sqlite3DbFree(db, pOp->zComment);
53766#endif
53767    }
53768  }
53769  sqlite3DbFree(db, aOp);
53770}
53771
53772/*
53773** Decrement the ref-count on the SubProgram structure passed as the
53774** second argument. If the ref-count reaches zero, free the structure.
53775**
53776** The array of VDBE opcodes stored as SubProgram.aOp is freed if
53777** either the ref-count reaches zero or parameter freeop is non-zero.
53778**
53779** Since the array of opcodes pointed to by SubProgram.aOp may directly
53780** or indirectly contain a reference to the SubProgram structure itself.
53781** By passing a non-zero freeop parameter, the caller may ensure that all
53782** SubProgram structures and their aOp arrays are freed, even when there
53783** are such circular references.
53784*/
53785SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
53786  if( p ){
53787    assert( p->nRef>0 );
53788    if( freeop || p->nRef==1 ){
53789      Op *aOp = p->aOp;
53790      p->aOp = 0;
53791      vdbeFreeOpArray(db, aOp, p->nOp);
53792      p->nOp = 0;
53793    }
53794    p->nRef--;
53795    if( p->nRef==0 ){
53796      sqlite3DbFree(db, p);
53797    }
53798  }
53799}
53800
53801
53802/*
53803** Change N opcodes starting at addr to No-ops.
53804*/
53805SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
53806  if( p->aOp ){
53807    VdbeOp *pOp = &p->aOp[addr];
53808    sqlite3 *db = p->db;
53809    while( N-- ){
53810      freeP4(db, pOp->p4type, pOp->p4.p);
53811      memset(pOp, 0, sizeof(pOp[0]));
53812      pOp->opcode = OP_Noop;
53813      pOp++;
53814    }
53815  }
53816}
53817
53818/*
53819** Change the value of the P4 operand for a specific instruction.
53820** This routine is useful when a large program is loaded from a
53821** static array using sqlite3VdbeAddOpList but we want to make a
53822** few minor changes to the program.
53823**
53824** If n>=0 then the P4 operand is dynamic, meaning that a copy of
53825** the string is made into memory obtained from sqlite3_malloc().
53826** A value of n==0 means copy bytes of zP4 up to and including the
53827** first null byte.  If n>0 then copy n+1 bytes of zP4.
53828**
53829** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
53830** A copy is made of the KeyInfo structure into memory obtained from
53831** sqlite3_malloc, to be freed when the Vdbe is finalized.
53832** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
53833** stored in memory that the caller has obtained from sqlite3_malloc. The
53834** caller should not free the allocation, it will be freed when the Vdbe is
53835** finalized.
53836**
53837** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
53838** to a string or structure that is guaranteed to exist for the lifetime of
53839** the Vdbe. In these cases we can just copy the pointer.
53840**
53841** If addr<0 then change P4 on the most recently inserted instruction.
53842*/
53843SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
53844  Op *pOp;
53845  sqlite3 *db;
53846  assert( p!=0 );
53847  db = p->db;
53848  assert( p->magic==VDBE_MAGIC_INIT );
53849  if( p->aOp==0 || db->mallocFailed ){
53850    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
53851      freeP4(db, n, (void*)*(char**)&zP4);
53852    }
53853    return;
53854  }
53855  assert( p->nOp>0 );
53856  assert( addr<p->nOp );
53857  if( addr<0 ){
53858    addr = p->nOp - 1;
53859  }
53860  pOp = &p->aOp[addr];
53861  freeP4(db, pOp->p4type, pOp->p4.p);
53862  pOp->p4.p = 0;
53863  if( n==P4_INT32 ){
53864    /* Note: this cast is safe, because the origin data point was an int
53865    ** that was cast to a (const char *). */
53866    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
53867    pOp->p4type = P4_INT32;
53868  }else if( zP4==0 ){
53869    pOp->p4.p = 0;
53870    pOp->p4type = P4_NOTUSED;
53871  }else if( n==P4_KEYINFO ){
53872    KeyInfo *pKeyInfo;
53873    int nField, nByte;
53874
53875    nField = ((KeyInfo*)zP4)->nField;
53876    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
53877    pKeyInfo = sqlite3Malloc( nByte );
53878    pOp->p4.pKeyInfo = pKeyInfo;
53879    if( pKeyInfo ){
53880      u8 *aSortOrder;
53881      memcpy((char*)pKeyInfo, zP4, nByte - nField);
53882      aSortOrder = pKeyInfo->aSortOrder;
53883      if( aSortOrder ){
53884        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
53885        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
53886      }
53887      pOp->p4type = P4_KEYINFO;
53888    }else{
53889      p->db->mallocFailed = 1;
53890      pOp->p4type = P4_NOTUSED;
53891    }
53892  }else if( n==P4_KEYINFO_HANDOFF ){
53893    pOp->p4.p = (void*)zP4;
53894    pOp->p4type = P4_KEYINFO;
53895  }else if( n==P4_VTAB ){
53896    pOp->p4.p = (void*)zP4;
53897    pOp->p4type = P4_VTAB;
53898    sqlite3VtabLock((VTable *)zP4);
53899    assert( ((VTable *)zP4)->db==p->db );
53900  }else if( n<0 ){
53901    pOp->p4.p = (void*)zP4;
53902    pOp->p4type = (signed char)n;
53903  }else{
53904    if( n==0 ) n = sqlite3Strlen30(zP4);
53905    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
53906    pOp->p4type = P4_DYNAMIC;
53907  }
53908}
53909
53910#ifndef NDEBUG
53911/*
53912** Change the comment on the the most recently coded instruction.  Or
53913** insert a No-op and add the comment to that new instruction.  This
53914** makes the code easier to read during debugging.  None of this happens
53915** in a production build.
53916*/
53917SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
53918  va_list ap;
53919  if( !p ) return;
53920  assert( p->nOp>0 || p->aOp==0 );
53921  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
53922  if( p->nOp ){
53923    char **pz = &p->aOp[p->nOp-1].zComment;
53924    va_start(ap, zFormat);
53925    sqlite3DbFree(p->db, *pz);
53926    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
53927    va_end(ap);
53928  }
53929}
53930SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
53931  va_list ap;
53932  if( !p ) return;
53933  sqlite3VdbeAddOp0(p, OP_Noop);
53934  assert( p->nOp>0 || p->aOp==0 );
53935  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
53936  if( p->nOp ){
53937    char **pz = &p->aOp[p->nOp-1].zComment;
53938    va_start(ap, zFormat);
53939    sqlite3DbFree(p->db, *pz);
53940    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
53941    va_end(ap);
53942  }
53943}
53944#endif  /* NDEBUG */
53945
53946/*
53947** Return the opcode for a given address.  If the address is -1, then
53948** return the most recently inserted opcode.
53949**
53950** If a memory allocation error has occurred prior to the calling of this
53951** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
53952** is readable but not writable, though it is cast to a writable value.
53953** The return of a dummy opcode allows the call to continue functioning
53954** after a OOM fault without having to check to see if the return from
53955** this routine is a valid pointer.  But because the dummy.opcode is 0,
53956** dummy will never be written to.  This is verified by code inspection and
53957** by running with Valgrind.
53958**
53959** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
53960** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
53961** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
53962** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
53963** having to double-check to make sure that the result is non-negative. But
53964** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
53965** check the value of p->nOp-1 before continuing.
53966*/
53967SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
53968  static const VdbeOp dummy;
53969  assert( p->magic==VDBE_MAGIC_INIT );
53970  if( addr<0 ){
53971#ifdef SQLITE_OMIT_TRACE
53972    if( p->nOp==0 ) return (VdbeOp*)&dummy;
53973#endif
53974    addr = p->nOp - 1;
53975  }
53976  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
53977  if( p->db->mallocFailed ){
53978    return (VdbeOp*)&dummy;
53979  }else{
53980    return &p->aOp[addr];
53981  }
53982}
53983
53984#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
53985     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
53986/*
53987** Compute a string that describes the P4 parameter for an opcode.
53988** Use zTemp for any required temporary buffer space.
53989*/
53990static char *displayP4(Op *pOp, char *zTemp, int nTemp){
53991  char *zP4 = zTemp;
53992  assert( nTemp>=20 );
53993  switch( pOp->p4type ){
53994    case P4_KEYINFO_STATIC:
53995    case P4_KEYINFO: {
53996      int i, j;
53997      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
53998      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
53999      i = sqlite3Strlen30(zTemp);
54000      for(j=0; j<pKeyInfo->nField; j++){
54001        CollSeq *pColl = pKeyInfo->aColl[j];
54002        if( pColl ){
54003          int n = sqlite3Strlen30(pColl->zName);
54004          if( i+n>nTemp-6 ){
54005            memcpy(&zTemp[i],",...",4);
54006            break;
54007          }
54008          zTemp[i++] = ',';
54009          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
54010            zTemp[i++] = '-';
54011          }
54012          memcpy(&zTemp[i], pColl->zName,n+1);
54013          i += n;
54014        }else if( i+4<nTemp-6 ){
54015          memcpy(&zTemp[i],",nil",4);
54016          i += 4;
54017        }
54018      }
54019      zTemp[i++] = ')';
54020      zTemp[i] = 0;
54021      assert( i<nTemp );
54022      break;
54023    }
54024    case P4_COLLSEQ: {
54025      CollSeq *pColl = pOp->p4.pColl;
54026      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
54027      break;
54028    }
54029    case P4_FUNCDEF: {
54030      FuncDef *pDef = pOp->p4.pFunc;
54031      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
54032      break;
54033    }
54034    case P4_INT64: {
54035      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
54036      break;
54037    }
54038    case P4_INT32: {
54039      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
54040      break;
54041    }
54042    case P4_REAL: {
54043      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
54044      break;
54045    }
54046    case P4_MEM: {
54047      Mem *pMem = pOp->p4.pMem;
54048      assert( (pMem->flags & MEM_Null)==0 );
54049      if( pMem->flags & MEM_Str ){
54050        zP4 = pMem->z;
54051      }else if( pMem->flags & MEM_Int ){
54052        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
54053      }else if( pMem->flags & MEM_Real ){
54054        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
54055      }else{
54056        assert( pMem->flags & MEM_Blob );
54057        zP4 = "(blob)";
54058      }
54059      break;
54060    }
54061#ifndef SQLITE_OMIT_VIRTUALTABLE
54062    case P4_VTAB: {
54063      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
54064      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
54065      break;
54066    }
54067#endif
54068    case P4_INTARRAY: {
54069      sqlite3_snprintf(nTemp, zTemp, "intarray");
54070      break;
54071    }
54072    case P4_SUBPROGRAM: {
54073      sqlite3_snprintf(nTemp, zTemp, "program");
54074      break;
54075    }
54076    default: {
54077      zP4 = pOp->p4.z;
54078      if( zP4==0 ){
54079        zP4 = zTemp;
54080        zTemp[0] = 0;
54081      }
54082    }
54083  }
54084  assert( zP4!=0 );
54085  return zP4;
54086}
54087#endif
54088
54089/*
54090** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
54091**
54092** The prepared statement has to know in advance which Btree objects
54093** will be used so that it can acquire mutexes on them all in sorted
54094** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
54095** in order (and released in reverse order) to avoid deadlocks.
54096*/
54097SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
54098  int mask;
54099  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
54100  assert( i<(int)sizeof(p->btreeMask)*8 );
54101  mask = ((u32)1)<<i;
54102  if( (p->btreeMask & mask)==0 ){
54103    p->btreeMask |= mask;
54104    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
54105  }
54106}
54107
54108
54109#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
54110/*
54111** Print a single opcode.  This routine is used for debugging only.
54112*/
54113SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
54114  char *zP4;
54115  char zPtr[50];
54116  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
54117  if( pOut==0 ) pOut = stdout;
54118  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
54119  fprintf(pOut, zFormat1, pc,
54120      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
54121#ifdef SQLITE_DEBUG
54122      pOp->zComment ? pOp->zComment : ""
54123#else
54124      ""
54125#endif
54126  );
54127  fflush(pOut);
54128}
54129#endif
54130
54131/*
54132** Release an array of N Mem elements
54133*/
54134static void releaseMemArray(Mem *p, int N){
54135  if( p && N ){
54136    Mem *pEnd;
54137    sqlite3 *db = p->db;
54138    u8 malloc_failed = db->mallocFailed;
54139    for(pEnd=&p[N]; p<pEnd; p++){
54140      assert( (&p[1])==pEnd || p[0].db==p[1].db );
54141
54142      /* This block is really an inlined version of sqlite3VdbeMemRelease()
54143      ** that takes advantage of the fact that the memory cell value is
54144      ** being set to NULL after releasing any dynamic resources.
54145      **
54146      ** The justification for duplicating code is that according to
54147      ** callgrind, this causes a certain test case to hit the CPU 4.7
54148      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
54149      ** sqlite3MemRelease() were called from here. With -O2, this jumps
54150      ** to 6.6 percent. The test case is inserting 1000 rows into a table
54151      ** with no indexes using a single prepared INSERT statement, bind()
54152      ** and reset(). Inserts are grouped into a transaction.
54153      */
54154      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
54155        sqlite3VdbeMemRelease(p);
54156      }else if( p->zMalloc ){
54157        sqlite3DbFree(db, p->zMalloc);
54158        p->zMalloc = 0;
54159      }
54160
54161      p->flags = MEM_Null;
54162    }
54163    db->mallocFailed = malloc_failed;
54164  }
54165}
54166
54167/*
54168** Delete a VdbeFrame object and its contents. VdbeFrame objects are
54169** allocated by the OP_Program opcode in sqlite3VdbeExec().
54170*/
54171SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
54172  int i;
54173  Mem *aMem = VdbeFrameMem(p);
54174  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
54175  for(i=0; i<p->nChildCsr; i++){
54176    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
54177  }
54178  releaseMemArray(aMem, p->nChildMem);
54179  sqlite3DbFree(p->v->db, p);
54180}
54181
54182#ifndef SQLITE_OMIT_EXPLAIN
54183/*
54184** Give a listing of the program in the virtual machine.
54185**
54186** The interface is the same as sqlite3VdbeExec().  But instead of
54187** running the code, it invokes the callback once for each instruction.
54188** This feature is used to implement "EXPLAIN".
54189**
54190** When p->explain==1, each instruction is listed.  When
54191** p->explain==2, only OP_Explain instructions are listed and these
54192** are shown in a different format.  p->explain==2 is used to implement
54193** EXPLAIN QUERY PLAN.
54194**
54195** When p->explain==1, first the main program is listed, then each of
54196** the trigger subprograms are listed one by one.
54197*/
54198SQLITE_PRIVATE int sqlite3VdbeList(
54199  Vdbe *p                   /* The VDBE */
54200){
54201  int nRow;                            /* Stop when row count reaches this */
54202  int nSub = 0;                        /* Number of sub-vdbes seen so far */
54203  SubProgram **apSub = 0;              /* Array of sub-vdbes */
54204  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
54205  sqlite3 *db = p->db;                 /* The database connection */
54206  int i;                               /* Loop counter */
54207  int rc = SQLITE_OK;                  /* Return code */
54208  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
54209
54210  assert( p->explain );
54211  assert( p->magic==VDBE_MAGIC_RUN );
54212  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
54213
54214  /* Even though this opcode does not use dynamic strings for
54215  ** the result, result columns may become dynamic if the user calls
54216  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
54217  */
54218  releaseMemArray(pMem, 8);
54219
54220  if( p->rc==SQLITE_NOMEM ){
54221    /* This happens if a malloc() inside a call to sqlite3_column_text() or
54222    ** sqlite3_column_text16() failed.  */
54223    db->mallocFailed = 1;
54224    return SQLITE_ERROR;
54225  }
54226
54227  /* When the number of output rows reaches nRow, that means the
54228  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
54229  ** nRow is the sum of the number of rows in the main program, plus
54230  ** the sum of the number of rows in all trigger subprograms encountered
54231  ** so far.  The nRow value will increase as new trigger subprograms are
54232  ** encountered, but p->pc will eventually catch up to nRow.
54233  */
54234  nRow = p->nOp;
54235  if( p->explain==1 ){
54236    /* The first 8 memory cells are used for the result set.  So we will
54237    ** commandeer the 9th cell to use as storage for an array of pointers
54238    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
54239    ** cells.  */
54240    assert( p->nMem>9 );
54241    pSub = &p->aMem[9];
54242    if( pSub->flags&MEM_Blob ){
54243      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
54244      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
54245      nSub = pSub->n/sizeof(Vdbe*);
54246      apSub = (SubProgram **)pSub->z;
54247    }
54248    for(i=0; i<nSub; i++){
54249      nRow += apSub[i]->nOp;
54250    }
54251  }
54252
54253  do{
54254    i = p->pc++;
54255  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
54256  if( i>=nRow ){
54257    p->rc = SQLITE_OK;
54258    rc = SQLITE_DONE;
54259  }else if( db->u1.isInterrupted ){
54260    p->rc = SQLITE_INTERRUPT;
54261    rc = SQLITE_ERROR;
54262    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
54263  }else{
54264    char *z;
54265    Op *pOp;
54266    if( i<p->nOp ){
54267      /* The output line number is small enough that we are still in the
54268      ** main program. */
54269      pOp = &p->aOp[i];
54270    }else{
54271      /* We are currently listing subprograms.  Figure out which one and
54272      ** pick up the appropriate opcode. */
54273      int j;
54274      i -= p->nOp;
54275      for(j=0; i>=apSub[j]->nOp; j++){
54276        i -= apSub[j]->nOp;
54277      }
54278      pOp = &apSub[j]->aOp[i];
54279    }
54280    if( p->explain==1 ){
54281      pMem->flags = MEM_Int;
54282      pMem->type = SQLITE_INTEGER;
54283      pMem->u.i = i;                                /* Program counter */
54284      pMem++;
54285
54286      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
54287      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
54288      assert( pMem->z!=0 );
54289      pMem->n = sqlite3Strlen30(pMem->z);
54290      pMem->type = SQLITE_TEXT;
54291      pMem->enc = SQLITE_UTF8;
54292      pMem++;
54293
54294      /* When an OP_Program opcode is encounter (the only opcode that has
54295      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
54296      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
54297      ** has not already been seen.
54298      */
54299      if( pOp->p4type==P4_SUBPROGRAM ){
54300        int nByte = (nSub+1)*sizeof(SubProgram*);
54301        int j;
54302        for(j=0; j<nSub; j++){
54303          if( apSub[j]==pOp->p4.pProgram ) break;
54304        }
54305        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
54306          apSub = (SubProgram **)pSub->z;
54307          apSub[nSub++] = pOp->p4.pProgram;
54308          pSub->flags |= MEM_Blob;
54309          pSub->n = nSub*sizeof(SubProgram*);
54310        }
54311      }
54312    }
54313
54314    pMem->flags = MEM_Int;
54315    pMem->u.i = pOp->p1;                          /* P1 */
54316    pMem->type = SQLITE_INTEGER;
54317    pMem++;
54318
54319    pMem->flags = MEM_Int;
54320    pMem->u.i = pOp->p2;                          /* P2 */
54321    pMem->type = SQLITE_INTEGER;
54322    pMem++;
54323
54324    if( p->explain==1 ){
54325      pMem->flags = MEM_Int;
54326      pMem->u.i = pOp->p3;                          /* P3 */
54327      pMem->type = SQLITE_INTEGER;
54328      pMem++;
54329    }
54330
54331    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
54332      assert( p->db->mallocFailed );
54333      return SQLITE_ERROR;
54334    }
54335    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54336    z = displayP4(pOp, pMem->z, 32);
54337    if( z!=pMem->z ){
54338      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
54339    }else{
54340      assert( pMem->z!=0 );
54341      pMem->n = sqlite3Strlen30(pMem->z);
54342      pMem->enc = SQLITE_UTF8;
54343    }
54344    pMem->type = SQLITE_TEXT;
54345    pMem++;
54346
54347    if( p->explain==1 ){
54348      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
54349        assert( p->db->mallocFailed );
54350        return SQLITE_ERROR;
54351      }
54352      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54353      pMem->n = 2;
54354      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
54355      pMem->type = SQLITE_TEXT;
54356      pMem->enc = SQLITE_UTF8;
54357      pMem++;
54358
54359#ifdef SQLITE_DEBUG
54360      if( pOp->zComment ){
54361        pMem->flags = MEM_Str|MEM_Term;
54362        pMem->z = pOp->zComment;
54363        pMem->n = sqlite3Strlen30(pMem->z);
54364        pMem->enc = SQLITE_UTF8;
54365        pMem->type = SQLITE_TEXT;
54366      }else
54367#endif
54368      {
54369        pMem->flags = MEM_Null;                       /* Comment */
54370        pMem->type = SQLITE_NULL;
54371      }
54372    }
54373
54374    p->nResColumn = 8 - 5*(p->explain-1);
54375    p->rc = SQLITE_OK;
54376    rc = SQLITE_ROW;
54377  }
54378  return rc;
54379}
54380#endif /* SQLITE_OMIT_EXPLAIN */
54381
54382#ifdef SQLITE_DEBUG
54383/*
54384** Print the SQL that was used to generate a VDBE program.
54385*/
54386SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
54387  int nOp = p->nOp;
54388  VdbeOp *pOp;
54389  if( nOp<1 ) return;
54390  pOp = &p->aOp[0];
54391  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54392    const char *z = pOp->p4.z;
54393    while( sqlite3Isspace(*z) ) z++;
54394    printf("SQL: [%s]\n", z);
54395  }
54396}
54397#endif
54398
54399#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
54400/*
54401** Print an IOTRACE message showing SQL content.
54402*/
54403SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
54404  int nOp = p->nOp;
54405  VdbeOp *pOp;
54406  if( sqlite3IoTrace==0 ) return;
54407  if( nOp<1 ) return;
54408  pOp = &p->aOp[0];
54409  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54410    int i, j;
54411    char z[1000];
54412    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
54413    for(i=0; sqlite3Isspace(z[i]); i++){}
54414    for(j=0; z[i]; i++){
54415      if( sqlite3Isspace(z[i]) ){
54416        if( z[i-1]!=' ' ){
54417          z[j++] = ' ';
54418        }
54419      }else{
54420        z[j++] = z[i];
54421      }
54422    }
54423    z[j] = 0;
54424    sqlite3IoTrace("SQL %s\n", z);
54425  }
54426}
54427#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
54428
54429/*
54430** Allocate space from a fixed size buffer and return a pointer to
54431** that space.  If insufficient space is available, return NULL.
54432**
54433** The pBuf parameter is the initial value of a pointer which will
54434** receive the new memory.  pBuf is normally NULL.  If pBuf is not
54435** NULL, it means that memory space has already been allocated and that
54436** this routine should not allocate any new memory.  When pBuf is not
54437** NULL simply return pBuf.  Only allocate new memory space when pBuf
54438** is NULL.
54439**
54440** nByte is the number of bytes of space needed.
54441**
54442** *ppFrom points to available space and pEnd points to the end of the
54443** available space.  When space is allocated, *ppFrom is advanced past
54444** the end of the allocated space.
54445**
54446** *pnByte is a counter of the number of bytes of space that have failed
54447** to allocate.  If there is insufficient space in *ppFrom to satisfy the
54448** request, then increment *pnByte by the amount of the request.
54449*/
54450static void *allocSpace(
54451  void *pBuf,          /* Where return pointer will be stored */
54452  int nByte,           /* Number of bytes to allocate */
54453  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
54454  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
54455  int *pnByte          /* If allocation cannot be made, increment *pnByte */
54456){
54457  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
54458  if( pBuf ) return pBuf;
54459  nByte = ROUND8(nByte);
54460  if( &(*ppFrom)[nByte] <= pEnd ){
54461    pBuf = (void*)*ppFrom;
54462    *ppFrom += nByte;
54463  }else{
54464    *pnByte += nByte;
54465  }
54466  return pBuf;
54467}
54468
54469/*
54470** Prepare a virtual machine for execution.  This involves things such
54471** as allocating stack space and initializing the program counter.
54472** After the VDBE has be prepped, it can be executed by one or more
54473** calls to sqlite3VdbeExec().
54474**
54475** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
54476** VDBE_MAGIC_RUN.
54477**
54478** This function may be called more than once on a single virtual machine.
54479** The first call is made while compiling the SQL statement. Subsequent
54480** calls are made as part of the process of resetting a statement to be
54481** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
54482** and isExplain parameters are only passed correct values the first time
54483** the function is called. On subsequent calls, from sqlite3_reset(), nVar
54484** is passed -1 and nMem, nCursor and isExplain are all passed zero.
54485*/
54486SQLITE_PRIVATE void sqlite3VdbeMakeReady(
54487  Vdbe *p,                       /* The VDBE */
54488  int nVar,                      /* Number of '?' see in the SQL statement */
54489  int nMem,                      /* Number of memory cells to allocate */
54490  int nCursor,                   /* Number of cursors to allocate */
54491  int nArg,                      /* Maximum number of args in SubPrograms */
54492  int isExplain,                 /* True if the EXPLAIN keywords is present */
54493  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
54494){
54495  int n;
54496  sqlite3 *db = p->db;
54497
54498  assert( p!=0 );
54499  assert( p->magic==VDBE_MAGIC_INIT );
54500
54501  /* There should be at least one opcode.
54502  */
54503  assert( p->nOp>0 );
54504
54505  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
54506  p->magic = VDBE_MAGIC_RUN;
54507
54508  /* For each cursor required, also allocate a memory cell. Memory
54509  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
54510  ** the vdbe program. Instead they are used to allocate space for
54511  ** VdbeCursor/BtCursor structures. The blob of memory associated with
54512  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
54513  ** stores the blob of memory associated with cursor 1, etc.
54514  **
54515  ** See also: allocateCursor().
54516  */
54517  nMem += nCursor;
54518
54519  /* Allocate space for memory registers, SQL variables, VDBE cursors and
54520  ** an array to marshal SQL function arguments in. This is only done the
54521  ** first time this function is called for a given VDBE, not when it is
54522  ** being called from sqlite3_reset() to reset the virtual machine.
54523  */
54524  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
54525    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
54526    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
54527    int nByte;                              /* How much extra memory needed */
54528
54529    resolveP2Values(p, &nArg);
54530    p->usesStmtJournal = (u8)usesStmtJournal;
54531    if( isExplain && nMem<10 ){
54532      nMem = 10;
54533    }
54534    memset(zCsr, 0, zEnd-zCsr);
54535    zCsr += (zCsr - (u8*)0)&7;
54536    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
54537
54538    /* Memory for registers, parameters, cursor, etc, is allocated in two
54539    ** passes.  On the first pass, we try to reuse unused space at the
54540    ** end of the opcode array.  If we are unable to satisfy all memory
54541    ** requirements by reusing the opcode array tail, then the second
54542    ** pass will fill in the rest using a fresh allocation.
54543    **
54544    ** This two-pass approach that reuses as much memory as possible from
54545    ** the leftover space at the end of the opcode array can significantly
54546    ** reduce the amount of memory held by a prepared statement.
54547    */
54548    do {
54549      nByte = 0;
54550      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
54551      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
54552      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
54553      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
54554      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
54555                            &zCsr, zEnd, &nByte);
54556      if( nByte ){
54557        p->pFree = sqlite3DbMallocZero(db, nByte);
54558      }
54559      zCsr = p->pFree;
54560      zEnd = &zCsr[nByte];
54561    }while( nByte && !db->mallocFailed );
54562
54563    p->nCursor = (u16)nCursor;
54564    if( p->aVar ){
54565      p->nVar = (ynVar)nVar;
54566      for(n=0; n<nVar; n++){
54567        p->aVar[n].flags = MEM_Null;
54568        p->aVar[n].db = db;
54569      }
54570    }
54571    if( p->aMem ){
54572      p->aMem--;                      /* aMem[] goes from 1..nMem */
54573      p->nMem = nMem;                 /*       not from 0..nMem-1 */
54574      for(n=1; n<=nMem; n++){
54575        p->aMem[n].flags = MEM_Null;
54576        p->aMem[n].db = db;
54577      }
54578    }
54579  }
54580#ifdef SQLITE_DEBUG
54581  for(n=1; n<p->nMem; n++){
54582    assert( p->aMem[n].db==db );
54583  }
54584#endif
54585
54586  p->pc = -1;
54587  p->rc = SQLITE_OK;
54588  p->errorAction = OE_Abort;
54589  p->explain |= isExplain;
54590  p->magic = VDBE_MAGIC_RUN;
54591  p->nChange = 0;
54592  p->cacheCtr = 1;
54593  p->minWriteFileFormat = 255;
54594  p->iStatement = 0;
54595  p->nFkConstraint = 0;
54596#ifdef VDBE_PROFILE
54597  {
54598    int i;
54599    for(i=0; i<p->nOp; i++){
54600      p->aOp[i].cnt = 0;
54601      p->aOp[i].cycles = 0;
54602    }
54603  }
54604#endif
54605}
54606
54607/*
54608** Close a VDBE cursor and release all the resources that cursor
54609** happens to hold.
54610*/
54611SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
54612  if( pCx==0 ){
54613    return;
54614  }
54615  if( pCx->pBt ){
54616    sqlite3BtreeClose(pCx->pBt);
54617    /* The pCx->pCursor will be close automatically, if it exists, by
54618    ** the call above. */
54619  }else if( pCx->pCursor ){
54620    sqlite3BtreeCloseCursor(pCx->pCursor);
54621  }
54622#ifndef SQLITE_OMIT_VIRTUALTABLE
54623  if( pCx->pVtabCursor ){
54624    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
54625    const sqlite3_module *pModule = pCx->pModule;
54626    p->inVtabMethod = 1;
54627    pModule->xClose(pVtabCursor);
54628    p->inVtabMethod = 0;
54629  }
54630#endif
54631}
54632
54633/*
54634** Copy the values stored in the VdbeFrame structure to its Vdbe. This
54635** is used, for example, when a trigger sub-program is halted to restore
54636** control to the main program.
54637*/
54638SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
54639  Vdbe *v = pFrame->v;
54640  v->aOp = pFrame->aOp;
54641  v->nOp = pFrame->nOp;
54642  v->aMem = pFrame->aMem;
54643  v->nMem = pFrame->nMem;
54644  v->apCsr = pFrame->apCsr;
54645  v->nCursor = pFrame->nCursor;
54646  v->db->lastRowid = pFrame->lastRowid;
54647  v->nChange = pFrame->nChange;
54648  return pFrame->pc;
54649}
54650
54651/*
54652** Close all cursors.
54653**
54654** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
54655** cell array. This is necessary as the memory cell array may contain
54656** pointers to VdbeFrame objects, which may in turn contain pointers to
54657** open cursors.
54658*/
54659static void closeAllCursors(Vdbe *p){
54660  if( p->pFrame ){
54661    VdbeFrame *pFrame = p->pFrame;
54662    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
54663    sqlite3VdbeFrameRestore(pFrame);
54664  }
54665  p->pFrame = 0;
54666  p->nFrame = 0;
54667
54668  if( p->apCsr ){
54669    int i;
54670    for(i=0; i<p->nCursor; i++){
54671      VdbeCursor *pC = p->apCsr[i];
54672      if( pC ){
54673        sqlite3VdbeFreeCursor(p, pC);
54674        p->apCsr[i] = 0;
54675      }
54676    }
54677  }
54678  if( p->aMem ){
54679    releaseMemArray(&p->aMem[1], p->nMem);
54680  }
54681}
54682
54683/*
54684** Clean up the VM after execution.
54685**
54686** This routine will automatically close any cursors, lists, and/or
54687** sorters that were left open.  It also deletes the values of
54688** variables in the aVar[] array.
54689*/
54690static void Cleanup(Vdbe *p){
54691  sqlite3 *db = p->db;
54692
54693#ifdef SQLITE_DEBUG
54694  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
54695  ** Vdbe.aMem[] arrays have already been cleaned up.  */
54696  int i;
54697  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
54698  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
54699#endif
54700
54701  sqlite3DbFree(db, p->zErrMsg);
54702  p->zErrMsg = 0;
54703  p->pResultSet = 0;
54704}
54705
54706/*
54707** Set the number of result columns that will be returned by this SQL
54708** statement. This is now set at compile time, rather than during
54709** execution of the vdbe program so that sqlite3_column_count() can
54710** be called on an SQL statement before sqlite3_step().
54711*/
54712SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
54713  Mem *pColName;
54714  int n;
54715  sqlite3 *db = p->db;
54716
54717  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
54718  sqlite3DbFree(db, p->aColName);
54719  n = nResColumn*COLNAME_N;
54720  p->nResColumn = (u16)nResColumn;
54721  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
54722  if( p->aColName==0 ) return;
54723  while( n-- > 0 ){
54724    pColName->flags = MEM_Null;
54725    pColName->db = p->db;
54726    pColName++;
54727  }
54728}
54729
54730/*
54731** Set the name of the idx'th column to be returned by the SQL statement.
54732** zName must be a pointer to a nul terminated string.
54733**
54734** This call must be made after a call to sqlite3VdbeSetNumCols().
54735**
54736** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
54737** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
54738** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
54739*/
54740SQLITE_PRIVATE int sqlite3VdbeSetColName(
54741  Vdbe *p,                         /* Vdbe being configured */
54742  int idx,                         /* Index of column zName applies to */
54743  int var,                         /* One of the COLNAME_* constants */
54744  const char *zName,               /* Pointer to buffer containing name */
54745  void (*xDel)(void*)              /* Memory management strategy for zName */
54746){
54747  int rc;
54748  Mem *pColName;
54749  assert( idx<p->nResColumn );
54750  assert( var<COLNAME_N );
54751  if( p->db->mallocFailed ){
54752    assert( !zName || xDel!=SQLITE_DYNAMIC );
54753    return SQLITE_NOMEM;
54754  }
54755  assert( p->aColName!=0 );
54756  pColName = &(p->aColName[idx+var*p->nResColumn]);
54757  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
54758  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
54759  return rc;
54760}
54761
54762/*
54763** A read or write transaction may or may not be active on database handle
54764** db. If a transaction is active, commit it. If there is a
54765** write-transaction spanning more than one database file, this routine
54766** takes care of the master journal trickery.
54767*/
54768static int vdbeCommit(sqlite3 *db, Vdbe *p){
54769  int i;
54770  int nTrans = 0;  /* Number of databases with an active write-transaction */
54771  int rc = SQLITE_OK;
54772  int needXcommit = 0;
54773
54774#ifdef SQLITE_OMIT_VIRTUALTABLE
54775  /* With this option, sqlite3VtabSync() is defined to be simply
54776  ** SQLITE_OK so p is not used.
54777  */
54778  UNUSED_PARAMETER(p);
54779#endif
54780
54781  /* Before doing anything else, call the xSync() callback for any
54782  ** virtual module tables written in this transaction. This has to
54783  ** be done before determining whether a master journal file is
54784  ** required, as an xSync() callback may add an attached database
54785  ** to the transaction.
54786  */
54787  rc = sqlite3VtabSync(db, &p->zErrMsg);
54788  if( rc!=SQLITE_OK ){
54789    return rc;
54790  }
54791
54792  /* This loop determines (a) if the commit hook should be invoked and
54793  ** (b) how many database files have open write transactions, not
54794  ** including the temp database. (b) is important because if more than
54795  ** one database file has an open write transaction, a master journal
54796  ** file is required for an atomic commit.
54797  */
54798  for(i=0; i<db->nDb; i++){
54799    Btree *pBt = db->aDb[i].pBt;
54800    if( sqlite3BtreeIsInTrans(pBt) ){
54801      needXcommit = 1;
54802      if( i!=1 ) nTrans++;
54803    }
54804  }
54805
54806  /* If there are any write-transactions at all, invoke the commit hook */
54807  if( needXcommit && db->xCommitCallback ){
54808    rc = db->xCommitCallback(db->pCommitArg);
54809    if( rc ){
54810      return SQLITE_CONSTRAINT;
54811    }
54812  }
54813
54814  /* The simple case - no more than one database file (not counting the
54815  ** TEMP database) has a transaction active.   There is no need for the
54816  ** master-journal.
54817  **
54818  ** If the return value of sqlite3BtreeGetFilename() is a zero length
54819  ** string, it means the main database is :memory: or a temp file.  In
54820  ** that case we do not support atomic multi-file commits, so use the
54821  ** simple case then too.
54822  */
54823  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
54824   || nTrans<=1
54825  ){
54826    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
54827      Btree *pBt = db->aDb[i].pBt;
54828      if( pBt ){
54829        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
54830      }
54831    }
54832
54833    /* Do the commit only if all databases successfully complete phase 1.
54834    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
54835    ** IO error while deleting or truncating a journal file. It is unlikely,
54836    ** but could happen. In this case abandon processing and return the error.
54837    */
54838    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
54839      Btree *pBt = db->aDb[i].pBt;
54840      if( pBt ){
54841        rc = sqlite3BtreeCommitPhaseTwo(pBt);
54842      }
54843    }
54844    if( rc==SQLITE_OK ){
54845      sqlite3VtabCommit(db);
54846    }
54847  }
54848
54849  /* The complex case - There is a multi-file write-transaction active.
54850  ** This requires a master journal file to ensure the transaction is
54851  ** committed atomicly.
54852  */
54853#ifndef SQLITE_OMIT_DISKIO
54854  else{
54855    sqlite3_vfs *pVfs = db->pVfs;
54856    int needSync = 0;
54857    char *zMaster = 0;   /* File-name for the master journal */
54858    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
54859    sqlite3_file *pMaster = 0;
54860    i64 offset = 0;
54861    int res;
54862
54863    /* Select a master journal file name */
54864    do {
54865      u32 iRandom;
54866      sqlite3DbFree(db, zMaster);
54867      sqlite3_randomness(sizeof(iRandom), &iRandom);
54868      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
54869      if( !zMaster ){
54870        return SQLITE_NOMEM;
54871      }
54872      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
54873    }while( rc==SQLITE_OK && res );
54874    if( rc==SQLITE_OK ){
54875      /* Open the master journal. */
54876      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
54877          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
54878          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
54879      );
54880    }
54881    if( rc!=SQLITE_OK ){
54882      sqlite3DbFree(db, zMaster);
54883      return rc;
54884    }
54885
54886    /* Write the name of each database file in the transaction into the new
54887    ** master journal file. If an error occurs at this point close
54888    ** and delete the master journal file. All the individual journal files
54889    ** still have 'null' as the master journal pointer, so they will roll
54890    ** back independently if a failure occurs.
54891    */
54892    for(i=0; i<db->nDb; i++){
54893      Btree *pBt = db->aDb[i].pBt;
54894      if( sqlite3BtreeIsInTrans(pBt) ){
54895        char const *zFile = sqlite3BtreeGetJournalname(pBt);
54896        if( zFile==0 || zFile[0]==0 ){
54897          continue;  /* Ignore TEMP and :memory: databases */
54898        }
54899        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
54900          needSync = 1;
54901        }
54902        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
54903        offset += sqlite3Strlen30(zFile)+1;
54904        if( rc!=SQLITE_OK ){
54905          sqlite3OsCloseFree(pMaster);
54906          sqlite3OsDelete(pVfs, zMaster, 0);
54907          sqlite3DbFree(db, zMaster);
54908          return rc;
54909        }
54910      }
54911    }
54912
54913    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
54914    ** flag is set this is not required.
54915    */
54916    if( needSync
54917     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
54918     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
54919    ){
54920      sqlite3OsCloseFree(pMaster);
54921      sqlite3OsDelete(pVfs, zMaster, 0);
54922      sqlite3DbFree(db, zMaster);
54923      return rc;
54924    }
54925
54926    /* Sync all the db files involved in the transaction. The same call
54927    ** sets the master journal pointer in each individual journal. If
54928    ** an error occurs here, do not delete the master journal file.
54929    **
54930    ** If the error occurs during the first call to
54931    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
54932    ** master journal file will be orphaned. But we cannot delete it,
54933    ** in case the master journal file name was written into the journal
54934    ** file before the failure occurred.
54935    */
54936    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
54937      Btree *pBt = db->aDb[i].pBt;
54938      if( pBt ){
54939        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
54940      }
54941    }
54942    sqlite3OsCloseFree(pMaster);
54943    if( rc!=SQLITE_OK ){
54944      sqlite3DbFree(db, zMaster);
54945      return rc;
54946    }
54947
54948    /* Delete the master journal file. This commits the transaction. After
54949    ** doing this the directory is synced again before any individual
54950    ** transaction files are deleted.
54951    */
54952    rc = sqlite3OsDelete(pVfs, zMaster, 1);
54953    sqlite3DbFree(db, zMaster);
54954    zMaster = 0;
54955    if( rc ){
54956      return rc;
54957    }
54958
54959    /* All files and directories have already been synced, so the following
54960    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
54961    ** deleting or truncating journals. If something goes wrong while
54962    ** this is happening we don't really care. The integrity of the
54963    ** transaction is already guaranteed, but some stray 'cold' journals
54964    ** may be lying around. Returning an error code won't help matters.
54965    */
54966    disable_simulated_io_errors();
54967    sqlite3BeginBenignMalloc();
54968    for(i=0; i<db->nDb; i++){
54969      Btree *pBt = db->aDb[i].pBt;
54970      if( pBt ){
54971        sqlite3BtreeCommitPhaseTwo(pBt);
54972      }
54973    }
54974    sqlite3EndBenignMalloc();
54975    enable_simulated_io_errors();
54976
54977    sqlite3VtabCommit(db);
54978  }
54979#endif
54980
54981  return rc;
54982}
54983
54984/*
54985** This routine checks that the sqlite3.activeVdbeCnt count variable
54986** matches the number of vdbe's in the list sqlite3.pVdbe that are
54987** currently active. An assertion fails if the two counts do not match.
54988** This is an internal self-check only - it is not an essential processing
54989** step.
54990**
54991** This is a no-op if NDEBUG is defined.
54992*/
54993#ifndef NDEBUG
54994static void checkActiveVdbeCnt(sqlite3 *db){
54995  Vdbe *p;
54996  int cnt = 0;
54997  int nWrite = 0;
54998  p = db->pVdbe;
54999  while( p ){
55000    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
55001      cnt++;
55002      if( p->readOnly==0 ) nWrite++;
55003    }
55004    p = p->pNext;
55005  }
55006  assert( cnt==db->activeVdbeCnt );
55007  assert( nWrite==db->writeVdbeCnt );
55008}
55009#else
55010#define checkActiveVdbeCnt(x)
55011#endif
55012
55013/*
55014** For every Btree that in database connection db which
55015** has been modified, "trip" or invalidate each cursor in
55016** that Btree might have been modified so that the cursor
55017** can never be used again.  This happens when a rollback
55018*** occurs.  We have to trip all the other cursors, even
55019** cursor from other VMs in different database connections,
55020** so that none of them try to use the data at which they
55021** were pointing and which now may have been changed due
55022** to the rollback.
55023**
55024** Remember that a rollback can delete tables complete and
55025** reorder rootpages.  So it is not sufficient just to save
55026** the state of the cursor.  We have to invalidate the cursor
55027** so that it is never used again.
55028*/
55029static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
55030  int i;
55031  for(i=0; i<db->nDb; i++){
55032    Btree *p = db->aDb[i].pBt;
55033    if( p && sqlite3BtreeIsInTrans(p) ){
55034      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
55035    }
55036  }
55037}
55038
55039/*
55040** If the Vdbe passed as the first argument opened a statement-transaction,
55041** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
55042** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
55043** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
55044** statement transaction is commtted.
55045**
55046** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
55047** Otherwise SQLITE_OK.
55048*/
55049SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
55050  sqlite3 *const db = p->db;
55051  int rc = SQLITE_OK;
55052
55053  /* If p->iStatement is greater than zero, then this Vdbe opened a
55054  ** statement transaction that should be closed here. The only exception
55055  ** is that an IO error may have occured, causing an emergency rollback.
55056  ** In this case (db->nStatement==0), and there is nothing to do.
55057  */
55058  if( db->nStatement && p->iStatement ){
55059    int i;
55060    const int iSavepoint = p->iStatement-1;
55061
55062    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
55063    assert( db->nStatement>0 );
55064    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
55065
55066    for(i=0; i<db->nDb; i++){
55067      int rc2 = SQLITE_OK;
55068      Btree *pBt = db->aDb[i].pBt;
55069      if( pBt ){
55070        if( eOp==SAVEPOINT_ROLLBACK ){
55071          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
55072        }
55073        if( rc2==SQLITE_OK ){
55074          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
55075        }
55076        if( rc==SQLITE_OK ){
55077          rc = rc2;
55078        }
55079      }
55080    }
55081    db->nStatement--;
55082    p->iStatement = 0;
55083
55084    /* If the statement transaction is being rolled back, also restore the
55085    ** database handles deferred constraint counter to the value it had when
55086    ** the statement transaction was opened.  */
55087    if( eOp==SAVEPOINT_ROLLBACK ){
55088      db->nDeferredCons = p->nStmtDefCons;
55089    }
55090  }
55091  return rc;
55092}
55093
55094/*
55095** If SQLite is compiled to support shared-cache mode and to be threadsafe,
55096** this routine obtains the mutex associated with each BtShared structure
55097** that may be accessed by the VM passed as an argument. In doing so it
55098** sets the BtShared.db member of each of the BtShared structures, ensuring
55099** that the correct busy-handler callback is invoked if required.
55100**
55101** If SQLite is not threadsafe but does support shared-cache mode, then
55102** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
55103** of all of BtShared structures accessible via the database handle
55104** associated with the VM. Of course only a subset of these structures
55105** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
55106** that subset out, but there is no advantage to doing so.
55107**
55108** If SQLite is not threadsafe and does not support shared-cache mode, this
55109** function is a no-op.
55110*/
55111#ifndef SQLITE_OMIT_SHARED_CACHE
55112SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
55113#if SQLITE_THREADSAFE
55114  sqlite3BtreeMutexArrayEnter(&p->aMutex);
55115#else
55116  sqlite3BtreeEnterAll(p->db);
55117#endif
55118}
55119#endif
55120
55121/*
55122** This function is called when a transaction opened by the database
55123** handle associated with the VM passed as an argument is about to be
55124** committed. If there are outstanding deferred foreign key constraint
55125** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
55126**
55127** If there are outstanding FK violations and this function returns
55128** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
55129** an error message to it. Then return SQLITE_ERROR.
55130*/
55131#ifndef SQLITE_OMIT_FOREIGN_KEY
55132SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
55133  sqlite3 *db = p->db;
55134  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
55135    p->rc = SQLITE_CONSTRAINT;
55136    p->errorAction = OE_Abort;
55137    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
55138    return SQLITE_ERROR;
55139  }
55140  return SQLITE_OK;
55141}
55142#endif
55143
55144/*
55145** This routine is called the when a VDBE tries to halt.  If the VDBE
55146** has made changes and is in autocommit mode, then commit those
55147** changes.  If a rollback is needed, then do the rollback.
55148**
55149** This routine is the only way to move the state of a VM from
55150** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
55151** call this on a VM that is in the SQLITE_MAGIC_HALT state.
55152**
55153** Return an error code.  If the commit could not complete because of
55154** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
55155** means the close did not happen and needs to be repeated.
55156*/
55157SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
55158  int rc;                         /* Used to store transient return codes */
55159  sqlite3 *db = p->db;
55160
55161  /* This function contains the logic that determines if a statement or
55162  ** transaction will be committed or rolled back as a result of the
55163  ** execution of this virtual machine.
55164  **
55165  ** If any of the following errors occur:
55166  **
55167  **     SQLITE_NOMEM
55168  **     SQLITE_IOERR
55169  **     SQLITE_FULL
55170  **     SQLITE_INTERRUPT
55171  **
55172  ** Then the internal cache might have been left in an inconsistent
55173  ** state.  We need to rollback the statement transaction, if there is
55174  ** one, or the complete transaction if there is no statement transaction.
55175  */
55176
55177  if( p->db->mallocFailed ){
55178    p->rc = SQLITE_NOMEM;
55179  }
55180  closeAllCursors(p);
55181  if( p->magic!=VDBE_MAGIC_RUN ){
55182    return SQLITE_OK;
55183  }
55184  checkActiveVdbeCnt(db);
55185
55186  /* No commit or rollback needed if the program never started */
55187  if( p->pc>=0 ){
55188    int mrc;   /* Primary error code from p->rc */
55189    int eStatementOp = 0;
55190    int isSpecialError;            /* Set to true if a 'special' error */
55191
55192    /* Lock all btrees used by the statement */
55193    sqlite3VdbeMutexArrayEnter(p);
55194
55195    /* Check for one of the special errors */
55196    mrc = p->rc & 0xff;
55197    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
55198    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
55199                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
55200    if( isSpecialError ){
55201      /* If the query was read-only, we need do no rollback at all. Otherwise,
55202      ** proceed with the special handling.
55203      */
55204      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
55205        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
55206          eStatementOp = SAVEPOINT_ROLLBACK;
55207        }else{
55208          /* We are forced to roll back the active transaction. Before doing
55209          ** so, abort any other statements this handle currently has active.
55210          */
55211          invalidateCursorsOnModifiedBtrees(db);
55212          sqlite3RollbackAll(db);
55213          sqlite3CloseSavepoints(db);
55214          db->autoCommit = 1;
55215        }
55216      }
55217    }
55218
55219    /* Check for immediate foreign key violations. */
55220    if( p->rc==SQLITE_OK ){
55221      sqlite3VdbeCheckFk(p, 0);
55222    }
55223
55224    /* If the auto-commit flag is set and this is the only active writer
55225    ** VM, then we do either a commit or rollback of the current transaction.
55226    **
55227    ** Note: This block also runs if one of the special errors handled
55228    ** above has occurred.
55229    */
55230    if( !sqlite3VtabInSync(db)
55231     && db->autoCommit
55232     && db->writeVdbeCnt==(p->readOnly==0)
55233    ){
55234      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
55235        if( sqlite3VdbeCheckFk(p, 1) ){
55236          sqlite3BtreeMutexArrayLeave(&p->aMutex);
55237          return SQLITE_ERROR;
55238        }
55239        /* The auto-commit flag is true, the vdbe program was successful
55240        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
55241        ** key constraints to hold up the transaction. This means a commit
55242        ** is required.  */
55243        rc = vdbeCommit(db, p);
55244        if( rc==SQLITE_BUSY ){
55245          sqlite3BtreeMutexArrayLeave(&p->aMutex);
55246          return SQLITE_BUSY;
55247        }else if( rc!=SQLITE_OK ){
55248          p->rc = rc;
55249          sqlite3RollbackAll(db);
55250        }else{
55251          db->nDeferredCons = 0;
55252          sqlite3CommitInternalChanges(db);
55253        }
55254      }else{
55255        sqlite3RollbackAll(db);
55256      }
55257      db->nStatement = 0;
55258    }else if( eStatementOp==0 ){
55259      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
55260        eStatementOp = SAVEPOINT_RELEASE;
55261      }else if( p->errorAction==OE_Abort ){
55262        eStatementOp = SAVEPOINT_ROLLBACK;
55263      }else{
55264        invalidateCursorsOnModifiedBtrees(db);
55265        sqlite3RollbackAll(db);
55266        sqlite3CloseSavepoints(db);
55267        db->autoCommit = 1;
55268      }
55269    }
55270
55271    /* If eStatementOp is non-zero, then a statement transaction needs to
55272    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
55273    ** do so. If this operation returns an error, and the current statement
55274    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
55275    ** current statement error code.
55276    **
55277    ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
55278    ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
55279    ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
55280    ** the following code.
55281    */
55282    if( eStatementOp ){
55283      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
55284      if( rc ){
55285        assert( eStatementOp==SAVEPOINT_ROLLBACK );
55286        if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
55287          p->rc = rc;
55288          sqlite3DbFree(db, p->zErrMsg);
55289          p->zErrMsg = 0;
55290        }
55291        invalidateCursorsOnModifiedBtrees(db);
55292        sqlite3RollbackAll(db);
55293        sqlite3CloseSavepoints(db);
55294        db->autoCommit = 1;
55295      }
55296    }
55297
55298    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
55299    ** has been rolled back, update the database connection change-counter.
55300    */
55301    if( p->changeCntOn ){
55302      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
55303        sqlite3VdbeSetChanges(db, p->nChange);
55304      }else{
55305        sqlite3VdbeSetChanges(db, 0);
55306      }
55307      p->nChange = 0;
55308    }
55309
55310    /* Rollback or commit any schema changes that occurred. */
55311    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
55312      sqlite3ResetInternalSchema(db, 0);
55313      db->flags = (db->flags | SQLITE_InternChanges);
55314    }
55315
55316    /* Release the locks */
55317    sqlite3BtreeMutexArrayLeave(&p->aMutex);
55318  }
55319
55320  /* We have successfully halted and closed the VM.  Record this fact. */
55321  if( p->pc>=0 ){
55322    db->activeVdbeCnt--;
55323    if( !p->readOnly ){
55324      db->writeVdbeCnt--;
55325    }
55326    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
55327  }
55328  p->magic = VDBE_MAGIC_HALT;
55329  checkActiveVdbeCnt(db);
55330  if( p->db->mallocFailed ){
55331    p->rc = SQLITE_NOMEM;
55332  }
55333
55334  /* If the auto-commit flag is set to true, then any locks that were held
55335  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
55336  ** to invoke any required unlock-notify callbacks.
55337  */
55338  if( db->autoCommit ){
55339    sqlite3ConnectionUnlocked(db);
55340  }
55341
55342  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
55343  return SQLITE_OK;
55344}
55345
55346
55347/*
55348** Each VDBE holds the result of the most recent sqlite3_step() call
55349** in p->rc.  This routine sets that result back to SQLITE_OK.
55350*/
55351SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
55352  p->rc = SQLITE_OK;
55353}
55354
55355/*
55356** Clean up a VDBE after execution but do not delete the VDBE just yet.
55357** Write any error messages into *pzErrMsg.  Return the result code.
55358**
55359** After this routine is run, the VDBE should be ready to be executed
55360** again.
55361**
55362** To look at it another way, this routine resets the state of the
55363** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
55364** VDBE_MAGIC_INIT.
55365*/
55366SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
55367  sqlite3 *db;
55368  db = p->db;
55369
55370  /* If the VM did not run to completion or if it encountered an
55371  ** error, then it might not have been halted properly.  So halt
55372  ** it now.
55373  */
55374  sqlite3VdbeHalt(p);
55375
55376  /* If the VDBE has be run even partially, then transfer the error code
55377  ** and error message from the VDBE into the main database structure.  But
55378  ** if the VDBE has just been set to run but has not actually executed any
55379  ** instructions yet, leave the main database error information unchanged.
55380  */
55381  if( p->pc>=0 ){
55382    if( p->zErrMsg ){
55383      sqlite3BeginBenignMalloc();
55384      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
55385      sqlite3EndBenignMalloc();
55386      db->errCode = p->rc;
55387      sqlite3DbFree(db, p->zErrMsg);
55388      p->zErrMsg = 0;
55389    }else if( p->rc ){
55390      sqlite3Error(db, p->rc, 0);
55391    }else{
55392      sqlite3Error(db, SQLITE_OK, 0);
55393    }
55394    if( p->runOnlyOnce ) p->expired = 1;
55395  }else if( p->rc && p->expired ){
55396    /* The expired flag was set on the VDBE before the first call
55397    ** to sqlite3_step(). For consistency (since sqlite3_step() was
55398    ** called), set the database error in this case as well.
55399    */
55400    sqlite3Error(db, p->rc, 0);
55401    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
55402    sqlite3DbFree(db, p->zErrMsg);
55403    p->zErrMsg = 0;
55404  }
55405
55406  /* Reclaim all memory used by the VDBE
55407  */
55408  Cleanup(p);
55409
55410  /* Save profiling information from this VDBE run.
55411  */
55412#ifdef VDBE_PROFILE
55413  {
55414    FILE *out = fopen("vdbe_profile.out", "a");
55415    if( out ){
55416      int i;
55417      fprintf(out, "---- ");
55418      for(i=0; i<p->nOp; i++){
55419        fprintf(out, "%02x", p->aOp[i].opcode);
55420      }
55421      fprintf(out, "\n");
55422      for(i=0; i<p->nOp; i++){
55423        fprintf(out, "%6d %10lld %8lld ",
55424           p->aOp[i].cnt,
55425           p->aOp[i].cycles,
55426           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
55427        );
55428        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
55429      }
55430      fclose(out);
55431    }
55432  }
55433#endif
55434  p->magic = VDBE_MAGIC_INIT;
55435  return p->rc & db->errMask;
55436}
55437
55438/*
55439** Clean up and delete a VDBE after execution.  Return an integer which is
55440** the result code.  Write any error message text into *pzErrMsg.
55441*/
55442SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
55443  int rc = SQLITE_OK;
55444  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
55445    rc = sqlite3VdbeReset(p);
55446    assert( (rc & p->db->errMask)==rc );
55447  }
55448  sqlite3VdbeDelete(p);
55449  return rc;
55450}
55451
55452/*
55453** Call the destructor for each auxdata entry in pVdbeFunc for which
55454** the corresponding bit in mask is clear.  Auxdata entries beyond 31
55455** are always destroyed.  To destroy all auxdata entries, call this
55456** routine with mask==0.
55457*/
55458SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
55459  int i;
55460  for(i=0; i<pVdbeFunc->nAux; i++){
55461    struct AuxData *pAux = &pVdbeFunc->apAux[i];
55462    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
55463      if( pAux->xDelete ){
55464        pAux->xDelete(pAux->pAux);
55465      }
55466      pAux->pAux = 0;
55467    }
55468  }
55469}
55470
55471/*
55472** Delete an entire VDBE.
55473*/
55474SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
55475  sqlite3 *db;
55476
55477  if( NEVER(p==0) ) return;
55478  db = p->db;
55479  if( p->pPrev ){
55480    p->pPrev->pNext = p->pNext;
55481  }else{
55482    assert( db->pVdbe==p );
55483    db->pVdbe = p->pNext;
55484  }
55485  if( p->pNext ){
55486    p->pNext->pPrev = p->pPrev;
55487  }
55488  releaseMemArray(p->aVar, p->nVar);
55489  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55490  vdbeFreeOpArray(db, p->aOp, p->nOp);
55491  sqlite3DbFree(db, p->aLabel);
55492  sqlite3DbFree(db, p->aColName);
55493  sqlite3DbFree(db, p->zSql);
55494  p->magic = VDBE_MAGIC_DEAD;
55495  sqlite3DbFree(db, p->pFree);
55496  p->db = 0;
55497  sqlite3DbFree(db, p);
55498}
55499
55500/*
55501** Make sure the cursor p is ready to read or write the row to which it
55502** was last positioned.  Return an error code if an OOM fault or I/O error
55503** prevents us from positioning the cursor to its correct position.
55504**
55505** If a MoveTo operation is pending on the given cursor, then do that
55506** MoveTo now.  If no move is pending, check to see if the row has been
55507** deleted out from under the cursor and if it has, mark the row as
55508** a NULL row.
55509**
55510** If the cursor is already pointing to the correct row and that row has
55511** not been deleted out from under the cursor, then this routine is a no-op.
55512*/
55513SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
55514  if( p->deferredMoveto ){
55515    int res, rc;
55516#ifdef SQLITE_TEST
55517    extern int sqlite3_search_count;
55518#endif
55519    assert( p->isTable );
55520    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
55521    if( rc ) return rc;
55522    p->lastRowid = p->movetoTarget;
55523    p->rowidIsValid = ALWAYS(res==0) ?1:0;
55524    if( NEVER(res<0) ){
55525      rc = sqlite3BtreeNext(p->pCursor, &res);
55526      if( rc ) return rc;
55527    }
55528#ifdef SQLITE_TEST
55529    sqlite3_search_count++;
55530#endif
55531    p->deferredMoveto = 0;
55532    p->cacheStatus = CACHE_STALE;
55533  }else if( ALWAYS(p->pCursor) ){
55534    int hasMoved;
55535    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
55536    if( rc ) return rc;
55537    if( hasMoved ){
55538      p->cacheStatus = CACHE_STALE;
55539      p->nullRow = 1;
55540    }
55541  }
55542  return SQLITE_OK;
55543}
55544
55545/*
55546** The following functions:
55547**
55548** sqlite3VdbeSerialType()
55549** sqlite3VdbeSerialTypeLen()
55550** sqlite3VdbeSerialLen()
55551** sqlite3VdbeSerialPut()
55552** sqlite3VdbeSerialGet()
55553**
55554** encapsulate the code that serializes values for storage in SQLite
55555** data and index records. Each serialized value consists of a
55556** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
55557** integer, stored as a varint.
55558**
55559** In an SQLite index record, the serial type is stored directly before
55560** the blob of data that it corresponds to. In a table record, all serial
55561** types are stored at the start of the record, and the blobs of data at
55562** the end. Hence these functions allow the caller to handle the
55563** serial-type and data blob seperately.
55564**
55565** The following table describes the various storage classes for data:
55566**
55567**   serial type        bytes of data      type
55568**   --------------     ---------------    ---------------
55569**      0                     0            NULL
55570**      1                     1            signed integer
55571**      2                     2            signed integer
55572**      3                     3            signed integer
55573**      4                     4            signed integer
55574**      5                     6            signed integer
55575**      6                     8            signed integer
55576**      7                     8            IEEE float
55577**      8                     0            Integer constant 0
55578**      9                     0            Integer constant 1
55579**     10,11                               reserved for expansion
55580**    N>=12 and even       (N-12)/2        BLOB
55581**    N>=13 and odd        (N-13)/2        text
55582**
55583** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
55584** of SQLite will not understand those serial types.
55585*/
55586
55587/*
55588** Return the serial-type for the value stored in pMem.
55589*/
55590SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
55591  int flags = pMem->flags;
55592  int n;
55593
55594  if( flags&MEM_Null ){
55595    return 0;
55596  }
55597  if( flags&MEM_Int ){
55598    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
55599#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
55600    i64 i = pMem->u.i;
55601    u64 u;
55602    if( file_format>=4 && (i&1)==i ){
55603      return 8+(u32)i;
55604    }
55605    u = i<0 ? -i : i;
55606    if( u<=127 ) return 1;
55607    if( u<=32767 ) return 2;
55608    if( u<=8388607 ) return 3;
55609    if( u<=2147483647 ) return 4;
55610    if( u<=MAX_6BYTE ) return 5;
55611    return 6;
55612  }
55613  if( flags&MEM_Real ){
55614    return 7;
55615  }
55616  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
55617  n = pMem->n;
55618  if( flags & MEM_Zero ){
55619    n += pMem->u.nZero;
55620  }
55621  assert( n>=0 );
55622  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
55623}
55624
55625/*
55626** Return the length of the data corresponding to the supplied serial-type.
55627*/
55628SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
55629  if( serial_type>=12 ){
55630    return (serial_type-12)/2;
55631  }else{
55632    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
55633    return aSize[serial_type];
55634  }
55635}
55636
55637/*
55638** If we are on an architecture with mixed-endian floating
55639** points (ex: ARM7) then swap the lower 4 bytes with the
55640** upper 4 bytes.  Return the result.
55641**
55642** For most architectures, this is a no-op.
55643**
55644** (later):  It is reported to me that the mixed-endian problem
55645** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
55646** that early versions of GCC stored the two words of a 64-bit
55647** float in the wrong order.  And that error has been propagated
55648** ever since.  The blame is not necessarily with GCC, though.
55649** GCC might have just copying the problem from a prior compiler.
55650** I am also told that newer versions of GCC that follow a different
55651** ABI get the byte order right.
55652**
55653** Developers using SQLite on an ARM7 should compile and run their
55654** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
55655** enabled, some asserts below will ensure that the byte order of
55656** floating point values is correct.
55657**
55658** (2007-08-30)  Frank van Vugt has studied this problem closely
55659** and has send his findings to the SQLite developers.  Frank
55660** writes that some Linux kernels offer floating point hardware
55661** emulation that uses only 32-bit mantissas instead of a full
55662** 48-bits as required by the IEEE standard.  (This is the
55663** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
55664** byte swapping becomes very complicated.  To avoid problems,
55665** the necessary byte swapping is carried out using a 64-bit integer
55666** rather than a 64-bit float.  Frank assures us that the code here
55667** works for him.  We, the developers, have no way to independently
55668** verify this, but Frank seems to know what he is talking about
55669** so we trust him.
55670*/
55671#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
55672static u64 floatSwap(u64 in){
55673  union {
55674    u64 r;
55675    u32 i[2];
55676  } u;
55677  u32 t;
55678
55679  u.r = in;
55680  t = u.i[0];
55681  u.i[0] = u.i[1];
55682  u.i[1] = t;
55683  return u.r;
55684}
55685# define swapMixedEndianFloat(X)  X = floatSwap(X)
55686#else
55687# define swapMixedEndianFloat(X)
55688#endif
55689
55690/*
55691** Write the serialized data blob for the value stored in pMem into
55692** buf. It is assumed that the caller has allocated sufficient space.
55693** Return the number of bytes written.
55694**
55695** nBuf is the amount of space left in buf[].  nBuf must always be
55696** large enough to hold the entire field.  Except, if the field is
55697** a blob with a zero-filled tail, then buf[] might be just the right
55698** size to hold everything except for the zero-filled tail.  If buf[]
55699** is only big enough to hold the non-zero prefix, then only write that
55700** prefix into buf[].  But if buf[] is large enough to hold both the
55701** prefix and the tail then write the prefix and set the tail to all
55702** zeros.
55703**
55704** Return the number of bytes actually written into buf[].  The number
55705** of bytes in the zero-filled tail is included in the return value only
55706** if those bytes were zeroed in buf[].
55707*/
55708SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
55709  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
55710  u32 len;
55711
55712  /* Integer and Real */
55713  if( serial_type<=7 && serial_type>0 ){
55714    u64 v;
55715    u32 i;
55716    if( serial_type==7 ){
55717      assert( sizeof(v)==sizeof(pMem->r) );
55718      memcpy(&v, &pMem->r, sizeof(v));
55719      swapMixedEndianFloat(v);
55720    }else{
55721      v = pMem->u.i;
55722    }
55723    len = i = sqlite3VdbeSerialTypeLen(serial_type);
55724    assert( len<=(u32)nBuf );
55725    while( i-- ){
55726      buf[i] = (u8)(v&0xFF);
55727      v >>= 8;
55728    }
55729    return len;
55730  }
55731
55732  /* String or blob */
55733  if( serial_type>=12 ){
55734    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
55735             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
55736    assert( pMem->n<=nBuf );
55737    len = pMem->n;
55738    memcpy(buf, pMem->z, len);
55739    if( pMem->flags & MEM_Zero ){
55740      len += pMem->u.nZero;
55741      assert( nBuf>=0 );
55742      if( len > (u32)nBuf ){
55743        len = (u32)nBuf;
55744      }
55745      memset(&buf[pMem->n], 0, len-pMem->n);
55746    }
55747    return len;
55748  }
55749
55750  /* NULL or constants 0 or 1 */
55751  return 0;
55752}
55753
55754/*
55755** Deserialize the data blob pointed to by buf as serial type serial_type
55756** and store the result in pMem.  Return the number of bytes read.
55757*/
55758SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
55759  const unsigned char *buf,     /* Buffer to deserialize from */
55760  u32 serial_type,              /* Serial type to deserialize */
55761  Mem *pMem                     /* Memory cell to write value into */
55762){
55763  switch( serial_type ){
55764    case 10:   /* Reserved for future use */
55765    case 11:   /* Reserved for future use */
55766    case 0: {  /* NULL */
55767      pMem->flags = MEM_Null;
55768      break;
55769    }
55770    case 1: { /* 1-byte signed integer */
55771      pMem->u.i = (signed char)buf[0];
55772      pMem->flags = MEM_Int;
55773      return 1;
55774    }
55775    case 2: { /* 2-byte signed integer */
55776      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
55777      pMem->flags = MEM_Int;
55778      return 2;
55779    }
55780    case 3: { /* 3-byte signed integer */
55781      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
55782      pMem->flags = MEM_Int;
55783      return 3;
55784    }
55785    case 4: { /* 4-byte signed integer */
55786      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
55787      pMem->flags = MEM_Int;
55788      return 4;
55789    }
55790    case 5: { /* 6-byte signed integer */
55791      u64 x = (((signed char)buf[0])<<8) | buf[1];
55792      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
55793      x = (x<<32) | y;
55794      pMem->u.i = *(i64*)&x;
55795      pMem->flags = MEM_Int;
55796      return 6;
55797    }
55798    case 6:   /* 8-byte signed integer */
55799    case 7: { /* IEEE floating point */
55800      u64 x;
55801      u32 y;
55802#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
55803      /* Verify that integers and floating point values use the same
55804      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
55805      ** defined that 64-bit floating point values really are mixed
55806      ** endian.
55807      */
55808      static const u64 t1 = ((u64)0x3ff00000)<<32;
55809      static const double r1 = 1.0;
55810      u64 t2 = t1;
55811      swapMixedEndianFloat(t2);
55812      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
55813#endif
55814
55815      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
55816      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
55817      x = (x<<32) | y;
55818      if( serial_type==6 ){
55819        pMem->u.i = *(i64*)&x;
55820        pMem->flags = MEM_Int;
55821      }else{
55822        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
55823        swapMixedEndianFloat(x);
55824        memcpy(&pMem->r, &x, sizeof(x));
55825        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
55826      }
55827      return 8;
55828    }
55829    case 8:    /* Integer 0 */
55830    case 9: {  /* Integer 1 */
55831      pMem->u.i = serial_type-8;
55832      pMem->flags = MEM_Int;
55833      return 0;
55834    }
55835    default: {
55836      u32 len = (serial_type-12)/2;
55837      pMem->z = (char *)buf;
55838      pMem->n = len;
55839      pMem->xDel = 0;
55840      if( serial_type&0x01 ){
55841        pMem->flags = MEM_Str | MEM_Ephem;
55842      }else{
55843        pMem->flags = MEM_Blob | MEM_Ephem;
55844      }
55845      return len;
55846    }
55847  }
55848  return 0;
55849}
55850
55851
55852/*
55853** Given the nKey-byte encoding of a record in pKey[], parse the
55854** record into a UnpackedRecord structure.  Return a pointer to
55855** that structure.
55856**
55857** The calling function might provide szSpace bytes of memory
55858** space at pSpace.  This space can be used to hold the returned
55859** VDbeParsedRecord structure if it is large enough.  If it is
55860** not big enough, space is obtained from sqlite3_malloc().
55861**
55862** The returned structure should be closed by a call to
55863** sqlite3VdbeDeleteUnpackedRecord().
55864*/
55865SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
55866  KeyInfo *pKeyInfo,     /* Information about the record format */
55867  int nKey,              /* Size of the binary record */
55868  const void *pKey,      /* The binary record */
55869  char *pSpace,          /* Unaligned space available to hold the object */
55870  int szSpace            /* Size of pSpace[] in bytes */
55871){
55872  const unsigned char *aKey = (const unsigned char *)pKey;
55873  UnpackedRecord *p;  /* The unpacked record that we will return */
55874  int nByte;          /* Memory space needed to hold p, in bytes */
55875  int d;
55876  u32 idx;
55877  u16 u;              /* Unsigned loop counter */
55878  u32 szHdr;
55879  Mem *pMem;
55880  int nOff;           /* Increase pSpace by this much to 8-byte align it */
55881
55882  /*
55883  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
55884  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
55885  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
55886  */
55887  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
55888  pSpace += nOff;
55889  szSpace -= nOff;
55890  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
55891  if( nByte>szSpace ){
55892    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
55893    if( p==0 ) return 0;
55894    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
55895  }else{
55896    p = (UnpackedRecord*)pSpace;
55897    p->flags = UNPACKED_NEED_DESTROY;
55898  }
55899  p->pKeyInfo = pKeyInfo;
55900  p->nField = pKeyInfo->nField + 1;
55901  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
55902  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
55903  idx = getVarint32(aKey, szHdr);
55904  d = szHdr;
55905  u = 0;
55906  while( idx<szHdr && u<p->nField && d<=nKey ){
55907    u32 serial_type;
55908
55909    idx += getVarint32(&aKey[idx], serial_type);
55910    pMem->enc = pKeyInfo->enc;
55911    pMem->db = pKeyInfo->db;
55912    pMem->flags = 0;
55913    pMem->zMalloc = 0;
55914    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
55915    pMem++;
55916    u++;
55917  }
55918  assert( u<=pKeyInfo->nField + 1 );
55919  p->nField = u;
55920  return (void*)p;
55921}
55922
55923/*
55924** This routine destroys a UnpackedRecord object.
55925*/
55926SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
55927  int i;
55928  Mem *pMem;
55929
55930  assert( p!=0 );
55931  assert( p->flags & UNPACKED_NEED_DESTROY );
55932  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
55933    /* The unpacked record is always constructed by the
55934    ** sqlite3VdbeUnpackRecord() function above, which makes all
55935    ** strings and blobs static.  And none of the elements are
55936    ** ever transformed, so there is never anything to delete.
55937    */
55938    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
55939  }
55940  if( p->flags & UNPACKED_NEED_FREE ){
55941    sqlite3DbFree(p->pKeyInfo->db, p);
55942  }
55943}
55944
55945/*
55946** This function compares the two table rows or index records
55947** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
55948** or positive integer if key1 is less than, equal to or
55949** greater than key2.  The {nKey1, pKey1} key must be a blob
55950** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
55951** key must be a parsed key such as obtained from
55952** sqlite3VdbeParseRecord.
55953**
55954** Key1 and Key2 do not have to contain the same number of fields.
55955** The key with fewer fields is usually compares less than the
55956** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
55957** and the common prefixes are equal, then key1 is less than key2.
55958** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
55959** equal, then the keys are considered to be equal and
55960** the parts beyond the common prefix are ignored.
55961**
55962** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
55963** the header of pKey1 is ignored.  It is assumed that pKey1 is
55964** an index key, and thus ends with a rowid value.  The last byte
55965** of the header will therefore be the serial type of the rowid:
55966** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
55967** The serial type of the final rowid will always be a single byte.
55968** By ignoring this last byte of the header, we force the comparison
55969** to ignore the rowid at the end of key1.
55970*/
55971SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
55972  int nKey1, const void *pKey1, /* Left key */
55973  UnpackedRecord *pPKey2        /* Right key */
55974){
55975  int d1;            /* Offset into aKey[] of next data element */
55976  u32 idx1;          /* Offset into aKey[] of next header element */
55977  u32 szHdr1;        /* Number of bytes in header */
55978  int i = 0;
55979  int nField;
55980  int rc = 0;
55981  const unsigned char *aKey1 = (const unsigned char *)pKey1;
55982  KeyInfo *pKeyInfo;
55983  Mem mem1;
55984
55985  pKeyInfo = pPKey2->pKeyInfo;
55986  mem1.enc = pKeyInfo->enc;
55987  mem1.db = pKeyInfo->db;
55988  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
55989  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
55990
55991  /* Compilers may complain that mem1.u.i is potentially uninitialized.
55992  ** We could initialize it, as shown here, to silence those complaints.
55993  ** But in fact, mem1.u.i will never actually be used initialized, and doing
55994  ** the unnecessary initialization has a measurable negative performance
55995  ** impact, since this routine is a very high runner.  And so, we choose
55996  ** to ignore the compiler warnings and leave this variable uninitialized.
55997  */
55998  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
55999
56000  idx1 = getVarint32(aKey1, szHdr1);
56001  d1 = szHdr1;
56002  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
56003    szHdr1--;
56004  }
56005  nField = pKeyInfo->nField;
56006  while( idx1<szHdr1 && i<pPKey2->nField ){
56007    u32 serial_type1;
56008
56009    /* Read the serial types for the next element in each key. */
56010    idx1 += getVarint32( aKey1+idx1, serial_type1 );
56011    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
56012
56013    /* Extract the values to be compared.
56014    */
56015    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
56016
56017    /* Do the comparison
56018    */
56019    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
56020                           i<nField ? pKeyInfo->aColl[i] : 0);
56021    if( rc!=0 ){
56022      assert( mem1.zMalloc==0 );  /* See comment below */
56023
56024      /* Invert the result if we are using DESC sort order. */
56025      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
56026        rc = -rc;
56027      }
56028
56029      /* If the PREFIX_SEARCH flag is set and all fields except the final
56030      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
56031      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
56032      ** This is used by the OP_IsUnique opcode.
56033      */
56034      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
56035        assert( idx1==szHdr1 && rc );
56036        assert( mem1.flags & MEM_Int );
56037        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
56038        pPKey2->rowid = mem1.u.i;
56039      }
56040
56041      return rc;
56042    }
56043    i++;
56044  }
56045
56046  /* No memory allocation is ever used on mem1.  Prove this using
56047  ** the following assert().  If the assert() fails, it indicates a
56048  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
56049  */
56050  assert( mem1.zMalloc==0 );
56051
56052  /* rc==0 here means that one of the keys ran out of fields and
56053  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
56054  ** flag is set, then break the tie by treating key2 as larger.
56055  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
56056  ** are considered to be equal.  Otherwise, the longer key is the
56057  ** larger.  As it happens, the pPKey2 will always be the longer
56058  ** if there is a difference.
56059  */
56060  assert( rc==0 );
56061  if( pPKey2->flags & UNPACKED_INCRKEY ){
56062    rc = -1;
56063  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
56064    /* Leave rc==0 */
56065  }else if( idx1<szHdr1 ){
56066    rc = 1;
56067  }
56068  return rc;
56069}
56070
56071
56072/*
56073** pCur points at an index entry created using the OP_MakeRecord opcode.
56074** Read the rowid (the last field in the record) and store it in *rowid.
56075** Return SQLITE_OK if everything works, or an error code otherwise.
56076**
56077** pCur might be pointing to text obtained from a corrupt database file.
56078** So the content cannot be trusted.  Do appropriate checks on the content.
56079*/
56080SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
56081  i64 nCellKey = 0;
56082  int rc;
56083  u32 szHdr;        /* Size of the header */
56084  u32 typeRowid;    /* Serial type of the rowid */
56085  u32 lenRowid;     /* Size of the rowid */
56086  Mem m, v;
56087
56088  UNUSED_PARAMETER(db);
56089
56090  /* Get the size of the index entry.  Only indices entries of less
56091  ** than 2GiB are support - anything large must be database corruption.
56092  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
56093  ** this code can safely assume that nCellKey is 32-bits
56094  */
56095  assert( sqlite3BtreeCursorIsValid(pCur) );
56096  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56097  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
56098  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
56099
56100  /* Read in the complete content of the index entry */
56101  memset(&m, 0, sizeof(m));
56102  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
56103  if( rc ){
56104    return rc;
56105  }
56106
56107  /* The index entry must begin with a header size */
56108  (void)getVarint32((u8*)m.z, szHdr);
56109  testcase( szHdr==3 );
56110  testcase( szHdr==m.n );
56111  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
56112    goto idx_rowid_corruption;
56113  }
56114
56115  /* The last field of the index should be an integer - the ROWID.
56116  ** Verify that the last entry really is an integer. */
56117  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
56118  testcase( typeRowid==1 );
56119  testcase( typeRowid==2 );
56120  testcase( typeRowid==3 );
56121  testcase( typeRowid==4 );
56122  testcase( typeRowid==5 );
56123  testcase( typeRowid==6 );
56124  testcase( typeRowid==8 );
56125  testcase( typeRowid==9 );
56126  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
56127    goto idx_rowid_corruption;
56128  }
56129  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
56130  testcase( (u32)m.n==szHdr+lenRowid );
56131  if( unlikely((u32)m.n<szHdr+lenRowid) ){
56132    goto idx_rowid_corruption;
56133  }
56134
56135  /* Fetch the integer off the end of the index record */
56136  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
56137  *rowid = v.u.i;
56138  sqlite3VdbeMemRelease(&m);
56139  return SQLITE_OK;
56140
56141  /* Jump here if database corruption is detected after m has been
56142  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
56143idx_rowid_corruption:
56144  testcase( m.zMalloc!=0 );
56145  sqlite3VdbeMemRelease(&m);
56146  return SQLITE_CORRUPT_BKPT;
56147}
56148
56149/*
56150** Compare the key of the index entry that cursor pC is pointing to against
56151** the key string in pUnpacked.  Write into *pRes a number
56152** that is negative, zero, or positive if pC is less than, equal to,
56153** or greater than pUnpacked.  Return SQLITE_OK on success.
56154**
56155** pUnpacked is either created without a rowid or is truncated so that it
56156** omits the rowid at the end.  The rowid at the end of the index entry
56157** is ignored as well.  Hence, this routine only compares the prefixes
56158** of the keys prior to the final rowid, not the entire key.
56159*/
56160SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
56161  VdbeCursor *pC,             /* The cursor to compare against */
56162  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
56163  int *res                    /* Write the comparison result here */
56164){
56165  i64 nCellKey = 0;
56166  int rc;
56167  BtCursor *pCur = pC->pCursor;
56168  Mem m;
56169
56170  assert( sqlite3BtreeCursorIsValid(pCur) );
56171  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56172  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
56173  /* nCellKey will always be between 0 and 0xffffffff because of the say
56174  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
56175  if( nCellKey<=0 || nCellKey>0x7fffffff ){
56176    *res = 0;
56177    return SQLITE_CORRUPT_BKPT;
56178  }
56179  memset(&m, 0, sizeof(m));
56180  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
56181  if( rc ){
56182    return rc;
56183  }
56184  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
56185  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
56186  sqlite3VdbeMemRelease(&m);
56187  return SQLITE_OK;
56188}
56189
56190/*
56191** This routine sets the value to be returned by subsequent calls to
56192** sqlite3_changes() on the database handle 'db'.
56193*/
56194SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
56195  assert( sqlite3_mutex_held(db->mutex) );
56196  db->nChange = nChange;
56197  db->nTotalChange += nChange;
56198}
56199
56200/*
56201** Set a flag in the vdbe to update the change counter when it is finalised
56202** or reset.
56203*/
56204SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
56205  v->changeCntOn = 1;
56206}
56207
56208/*
56209** Mark every prepared statement associated with a database connection
56210** as expired.
56211**
56212** An expired statement means that recompilation of the statement is
56213** recommend.  Statements expire when things happen that make their
56214** programs obsolete.  Removing user-defined functions or collating
56215** sequences, or changing an authorization function are the types of
56216** things that make prepared statements obsolete.
56217*/
56218SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
56219  Vdbe *p;
56220  for(p = db->pVdbe; p; p=p->pNext){
56221    p->expired = 1;
56222  }
56223}
56224
56225/*
56226** Return the database associated with the Vdbe.
56227*/
56228SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
56229  return v->db;
56230}
56231
56232/*
56233** Return a pointer to an sqlite3_value structure containing the value bound
56234** parameter iVar of VM v. Except, if the value is an SQL NULL, return
56235** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
56236** constants) to the value before returning it.
56237**
56238** The returned value must be freed by the caller using sqlite3ValueFree().
56239*/
56240SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
56241  assert( iVar>0 );
56242  if( v ){
56243    Mem *pMem = &v->aVar[iVar-1];
56244    if( 0==(pMem->flags & MEM_Null) ){
56245      sqlite3_value *pRet = sqlite3ValueNew(v->db);
56246      if( pRet ){
56247        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
56248        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
56249        sqlite3VdbeMemStoreType((Mem *)pRet);
56250      }
56251      return pRet;
56252    }
56253  }
56254  return 0;
56255}
56256
56257/*
56258** Configure SQL variable iVar so that binding a new value to it signals
56259** to sqlite3_reoptimize() that re-preparing the statement may result
56260** in a better query plan.
56261*/
56262SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
56263  assert( iVar>0 );
56264  if( iVar>32 ){
56265    v->expmask = 0xffffffff;
56266  }else{
56267    v->expmask |= ((u32)1 << (iVar-1));
56268  }
56269}
56270
56271/************** End of vdbeaux.c *********************************************/
56272/************** Begin file vdbeapi.c *****************************************/
56273/*
56274** 2004 May 26
56275**
56276** The author disclaims copyright to this source code.  In place of
56277** a legal notice, here is a blessing:
56278**
56279**    May you do good and not evil.
56280**    May you find forgiveness for yourself and forgive others.
56281**    May you share freely, never taking more than you give.
56282**
56283*************************************************************************
56284**
56285** This file contains code use to implement APIs that are part of the
56286** VDBE.
56287*/
56288
56289#ifndef SQLITE_OMIT_DEPRECATED
56290/*
56291** Return TRUE (non-zero) of the statement supplied as an argument needs
56292** to be recompiled.  A statement needs to be recompiled whenever the
56293** execution environment changes in a way that would alter the program
56294** that sqlite3_prepare() generates.  For example, if new functions or
56295** collating sequences are registered or if an authorizer function is
56296** added or changed.
56297*/
56298SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
56299  Vdbe *p = (Vdbe*)pStmt;
56300  return p==0 || p->expired;
56301}
56302#endif
56303
56304/*
56305** Check on a Vdbe to make sure it has not been finalized.  Log
56306** an error and return true if it has been finalized (or is otherwise
56307** invalid).  Return false if it is ok.
56308*/
56309static int vdbeSafety(Vdbe *p){
56310  if( p->db==0 ){
56311    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
56312    return 1;
56313  }else{
56314    return 0;
56315  }
56316}
56317static int vdbeSafetyNotNull(Vdbe *p){
56318  if( p==0 ){
56319    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
56320    return 1;
56321  }else{
56322    return vdbeSafety(p);
56323  }
56324}
56325
56326/*
56327** The following routine destroys a virtual machine that is created by
56328** the sqlite3_compile() routine. The integer returned is an SQLITE_
56329** success/failure code that describes the result of executing the virtual
56330** machine.
56331**
56332** This routine sets the error code and string returned by
56333** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56334*/
56335SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
56336  int rc;
56337  if( pStmt==0 ){
56338    rc = SQLITE_OK;
56339  }else{
56340    Vdbe *v = (Vdbe*)pStmt;
56341    sqlite3 *db = v->db;
56342#if SQLITE_THREADSAFE
56343    sqlite3_mutex *mutex;
56344#endif
56345    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
56346#if SQLITE_THREADSAFE
56347    mutex = v->db->mutex;
56348#endif
56349    sqlite3_mutex_enter(mutex);
56350    rc = sqlite3VdbeFinalize(v);
56351    rc = sqlite3ApiExit(db, rc);
56352    sqlite3_mutex_leave(mutex);
56353  }
56354  return rc;
56355}
56356
56357/*
56358** Terminate the current execution of an SQL statement and reset it
56359** back to its starting state so that it can be reused. A success code from
56360** the prior execution is returned.
56361**
56362** This routine sets the error code and string returned by
56363** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56364*/
56365SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
56366  int rc;
56367  if( pStmt==0 ){
56368    rc = SQLITE_OK;
56369  }else{
56370    Vdbe *v = (Vdbe*)pStmt;
56371    sqlite3_mutex_enter(v->db->mutex);
56372    rc = sqlite3VdbeReset(v);
56373    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
56374    assert( (rc & (v->db->errMask))==rc );
56375    rc = sqlite3ApiExit(v->db, rc);
56376    sqlite3_mutex_leave(v->db->mutex);
56377  }
56378  return rc;
56379}
56380
56381/*
56382** Set all the parameters in the compiled SQL statement to NULL.
56383*/
56384SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
56385  int i;
56386  int rc = SQLITE_OK;
56387  Vdbe *p = (Vdbe*)pStmt;
56388#if SQLITE_THREADSAFE
56389  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
56390#endif
56391  sqlite3_mutex_enter(mutex);
56392  for(i=0; i<p->nVar; i++){
56393    sqlite3VdbeMemRelease(&p->aVar[i]);
56394    p->aVar[i].flags = MEM_Null;
56395  }
56396  if( p->isPrepareV2 && p->expmask ){
56397    p->expired = 1;
56398  }
56399  sqlite3_mutex_leave(mutex);
56400  return rc;
56401}
56402
56403
56404/**************************** sqlite3_value_  *******************************
56405** The following routines extract information from a Mem or sqlite3_value
56406** structure.
56407*/
56408SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
56409  Mem *p = (Mem*)pVal;
56410  if( p->flags & (MEM_Blob|MEM_Str) ){
56411    sqlite3VdbeMemExpandBlob(p);
56412    p->flags &= ~MEM_Str;
56413    p->flags |= MEM_Blob;
56414    return p->z;
56415  }else{
56416    return sqlite3_value_text(pVal);
56417  }
56418}
56419SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
56420  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
56421}
56422SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
56423  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
56424}
56425SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
56426  return sqlite3VdbeRealValue((Mem*)pVal);
56427}
56428SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
56429  return (int)sqlite3VdbeIntValue((Mem*)pVal);
56430}
56431SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
56432  return sqlite3VdbeIntValue((Mem*)pVal);
56433}
56434SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
56435  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
56436}
56437#ifndef SQLITE_OMIT_UTF16
56438SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
56439  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
56440}
56441SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
56442  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
56443}
56444SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
56445  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
56446}
56447#endif /* SQLITE_OMIT_UTF16 */
56448SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
56449  return pVal->type;
56450}
56451
56452/**************************** sqlite3_result_  *******************************
56453** The following routines are used by user-defined functions to specify
56454** the function result.
56455**
56456** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
56457** result as a string or blob but if the string or blob is too large, it
56458** then sets the error code to SQLITE_TOOBIG
56459*/
56460static void setResultStrOrError(
56461  sqlite3_context *pCtx,  /* Function context */
56462  const char *z,          /* String pointer */
56463  int n,                  /* Bytes in string, or negative */
56464  u8 enc,                 /* Encoding of z.  0 for BLOBs */
56465  void (*xDel)(void*)     /* Destructor function */
56466){
56467  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
56468    sqlite3_result_error_toobig(pCtx);
56469  }
56470}
56471SQLITE_API void sqlite3_result_blob(
56472  sqlite3_context *pCtx,
56473  const void *z,
56474  int n,
56475  void (*xDel)(void *)
56476){
56477  assert( n>=0 );
56478  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56479  setResultStrOrError(pCtx, z, n, 0, xDel);
56480}
56481SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
56482  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56483  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
56484}
56485SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
56486  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56487  pCtx->isError = SQLITE_ERROR;
56488  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
56489}
56490#ifndef SQLITE_OMIT_UTF16
56491SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
56492  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56493  pCtx->isError = SQLITE_ERROR;
56494  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
56495}
56496#endif
56497SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
56498  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56499  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
56500}
56501SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
56502  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56503  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
56504}
56505SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
56506  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56507  sqlite3VdbeMemSetNull(&pCtx->s);
56508}
56509SQLITE_API void sqlite3_result_text(
56510  sqlite3_context *pCtx,
56511  const char *z,
56512  int n,
56513  void (*xDel)(void *)
56514){
56515  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56516  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
56517}
56518#ifndef SQLITE_OMIT_UTF16
56519SQLITE_API void sqlite3_result_text16(
56520  sqlite3_context *pCtx,
56521  const void *z,
56522  int n,
56523  void (*xDel)(void *)
56524){
56525  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56526  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
56527}
56528SQLITE_API void sqlite3_result_text16be(
56529  sqlite3_context *pCtx,
56530  const void *z,
56531  int n,
56532  void (*xDel)(void *)
56533){
56534  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56535  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
56536}
56537SQLITE_API void sqlite3_result_text16le(
56538  sqlite3_context *pCtx,
56539  const void *z,
56540  int n,
56541  void (*xDel)(void *)
56542){
56543  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56544  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
56545}
56546#endif /* SQLITE_OMIT_UTF16 */
56547SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
56548  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56549  sqlite3VdbeMemCopy(&pCtx->s, pValue);
56550}
56551SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
56552  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56553  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
56554}
56555SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
56556  pCtx->isError = errCode;
56557  if( pCtx->s.flags & MEM_Null ){
56558    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
56559                         SQLITE_UTF8, SQLITE_STATIC);
56560  }
56561}
56562
56563/* Force an SQLITE_TOOBIG error. */
56564SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
56565  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56566  pCtx->isError = SQLITE_TOOBIG;
56567  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
56568                       SQLITE_UTF8, SQLITE_STATIC);
56569}
56570
56571/* An SQLITE_NOMEM error. */
56572SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
56573  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56574  sqlite3VdbeMemSetNull(&pCtx->s);
56575  pCtx->isError = SQLITE_NOMEM;
56576  pCtx->s.db->mallocFailed = 1;
56577}
56578
56579/*
56580** This function is called after a transaction has been committed. It
56581** invokes callbacks registered with sqlite3_wal_hook() as required.
56582*/
56583static int doWalCallbacks(sqlite3 *db){
56584  int rc = SQLITE_OK;
56585#ifndef SQLITE_OMIT_WAL
56586  int i;
56587  for(i=0; i<db->nDb; i++){
56588    Btree *pBt = db->aDb[i].pBt;
56589    if( pBt ){
56590      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
56591      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
56592        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
56593      }
56594    }
56595  }
56596#endif
56597  return rc;
56598}
56599
56600/*
56601** Execute the statement pStmt, either until a row of data is ready, the
56602** statement is completely executed or an error occurs.
56603**
56604** This routine implements the bulk of the logic behind the sqlite_step()
56605** API.  The only thing omitted is the automatic recompile if a
56606** schema change has occurred.  That detail is handled by the
56607** outer sqlite3_step() wrapper procedure.
56608*/
56609static int sqlite3Step(Vdbe *p){
56610  sqlite3 *db;
56611  int rc;
56612
56613  assert(p);
56614  if( p->magic!=VDBE_MAGIC_RUN ){
56615    /* We used to require that sqlite3_reset() be called before retrying
56616    ** sqlite3_step() after any error.  But after 3.6.23, we changed this
56617    ** so that sqlite3_reset() would be called automatically instead of
56618    ** throwing the error.
56619    */
56620    sqlite3_reset((sqlite3_stmt*)p);
56621  }
56622
56623  /* Check that malloc() has not failed. If it has, return early. */
56624  db = p->db;
56625  if( db->mallocFailed ){
56626    p->rc = SQLITE_NOMEM;
56627    return SQLITE_NOMEM;
56628  }
56629
56630  if( p->pc<=0 && p->expired ){
56631    p->rc = SQLITE_SCHEMA;
56632    rc = SQLITE_ERROR;
56633    goto end_of_step;
56634  }
56635  if( p->pc<0 ){
56636    /* If there are no other statements currently running, then
56637    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
56638    ** from interrupting a statement that has not yet started.
56639    */
56640    if( db->activeVdbeCnt==0 ){
56641      db->u1.isInterrupted = 0;
56642    }
56643
56644    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
56645
56646#ifndef SQLITE_OMIT_TRACE
56647    if( db->xProfile && !db->init.busy ){
56648      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
56649    }
56650#endif
56651
56652    db->activeVdbeCnt++;
56653    if( p->readOnly==0 ) db->writeVdbeCnt++;
56654    p->pc = 0;
56655  }
56656#ifndef SQLITE_OMIT_EXPLAIN
56657  if( p->explain ){
56658    rc = sqlite3VdbeList(p);
56659  }else
56660#endif /* SQLITE_OMIT_EXPLAIN */
56661  {
56662    rc = sqlite3VdbeExec(p);
56663  }
56664
56665#ifndef SQLITE_OMIT_TRACE
56666  /* Invoke the profile callback if there is one
56667  */
56668  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
56669    sqlite3_int64 iNow;
56670    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
56671    db->xProfile(db->pProfileArg, p->zSql, iNow - p->startTime);
56672  }
56673#endif
56674
56675  if( rc==SQLITE_DONE ){
56676    assert( p->rc==SQLITE_OK );
56677    p->rc = doWalCallbacks(db);
56678    if( p->rc!=SQLITE_OK ){
56679      rc = SQLITE_ERROR;
56680    }
56681  }
56682
56683  db->errCode = rc;
56684  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
56685    p->rc = SQLITE_NOMEM;
56686  }
56687end_of_step:
56688  /* At this point local variable rc holds the value that should be
56689  ** returned if this statement was compiled using the legacy
56690  ** sqlite3_prepare() interface. According to the docs, this can only
56691  ** be one of the values in the first assert() below. Variable p->rc
56692  ** contains the value that would be returned if sqlite3_finalize()
56693  ** were called on statement p.
56694  */
56695  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
56696       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
56697  );
56698  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
56699  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
56700    /* If this statement was prepared using sqlite3_prepare_v2(), and an
56701    ** error has occured, then return the error code in p->rc to the
56702    ** caller. Set the error code in the database handle to the same value.
56703    */
56704    rc = db->errCode = p->rc;
56705  }
56706  return (rc&db->errMask);
56707}
56708
56709/*
56710** This is the top-level implementation of sqlite3_step().  Call
56711** sqlite3Step() to do most of the work.  If a schema error occurs,
56712** call sqlite3Reprepare() and try again.
56713*/
56714SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
56715  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
56716  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
56717  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
56718  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
56719  sqlite3 *db;             /* The database connection */
56720
56721  if( vdbeSafetyNotNull(v) ){
56722    return SQLITE_MISUSE_BKPT;
56723  }
56724  db = v->db;
56725  sqlite3_mutex_enter(db->mutex);
56726  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
56727         && cnt++ < 5
56728         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
56729    sqlite3_reset(pStmt);
56730    v->expired = 0;
56731  }
56732  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
56733    /* This case occurs after failing to recompile an sql statement.
56734    ** The error message from the SQL compiler has already been loaded
56735    ** into the database handle. This block copies the error message
56736    ** from the database handle into the statement and sets the statement
56737    ** program counter to 0 to ensure that when the statement is
56738    ** finalized or reset the parser error message is available via
56739    ** sqlite3_errmsg() and sqlite3_errcode().
56740    */
56741    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
56742    sqlite3DbFree(db, v->zErrMsg);
56743    if( !db->mallocFailed ){
56744      v->zErrMsg = sqlite3DbStrDup(db, zErr);
56745      v->rc = rc2;
56746    } else {
56747      v->zErrMsg = 0;
56748      v->rc = rc = SQLITE_NOMEM;
56749    }
56750  }
56751  rc = sqlite3ApiExit(db, rc);
56752  sqlite3_mutex_leave(db->mutex);
56753  return rc;
56754}
56755
56756/*
56757** Extract the user data from a sqlite3_context structure and return a
56758** pointer to it.
56759*/
56760SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
56761  assert( p && p->pFunc );
56762  return p->pFunc->pUserData;
56763}
56764
56765/*
56766** Extract the user data from a sqlite3_context structure and return a
56767** pointer to it.
56768*/
56769SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
56770  assert( p && p->pFunc );
56771  return p->s.db;
56772}
56773
56774/*
56775** The following is the implementation of an SQL function that always
56776** fails with an error message stating that the function is used in the
56777** wrong context.  The sqlite3_overload_function() API might construct
56778** SQL function that use this routine so that the functions will exist
56779** for name resolution but are actually overloaded by the xFindFunction
56780** method of virtual tables.
56781*/
56782SQLITE_PRIVATE void sqlite3InvalidFunction(
56783  sqlite3_context *context,  /* The function calling context */
56784  int NotUsed,               /* Number of arguments to the function */
56785  sqlite3_value **NotUsed2   /* Value of each argument */
56786){
56787  const char *zName = context->pFunc->zName;
56788  char *zErr;
56789  UNUSED_PARAMETER2(NotUsed, NotUsed2);
56790  zErr = sqlite3_mprintf(
56791      "unable to use function %s in the requested context", zName);
56792  sqlite3_result_error(context, zErr, -1);
56793  sqlite3_free(zErr);
56794}
56795
56796/*
56797** Allocate or return the aggregate context for a user function.  A new
56798** context is allocated on the first call.  Subsequent calls return the
56799** same context that was returned on prior calls.
56800*/
56801SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
56802  Mem *pMem;
56803  assert( p && p->pFunc && p->pFunc->xStep );
56804  assert( sqlite3_mutex_held(p->s.db->mutex) );
56805  pMem = p->pMem;
56806  testcase( nByte<0 );
56807  if( (pMem->flags & MEM_Agg)==0 ){
56808    if( nByte<=0 ){
56809      sqlite3VdbeMemReleaseExternal(pMem);
56810      pMem->flags = MEM_Null;
56811      pMem->z = 0;
56812    }else{
56813      sqlite3VdbeMemGrow(pMem, nByte, 0);
56814      pMem->flags = MEM_Agg;
56815      pMem->u.pDef = p->pFunc;
56816      if( pMem->z ){
56817        memset(pMem->z, 0, nByte);
56818      }
56819    }
56820  }
56821  return (void*)pMem->z;
56822}
56823
56824/*
56825** Return the auxilary data pointer, if any, for the iArg'th argument to
56826** the user-function defined by pCtx.
56827*/
56828SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
56829  VdbeFunc *pVdbeFunc;
56830
56831  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56832  pVdbeFunc = pCtx->pVdbeFunc;
56833  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
56834    return 0;
56835  }
56836  return pVdbeFunc->apAux[iArg].pAux;
56837}
56838
56839/*
56840** Set the auxilary data pointer and delete function, for the iArg'th
56841** argument to the user-function defined by pCtx. Any previous value is
56842** deleted by calling the delete function specified when it was set.
56843*/
56844SQLITE_API void sqlite3_set_auxdata(
56845  sqlite3_context *pCtx,
56846  int iArg,
56847  void *pAux,
56848  void (*xDelete)(void*)
56849){
56850  struct AuxData *pAuxData;
56851  VdbeFunc *pVdbeFunc;
56852  if( iArg<0 ) goto failed;
56853
56854  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56855  pVdbeFunc = pCtx->pVdbeFunc;
56856  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
56857    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
56858    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
56859    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
56860    if( !pVdbeFunc ){
56861      goto failed;
56862    }
56863    pCtx->pVdbeFunc = pVdbeFunc;
56864    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
56865    pVdbeFunc->nAux = iArg+1;
56866    pVdbeFunc->pFunc = pCtx->pFunc;
56867  }
56868
56869  pAuxData = &pVdbeFunc->apAux[iArg];
56870  if( pAuxData->pAux && pAuxData->xDelete ){
56871    pAuxData->xDelete(pAuxData->pAux);
56872  }
56873  pAuxData->pAux = pAux;
56874  pAuxData->xDelete = xDelete;
56875  return;
56876
56877failed:
56878  if( xDelete ){
56879    xDelete(pAux);
56880  }
56881}
56882
56883#ifndef SQLITE_OMIT_DEPRECATED
56884/*
56885** Return the number of times the Step function of a aggregate has been
56886** called.
56887**
56888** This function is deprecated.  Do not use it for new code.  It is
56889** provide only to avoid breaking legacy code.  New aggregate function
56890** implementations should keep their own counts within their aggregate
56891** context.
56892*/
56893SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
56894  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
56895  return p->pMem->n;
56896}
56897#endif
56898
56899/*
56900** Return the number of columns in the result set for the statement pStmt.
56901*/
56902SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
56903  Vdbe *pVm = (Vdbe *)pStmt;
56904  return pVm ? pVm->nResColumn : 0;
56905}
56906
56907/*
56908** Return the number of values available from the current row of the
56909** currently executing statement pStmt.
56910*/
56911SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
56912  Vdbe *pVm = (Vdbe *)pStmt;
56913  if( pVm==0 || pVm->pResultSet==0 ) return 0;
56914  return pVm->nResColumn;
56915}
56916
56917
56918/*
56919** Check to see if column iCol of the given statement is valid.  If
56920** it is, return a pointer to the Mem for the value of that column.
56921** If iCol is not valid, return a pointer to a Mem which has a value
56922** of NULL.
56923*/
56924static Mem *columnMem(sqlite3_stmt *pStmt, int i){
56925  Vdbe *pVm;
56926  int vals;
56927  Mem *pOut;
56928
56929  pVm = (Vdbe *)pStmt;
56930  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
56931    sqlite3_mutex_enter(pVm->db->mutex);
56932    vals = sqlite3_data_count(pStmt);
56933    pOut = &pVm->pResultSet[i];
56934  }else{
56935    /* If the value passed as the second argument is out of range, return
56936    ** a pointer to the following static Mem object which contains the
56937    ** value SQL NULL. Even though the Mem structure contains an element
56938    ** of type i64, on certain architecture (x86) with certain compiler
56939    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
56940    ** instead of an 8-byte one. This all works fine, except that when
56941    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
56942    ** that a Mem structure is located on an 8-byte boundary. To prevent
56943    ** this assert() from failing, when building with SQLITE_DEBUG defined
56944    ** using gcc, force nullMem to be 8-byte aligned using the magical
56945    ** __attribute__((aligned(8))) macro.  */
56946    static const Mem nullMem
56947#if defined(SQLITE_DEBUG) && defined(__GNUC__)
56948      __attribute__((aligned(8)))
56949#endif
56950      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
56951
56952    if( pVm && ALWAYS(pVm->db) ){
56953      sqlite3_mutex_enter(pVm->db->mutex);
56954      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
56955    }
56956    pOut = (Mem*)&nullMem;
56957  }
56958  return pOut;
56959}
56960
56961/*
56962** This function is called after invoking an sqlite3_value_XXX function on a
56963** column value (i.e. a value returned by evaluating an SQL expression in the
56964** select list of a SELECT statement) that may cause a malloc() failure. If
56965** malloc() has failed, the threads mallocFailed flag is cleared and the result
56966** code of statement pStmt set to SQLITE_NOMEM.
56967**
56968** Specifically, this is called from within:
56969**
56970**     sqlite3_column_int()
56971**     sqlite3_column_int64()
56972**     sqlite3_column_text()
56973**     sqlite3_column_text16()
56974**     sqlite3_column_real()
56975**     sqlite3_column_bytes()
56976**     sqlite3_column_bytes16()
56977**
56978** But not for sqlite3_column_blob(), which never calls malloc().
56979*/
56980static void columnMallocFailure(sqlite3_stmt *pStmt)
56981{
56982  /* If malloc() failed during an encoding conversion within an
56983  ** sqlite3_column_XXX API, then set the return code of the statement to
56984  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
56985  ** and _finalize() will return NOMEM.
56986  */
56987  Vdbe *p = (Vdbe *)pStmt;
56988  if( p ){
56989    p->rc = sqlite3ApiExit(p->db, p->rc);
56990    sqlite3_mutex_leave(p->db->mutex);
56991  }
56992}
56993
56994/**************************** sqlite3_column_  *******************************
56995** The following routines are used to access elements of the current row
56996** in the result set.
56997*/
56998SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
56999  const void *val;
57000  val = sqlite3_value_blob( columnMem(pStmt,i) );
57001  /* Even though there is no encoding conversion, value_blob() might
57002  ** need to call malloc() to expand the result of a zeroblob()
57003  ** expression.
57004  */
57005  columnMallocFailure(pStmt);
57006  return val;
57007}
57008SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
57009  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
57010  columnMallocFailure(pStmt);
57011  return val;
57012}
57013SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
57014  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
57015  columnMallocFailure(pStmt);
57016  return val;
57017}
57018SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
57019  double val = sqlite3_value_double( columnMem(pStmt,i) );
57020  columnMallocFailure(pStmt);
57021  return val;
57022}
57023SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
57024  int val = sqlite3_value_int( columnMem(pStmt,i) );
57025  columnMallocFailure(pStmt);
57026  return val;
57027}
57028SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
57029  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
57030  columnMallocFailure(pStmt);
57031  return val;
57032}
57033SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
57034  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
57035  columnMallocFailure(pStmt);
57036  return val;
57037}
57038SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
57039  Mem *pOut = columnMem(pStmt, i);
57040  if( pOut->flags&MEM_Static ){
57041    pOut->flags &= ~MEM_Static;
57042    pOut->flags |= MEM_Ephem;
57043  }
57044  columnMallocFailure(pStmt);
57045  return (sqlite3_value *)pOut;
57046}
57047#ifndef SQLITE_OMIT_UTF16
57048SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
57049  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
57050  columnMallocFailure(pStmt);
57051  return val;
57052}
57053#endif /* SQLITE_OMIT_UTF16 */
57054SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
57055  int iType = sqlite3_value_type( columnMem(pStmt,i) );
57056  columnMallocFailure(pStmt);
57057  return iType;
57058}
57059
57060/* The following function is experimental and subject to change or
57061** removal */
57062/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
57063**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
57064**}
57065*/
57066
57067/*
57068** Convert the N-th element of pStmt->pColName[] into a string using
57069** xFunc() then return that string.  If N is out of range, return 0.
57070**
57071** There are up to 5 names for each column.  useType determines which
57072** name is returned.  Here are the names:
57073**
57074**    0      The column name as it should be displayed for output
57075**    1      The datatype name for the column
57076**    2      The name of the database that the column derives from
57077**    3      The name of the table that the column derives from
57078**    4      The name of the table column that the result column derives from
57079**
57080** If the result is not a simple column reference (if it is an expression
57081** or a constant) then useTypes 2, 3, and 4 return NULL.
57082*/
57083static const void *columnName(
57084  sqlite3_stmt *pStmt,
57085  int N,
57086  const void *(*xFunc)(Mem*),
57087  int useType
57088){
57089  const void *ret = 0;
57090  Vdbe *p = (Vdbe *)pStmt;
57091  int n;
57092  sqlite3 *db = p->db;
57093
57094  assert( db!=0 );
57095  n = sqlite3_column_count(pStmt);
57096  if( N<n && N>=0 ){
57097    N += useType*n;
57098    sqlite3_mutex_enter(db->mutex);
57099    assert( db->mallocFailed==0 );
57100    ret = xFunc(&p->aColName[N]);
57101     /* A malloc may have failed inside of the xFunc() call. If this
57102    ** is the case, clear the mallocFailed flag and return NULL.
57103    */
57104    if( db->mallocFailed ){
57105      db->mallocFailed = 0;
57106      ret = 0;
57107    }
57108    sqlite3_mutex_leave(db->mutex);
57109  }
57110  return ret;
57111}
57112
57113/*
57114** Return the name of the Nth column of the result set returned by SQL
57115** statement pStmt.
57116*/
57117SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
57118  return columnName(
57119      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
57120}
57121#ifndef SQLITE_OMIT_UTF16
57122SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
57123  return columnName(
57124      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
57125}
57126#endif
57127
57128/*
57129** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
57130** not define OMIT_DECLTYPE.
57131*/
57132#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
57133# error "Must not define both SQLITE_OMIT_DECLTYPE \
57134         and SQLITE_ENABLE_COLUMN_METADATA"
57135#endif
57136
57137#ifndef SQLITE_OMIT_DECLTYPE
57138/*
57139** Return the column declaration type (if applicable) of the 'i'th column
57140** of the result set of SQL statement pStmt.
57141*/
57142SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
57143  return columnName(
57144      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
57145}
57146#ifndef SQLITE_OMIT_UTF16
57147SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
57148  return columnName(
57149      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
57150}
57151#endif /* SQLITE_OMIT_UTF16 */
57152#endif /* SQLITE_OMIT_DECLTYPE */
57153
57154#ifdef SQLITE_ENABLE_COLUMN_METADATA
57155/*
57156** Return the name of the database from which a result column derives.
57157** NULL is returned if the result column is an expression or constant or
57158** anything else which is not an unabiguous reference to a database column.
57159*/
57160SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
57161  return columnName(
57162      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
57163}
57164#ifndef SQLITE_OMIT_UTF16
57165SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
57166  return columnName(
57167      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
57168}
57169#endif /* SQLITE_OMIT_UTF16 */
57170
57171/*
57172** Return the name of the table from which a result column derives.
57173** NULL is returned if the result column is an expression or constant or
57174** anything else which is not an unabiguous reference to a database column.
57175*/
57176SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
57177  return columnName(
57178      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
57179}
57180#ifndef SQLITE_OMIT_UTF16
57181SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
57182  return columnName(
57183      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
57184}
57185#endif /* SQLITE_OMIT_UTF16 */
57186
57187/*
57188** Return the name of the table column from which a result column derives.
57189** NULL is returned if the result column is an expression or constant or
57190** anything else which is not an unabiguous reference to a database column.
57191*/
57192SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
57193  return columnName(
57194      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
57195}
57196#ifndef SQLITE_OMIT_UTF16
57197SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
57198  return columnName(
57199      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
57200}
57201#endif /* SQLITE_OMIT_UTF16 */
57202#endif /* SQLITE_ENABLE_COLUMN_METADATA */
57203
57204
57205/******************************* sqlite3_bind_  ***************************
57206**
57207** Routines used to attach values to wildcards in a compiled SQL statement.
57208*/
57209/*
57210** Unbind the value bound to variable i in virtual machine p. This is the
57211** the same as binding a NULL value to the column. If the "i" parameter is
57212** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
57213**
57214** A successful evaluation of this routine acquires the mutex on p.
57215** the mutex is released if any kind of error occurs.
57216**
57217** The error code stored in database p->db is overwritten with the return
57218** value in any case.
57219*/
57220static int vdbeUnbind(Vdbe *p, int i){
57221  Mem *pVar;
57222  if( vdbeSafetyNotNull(p) ){
57223    return SQLITE_MISUSE_BKPT;
57224  }
57225  sqlite3_mutex_enter(p->db->mutex);
57226  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
57227    sqlite3Error(p->db, SQLITE_MISUSE, 0);
57228    sqlite3_mutex_leave(p->db->mutex);
57229    sqlite3_log(SQLITE_MISUSE,
57230        "bind on a busy prepared statement: [%s]", p->zSql);
57231    return SQLITE_MISUSE_BKPT;
57232  }
57233  if( i<1 || i>p->nVar ){
57234    sqlite3Error(p->db, SQLITE_RANGE, 0);
57235    sqlite3_mutex_leave(p->db->mutex);
57236    return SQLITE_RANGE;
57237  }
57238  i--;
57239  pVar = &p->aVar[i];
57240  sqlite3VdbeMemRelease(pVar);
57241  pVar->flags = MEM_Null;
57242  sqlite3Error(p->db, SQLITE_OK, 0);
57243
57244  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
57245  ** binding a new value to this variable invalidates the current query plan.
57246  */
57247  if( p->isPrepareV2 &&
57248     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
57249  ){
57250    p->expired = 1;
57251  }
57252  return SQLITE_OK;
57253}
57254
57255/*
57256** Bind a text or BLOB value.
57257*/
57258static int bindText(
57259  sqlite3_stmt *pStmt,   /* The statement to bind against */
57260  int i,                 /* Index of the parameter to bind */
57261  const void *zData,     /* Pointer to the data to be bound */
57262  int nData,             /* Number of bytes of data to be bound */
57263  void (*xDel)(void*),   /* Destructor for the data */
57264  u8 encoding            /* Encoding for the data */
57265){
57266  Vdbe *p = (Vdbe *)pStmt;
57267  Mem *pVar;
57268  int rc;
57269
57270  rc = vdbeUnbind(p, i);
57271  if( rc==SQLITE_OK ){
57272    if( zData!=0 ){
57273      pVar = &p->aVar[i-1];
57274      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
57275      if( rc==SQLITE_OK && encoding!=0 ){
57276        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
57277      }
57278      sqlite3Error(p->db, rc, 0);
57279      rc = sqlite3ApiExit(p->db, rc);
57280    }
57281    sqlite3_mutex_leave(p->db->mutex);
57282  }
57283  return rc;
57284}
57285
57286
57287/*
57288** Bind a blob value to an SQL statement variable.
57289*/
57290SQLITE_API int sqlite3_bind_blob(
57291  sqlite3_stmt *pStmt,
57292  int i,
57293  const void *zData,
57294  int nData,
57295  void (*xDel)(void*)
57296){
57297  return bindText(pStmt, i, zData, nData, xDel, 0);
57298}
57299SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
57300  int rc;
57301  Vdbe *p = (Vdbe *)pStmt;
57302  rc = vdbeUnbind(p, i);
57303  if( rc==SQLITE_OK ){
57304    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
57305    sqlite3_mutex_leave(p->db->mutex);
57306  }
57307  return rc;
57308}
57309SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
57310  return sqlite3_bind_int64(p, i, (i64)iValue);
57311}
57312SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
57313  int rc;
57314  Vdbe *p = (Vdbe *)pStmt;
57315  rc = vdbeUnbind(p, i);
57316  if( rc==SQLITE_OK ){
57317    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
57318    sqlite3_mutex_leave(p->db->mutex);
57319  }
57320  return rc;
57321}
57322SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
57323  int rc;
57324  Vdbe *p = (Vdbe*)pStmt;
57325  rc = vdbeUnbind(p, i);
57326  if( rc==SQLITE_OK ){
57327    sqlite3_mutex_leave(p->db->mutex);
57328  }
57329  return rc;
57330}
57331SQLITE_API int sqlite3_bind_text(
57332  sqlite3_stmt *pStmt,
57333  int i,
57334  const char *zData,
57335  int nData,
57336  void (*xDel)(void*)
57337){
57338  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
57339}
57340#ifndef SQLITE_OMIT_UTF16
57341SQLITE_API int sqlite3_bind_text16(
57342  sqlite3_stmt *pStmt,
57343  int i,
57344  const void *zData,
57345  int nData,
57346  void (*xDel)(void*)
57347){
57348  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
57349}
57350#endif /* SQLITE_OMIT_UTF16 */
57351SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
57352  int rc;
57353  switch( pValue->type ){
57354    case SQLITE_INTEGER: {
57355      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
57356      break;
57357    }
57358    case SQLITE_FLOAT: {
57359      rc = sqlite3_bind_double(pStmt, i, pValue->r);
57360      break;
57361    }
57362    case SQLITE_BLOB: {
57363      if( pValue->flags & MEM_Zero ){
57364        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
57365      }else{
57366        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
57367      }
57368      break;
57369    }
57370    case SQLITE_TEXT: {
57371      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
57372                              pValue->enc);
57373      break;
57374    }
57375    default: {
57376      rc = sqlite3_bind_null(pStmt, i);
57377      break;
57378    }
57379  }
57380  return rc;
57381}
57382SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
57383  int rc;
57384  Vdbe *p = (Vdbe *)pStmt;
57385  rc = vdbeUnbind(p, i);
57386  if( rc==SQLITE_OK ){
57387    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
57388    sqlite3_mutex_leave(p->db->mutex);
57389  }
57390  return rc;
57391}
57392
57393/*
57394** Return the number of wildcards that can be potentially bound to.
57395** This routine is added to support DBD::SQLite.
57396*/
57397SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
57398  Vdbe *p = (Vdbe*)pStmt;
57399  return p ? p->nVar : 0;
57400}
57401
57402/*
57403** Create a mapping from variable numbers to variable names
57404** in the Vdbe.azVar[] array, if such a mapping does not already
57405** exist.
57406*/
57407static void createVarMap(Vdbe *p){
57408  if( !p->okVar ){
57409    int j;
57410    Op *pOp;
57411    sqlite3_mutex_enter(p->db->mutex);
57412    /* The race condition here is harmless.  If two threads call this
57413    ** routine on the same Vdbe at the same time, they both might end
57414    ** up initializing the Vdbe.azVar[] array.  That is a little extra
57415    ** work but it results in the same answer.
57416    */
57417    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
57418      if( pOp->opcode==OP_Variable ){
57419        assert( pOp->p1>0 && pOp->p1<=p->nVar );
57420        p->azVar[pOp->p1-1] = pOp->p4.z;
57421      }
57422    }
57423    p->okVar = 1;
57424    sqlite3_mutex_leave(p->db->mutex);
57425  }
57426}
57427
57428/*
57429** Return the name of a wildcard parameter.  Return NULL if the index
57430** is out of range or if the wildcard is unnamed.
57431**
57432** The result is always UTF-8.
57433*/
57434SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
57435  Vdbe *p = (Vdbe*)pStmt;
57436  if( p==0 || i<1 || i>p->nVar ){
57437    return 0;
57438  }
57439  createVarMap(p);
57440  return p->azVar[i-1];
57441}
57442
57443/*
57444** Given a wildcard parameter name, return the index of the variable
57445** with that name.  If there is no variable with the given name,
57446** return 0.
57447*/
57448SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
57449  int i;
57450  if( p==0 ){
57451    return 0;
57452  }
57453  createVarMap(p);
57454  if( zName ){
57455    for(i=0; i<p->nVar; i++){
57456      const char *z = p->azVar[i];
57457      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
57458        return i+1;
57459      }
57460    }
57461  }
57462  return 0;
57463}
57464SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
57465  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
57466}
57467
57468/*
57469** Transfer all bindings from the first statement over to the second.
57470*/
57471SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57472  Vdbe *pFrom = (Vdbe*)pFromStmt;
57473  Vdbe *pTo = (Vdbe*)pToStmt;
57474  int i;
57475  assert( pTo->db==pFrom->db );
57476  assert( pTo->nVar==pFrom->nVar );
57477  sqlite3_mutex_enter(pTo->db->mutex);
57478  for(i=0; i<pFrom->nVar; i++){
57479    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
57480  }
57481  sqlite3_mutex_leave(pTo->db->mutex);
57482  return SQLITE_OK;
57483}
57484
57485#ifndef SQLITE_OMIT_DEPRECATED
57486/*
57487** Deprecated external interface.  Internal/core SQLite code
57488** should call sqlite3TransferBindings.
57489**
57490** Is is misuse to call this routine with statements from different
57491** database connections.  But as this is a deprecated interface, we
57492** will not bother to check for that condition.
57493**
57494** If the two statements contain a different number of bindings, then
57495** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
57496** SQLITE_OK is returned.
57497*/
57498SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57499  Vdbe *pFrom = (Vdbe*)pFromStmt;
57500  Vdbe *pTo = (Vdbe*)pToStmt;
57501  if( pFrom->nVar!=pTo->nVar ){
57502    return SQLITE_ERROR;
57503  }
57504  if( pTo->isPrepareV2 && pTo->expmask ){
57505    pTo->expired = 1;
57506  }
57507  if( pFrom->isPrepareV2 && pFrom->expmask ){
57508    pFrom->expired = 1;
57509  }
57510  return sqlite3TransferBindings(pFromStmt, pToStmt);
57511}
57512#endif
57513
57514/*
57515** Return the sqlite3* database handle to which the prepared statement given
57516** in the argument belongs.  This is the same database handle that was
57517** the first argument to the sqlite3_prepare() that was used to create
57518** the statement in the first place.
57519*/
57520SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
57521  return pStmt ? ((Vdbe*)pStmt)->db : 0;
57522}
57523
57524/*
57525** Return a pointer to the next prepared statement after pStmt associated
57526** with database connection pDb.  If pStmt is NULL, return the first
57527** prepared statement for the database connection.  Return NULL if there
57528** are no more.
57529*/
57530SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
57531  sqlite3_stmt *pNext;
57532  sqlite3_mutex_enter(pDb->mutex);
57533  if( pStmt==0 ){
57534    pNext = (sqlite3_stmt*)pDb->pVdbe;
57535  }else{
57536    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
57537  }
57538  sqlite3_mutex_leave(pDb->mutex);
57539  return pNext;
57540}
57541
57542/*
57543** Return the value of a status counter for a prepared statement
57544*/
57545SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
57546  Vdbe *pVdbe = (Vdbe*)pStmt;
57547  int v = pVdbe->aCounter[op-1];
57548  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
57549  return v;
57550}
57551
57552/************** End of vdbeapi.c *********************************************/
57553/************** Begin file vdbetrace.c ***************************************/
57554/*
57555** 2009 November 25
57556**
57557** The author disclaims copyright to this source code.  In place of
57558** a legal notice, here is a blessing:
57559**
57560**    May you do good and not evil.
57561**    May you find forgiveness for yourself and forgive others.
57562**    May you share freely, never taking more than you give.
57563**
57564*************************************************************************
57565**
57566** This file contains code used to insert the values of host parameters
57567** (aka "wildcards") into the SQL text output by sqlite3_trace().
57568*/
57569
57570#ifndef SQLITE_OMIT_TRACE
57571
57572/*
57573** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
57574** bytes in this text up to but excluding the first character in
57575** a host parameter.  If the text contains no host parameters, return
57576** the total number of bytes in the text.
57577*/
57578static int findNextHostParameter(const char *zSql, int *pnToken){
57579  int tokenType;
57580  int nTotal = 0;
57581  int n;
57582
57583  *pnToken = 0;
57584  while( zSql[0] ){
57585    n = sqlite3GetToken((u8*)zSql, &tokenType);
57586    assert( n>0 && tokenType!=TK_ILLEGAL );
57587    if( tokenType==TK_VARIABLE ){
57588      *pnToken = n;
57589      break;
57590    }
57591    nTotal += n;
57592    zSql += n;
57593  }
57594  return nTotal;
57595}
57596
57597/*
57598** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
57599** holds a copy of zRawSql but with host parameters expanded to their
57600** current bindings.
57601**
57602** The calling function is responsible for making sure the memory returned
57603** is eventually freed.
57604**
57605** ALGORITHM:  Scan the input string looking for host parameters in any of
57606** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
57607** string literals, quoted identifier names, and comments.  For text forms,
57608** the host parameter index is found by scanning the perpared
57609** statement for the corresponding OP_Variable opcode.  Once the host
57610** parameter index is known, locate the value in p->aVar[].  Then render
57611** the value as a literal in place of the host parameter name.
57612*/
57613SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
57614  Vdbe *p,                 /* The prepared statement being evaluated */
57615  const char *zRawSql      /* Raw text of the SQL statement */
57616){
57617  sqlite3 *db;             /* The database connection */
57618  int idx = 0;             /* Index of a host parameter */
57619  int nextIndex = 1;       /* Index of next ? host parameter */
57620  int n;                   /* Length of a token prefix */
57621  int nToken;              /* Length of the parameter token */
57622  int i;                   /* Loop counter */
57623  Mem *pVar;               /* Value of a host parameter */
57624  StrAccum out;            /* Accumulate the output here */
57625  char zBase[100];         /* Initial working space */
57626
57627  db = p->db;
57628  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
57629                      db->aLimit[SQLITE_LIMIT_LENGTH]);
57630  out.db = db;
57631  while( zRawSql[0] ){
57632    n = findNextHostParameter(zRawSql, &nToken);
57633    assert( n>0 );
57634    sqlite3StrAccumAppend(&out, zRawSql, n);
57635    zRawSql += n;
57636    assert( zRawSql[0] || nToken==0 );
57637    if( nToken==0 ) break;
57638    if( zRawSql[0]=='?' ){
57639      if( nToken>1 ){
57640        assert( sqlite3Isdigit(zRawSql[1]) );
57641        sqlite3GetInt32(&zRawSql[1], &idx);
57642      }else{
57643        idx = nextIndex;
57644      }
57645    }else{
57646      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
57647      testcase( zRawSql[0]==':' );
57648      testcase( zRawSql[0]=='$' );
57649      testcase( zRawSql[0]=='@' );
57650      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
57651      assert( idx>0 );
57652    }
57653    zRawSql += nToken;
57654    nextIndex = idx + 1;
57655    assert( idx>0 && idx<=p->nVar );
57656    pVar = &p->aVar[idx-1];
57657    if( pVar->flags & MEM_Null ){
57658      sqlite3StrAccumAppend(&out, "NULL", 4);
57659    }else if( pVar->flags & MEM_Int ){
57660      sqlite3XPrintf(&out, "%lld", pVar->u.i);
57661    }else if( pVar->flags & MEM_Real ){
57662      sqlite3XPrintf(&out, "%!.15g", pVar->r);
57663    }else if( pVar->flags & MEM_Str ){
57664#ifndef SQLITE_OMIT_UTF16
57665      u8 enc = ENC(db);
57666      if( enc!=SQLITE_UTF8 ){
57667        Mem utf8;
57668        memset(&utf8, 0, sizeof(utf8));
57669        utf8.db = db;
57670        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
57671        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
57672        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
57673        sqlite3VdbeMemRelease(&utf8);
57674      }else
57675#endif
57676      {
57677        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
57678      }
57679    }else if( pVar->flags & MEM_Zero ){
57680      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
57681    }else{
57682      assert( pVar->flags & MEM_Blob );
57683      sqlite3StrAccumAppend(&out, "x'", 2);
57684      for(i=0; i<pVar->n; i++){
57685        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
57686      }
57687      sqlite3StrAccumAppend(&out, "'", 1);
57688    }
57689  }
57690  return sqlite3StrAccumFinish(&out);
57691}
57692
57693#endif /* #ifndef SQLITE_OMIT_TRACE */
57694
57695/************** End of vdbetrace.c *******************************************/
57696/************** Begin file vdbe.c ********************************************/
57697/*
57698** 2001 September 15
57699**
57700** The author disclaims copyright to this source code.  In place of
57701** a legal notice, here is a blessing:
57702**
57703**    May you do good and not evil.
57704**    May you find forgiveness for yourself and forgive others.
57705**    May you share freely, never taking more than you give.
57706**
57707*************************************************************************
57708** The code in this file implements execution method of the
57709** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
57710** handles housekeeping details such as creating and deleting
57711** VDBE instances.  This file is solely interested in executing
57712** the VDBE program.
57713**
57714** In the external interface, an "sqlite3_stmt*" is an opaque pointer
57715** to a VDBE.
57716**
57717** The SQL parser generates a program which is then executed by
57718** the VDBE to do the work of the SQL statement.  VDBE programs are
57719** similar in form to assembly language.  The program consists of
57720** a linear sequence of operations.  Each operation has an opcode
57721** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
57722** is a null-terminated string.  Operand P5 is an unsigned character.
57723** Few opcodes use all 5 operands.
57724**
57725** Computation results are stored on a set of registers numbered beginning
57726** with 1 and going up to Vdbe.nMem.  Each register can store
57727** either an integer, a null-terminated string, a floating point
57728** number, or the SQL "NULL" value.  An implicit conversion from one
57729** type to the other occurs as necessary.
57730**
57731** Most of the code in this file is taken up by the sqlite3VdbeExec()
57732** function which does the work of interpreting a VDBE program.
57733** But other routines are also provided to help in building up
57734** a program instruction by instruction.
57735**
57736** Various scripts scan this source file in order to generate HTML
57737** documentation, headers files, or other derived files.  The formatting
57738** of the code in this file is, therefore, important.  See other comments
57739** in this file for details.  If in doubt, do not deviate from existing
57740** commenting and indentation practices when changing or adding code.
57741*/
57742
57743/*
57744** The following global variable is incremented every time a cursor
57745** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
57746** procedures use this information to make sure that indices are
57747** working correctly.  This variable has no function other than to
57748** help verify the correct operation of the library.
57749*/
57750#ifdef SQLITE_TEST
57751SQLITE_API int sqlite3_search_count = 0;
57752#endif
57753
57754/*
57755** When this global variable is positive, it gets decremented once before
57756** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
57757** field of the sqlite3 structure is set in order to simulate and interrupt.
57758**
57759** This facility is used for testing purposes only.  It does not function
57760** in an ordinary build.
57761*/
57762#ifdef SQLITE_TEST
57763SQLITE_API int sqlite3_interrupt_count = 0;
57764#endif
57765
57766/*
57767** The next global variable is incremented each type the OP_Sort opcode
57768** is executed.  The test procedures use this information to make sure that
57769** sorting is occurring or not occurring at appropriate times.   This variable
57770** has no function other than to help verify the correct operation of the
57771** library.
57772*/
57773#ifdef SQLITE_TEST
57774SQLITE_API int sqlite3_sort_count = 0;
57775#endif
57776
57777/*
57778** The next global variable records the size of the largest MEM_Blob
57779** or MEM_Str that has been used by a VDBE opcode.  The test procedures
57780** use this information to make sure that the zero-blob functionality
57781** is working correctly.   This variable has no function other than to
57782** help verify the correct operation of the library.
57783*/
57784#ifdef SQLITE_TEST
57785SQLITE_API int sqlite3_max_blobsize = 0;
57786static void updateMaxBlobsize(Mem *p){
57787  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
57788    sqlite3_max_blobsize = p->n;
57789  }
57790}
57791#endif
57792
57793/*
57794** The next global variable is incremented each type the OP_Found opcode
57795** is executed. This is used to test whether or not the foreign key
57796** operation implemented using OP_FkIsZero is working. This variable
57797** has no function other than to help verify the correct operation of the
57798** library.
57799*/
57800#ifdef SQLITE_TEST
57801SQLITE_API int sqlite3_found_count = 0;
57802#endif
57803
57804/*
57805** Test a register to see if it exceeds the current maximum blob size.
57806** If it does, record the new maximum blob size.
57807*/
57808#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
57809# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
57810#else
57811# define UPDATE_MAX_BLOBSIZE(P)
57812#endif
57813
57814/*
57815** Convert the given register into a string if it isn't one
57816** already. Return non-zero if a malloc() fails.
57817*/
57818#define Stringify(P, enc) \
57819   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
57820     { goto no_mem; }
57821
57822/*
57823** An ephemeral string value (signified by the MEM_Ephem flag) contains
57824** a pointer to a dynamically allocated string where some other entity
57825** is responsible for deallocating that string.  Because the register
57826** does not control the string, it might be deleted without the register
57827** knowing it.
57828**
57829** This routine converts an ephemeral string into a dynamically allocated
57830** string that the register itself controls.  In other words, it
57831** converts an MEM_Ephem string into an MEM_Dyn string.
57832*/
57833#define Deephemeralize(P) \
57834   if( ((P)->flags&MEM_Ephem)!=0 \
57835       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
57836
57837/*
57838** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
57839** P if required.
57840*/
57841#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
57842
57843/*
57844** Argument pMem points at a register that will be passed to a
57845** user-defined function or returned to the user as the result of a query.
57846** This routine sets the pMem->type variable used by the sqlite3_value_*()
57847** routines.
57848*/
57849SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
57850  int flags = pMem->flags;
57851  if( flags & MEM_Null ){
57852    pMem->type = SQLITE_NULL;
57853  }
57854  else if( flags & MEM_Int ){
57855    pMem->type = SQLITE_INTEGER;
57856  }
57857  else if( flags & MEM_Real ){
57858    pMem->type = SQLITE_FLOAT;
57859  }
57860  else if( flags & MEM_Str ){
57861    pMem->type = SQLITE_TEXT;
57862  }else{
57863    pMem->type = SQLITE_BLOB;
57864  }
57865}
57866
57867/*
57868** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
57869** if we run out of memory.
57870*/
57871static VdbeCursor *allocateCursor(
57872  Vdbe *p,              /* The virtual machine */
57873  int iCur,             /* Index of the new VdbeCursor */
57874  int nField,           /* Number of fields in the table or index */
57875  int iDb,              /* When database the cursor belongs to, or -1 */
57876  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
57877){
57878  /* Find the memory cell that will be used to store the blob of memory
57879  ** required for this VdbeCursor structure. It is convenient to use a
57880  ** vdbe memory cell to manage the memory allocation required for a
57881  ** VdbeCursor structure for the following reasons:
57882  **
57883  **   * Sometimes cursor numbers are used for a couple of different
57884  **     purposes in a vdbe program. The different uses might require
57885  **     different sized allocations. Memory cells provide growable
57886  **     allocations.
57887  **
57888  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
57889  **     be freed lazily via the sqlite3_release_memory() API. This
57890  **     minimizes the number of malloc calls made by the system.
57891  **
57892  ** Memory cells for cursors are allocated at the top of the address
57893  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
57894  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
57895  */
57896  Mem *pMem = &p->aMem[p->nMem-iCur];
57897
57898  int nByte;
57899  VdbeCursor *pCx = 0;
57900  nByte =
57901      ROUND8(sizeof(VdbeCursor)) +
57902      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
57903      2*nField*sizeof(u32);
57904
57905  assert( iCur<p->nCursor );
57906  if( p->apCsr[iCur] ){
57907    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
57908    p->apCsr[iCur] = 0;
57909  }
57910  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57911    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
57912    memset(pCx, 0, sizeof(VdbeCursor));
57913    pCx->iDb = iDb;
57914    pCx->nField = nField;
57915    if( nField ){
57916      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
57917    }
57918    if( isBtreeCursor ){
57919      pCx->pCursor = (BtCursor*)
57920          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
57921      sqlite3BtreeCursorZero(pCx->pCursor);
57922    }
57923  }
57924  return pCx;
57925}
57926
57927/*
57928** Try to convert a value into a numeric representation if we can
57929** do so without loss of information.  In other words, if the string
57930** looks like a number, convert it into a number.  If it does not
57931** look like a number, leave it alone.
57932*/
57933static void applyNumericAffinity(Mem *pRec){
57934  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
57935    int realnum;
57936    u8 enc = pRec->enc;
57937    sqlite3VdbeMemNulTerminate(pRec);
57938    if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){
57939      i64 value;
57940      char *zUtf8 = pRec->z;
57941#ifndef SQLITE_OMIT_UTF16
57942      if( enc!=SQLITE_UTF8 ){
57943        assert( pRec->db );
57944        zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc);
57945        if( !zUtf8 ) return;
57946      }
57947#endif
57948      if( !realnum && sqlite3Atoi64(zUtf8, &value) ){
57949        pRec->u.i = value;
57950        MemSetTypeFlag(pRec, MEM_Int);
57951      }else{
57952        sqlite3AtoF(zUtf8, &pRec->r);
57953        MemSetTypeFlag(pRec, MEM_Real);
57954      }
57955#ifndef SQLITE_OMIT_UTF16
57956      if( enc!=SQLITE_UTF8 ){
57957        sqlite3DbFree(pRec->db, zUtf8);
57958      }
57959#endif
57960    }
57961  }
57962}
57963
57964/*
57965** Processing is determine by the affinity parameter:
57966**
57967** SQLITE_AFF_INTEGER:
57968** SQLITE_AFF_REAL:
57969** SQLITE_AFF_NUMERIC:
57970**    Try to convert pRec to an integer representation or a
57971**    floating-point representation if an integer representation
57972**    is not possible.  Note that the integer representation is
57973**    always preferred, even if the affinity is REAL, because
57974**    an integer representation is more space efficient on disk.
57975**
57976** SQLITE_AFF_TEXT:
57977**    Convert pRec to a text representation.
57978**
57979** SQLITE_AFF_NONE:
57980**    No-op.  pRec is unchanged.
57981*/
57982static void applyAffinity(
57983  Mem *pRec,          /* The value to apply affinity to */
57984  char affinity,      /* The affinity to be applied */
57985  u8 enc              /* Use this text encoding */
57986){
57987  if( affinity==SQLITE_AFF_TEXT ){
57988    /* Only attempt the conversion to TEXT if there is an integer or real
57989    ** representation (blob and NULL do not get converted) but no string
57990    ** representation.
57991    */
57992    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
57993      sqlite3VdbeMemStringify(pRec, enc);
57994    }
57995    pRec->flags &= ~(MEM_Real|MEM_Int);
57996  }else if( affinity!=SQLITE_AFF_NONE ){
57997    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
57998             || affinity==SQLITE_AFF_NUMERIC );
57999    applyNumericAffinity(pRec);
58000    if( pRec->flags & MEM_Real ){
58001      sqlite3VdbeIntegerAffinity(pRec);
58002    }
58003  }
58004}
58005
58006/*
58007** Try to convert the type of a function argument or a result column
58008** into a numeric representation.  Use either INTEGER or REAL whichever
58009** is appropriate.  But only do the conversion if it is possible without
58010** loss of information and return the revised type of the argument.
58011**
58012** This is an EXPERIMENTAL api and is subject to change or removal.
58013*/
58014SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
58015  Mem *pMem = (Mem*)pVal;
58016  applyNumericAffinity(pMem);
58017  sqlite3VdbeMemStoreType(pMem);
58018  return pMem->type;
58019}
58020
58021/*
58022** Exported version of applyAffinity(). This one works on sqlite3_value*,
58023** not the internal Mem* type.
58024*/
58025SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
58026  sqlite3_value *pVal,
58027  u8 affinity,
58028  u8 enc
58029){
58030  applyAffinity((Mem *)pVal, affinity, enc);
58031}
58032
58033#ifdef SQLITE_DEBUG
58034/*
58035** Write a nice string representation of the contents of cell pMem
58036** into buffer zBuf, length nBuf.
58037*/
58038SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
58039  char *zCsr = zBuf;
58040  int f = pMem->flags;
58041
58042  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
58043
58044  if( f&MEM_Blob ){
58045    int i;
58046    char c;
58047    if( f & MEM_Dyn ){
58048      c = 'z';
58049      assert( (f & (MEM_Static|MEM_Ephem))==0 );
58050    }else if( f & MEM_Static ){
58051      c = 't';
58052      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58053    }else if( f & MEM_Ephem ){
58054      c = 'e';
58055      assert( (f & (MEM_Static|MEM_Dyn))==0 );
58056    }else{
58057      c = 's';
58058    }
58059
58060    sqlite3_snprintf(100, zCsr, "%c", c);
58061    zCsr += sqlite3Strlen30(zCsr);
58062    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
58063    zCsr += sqlite3Strlen30(zCsr);
58064    for(i=0; i<16 && i<pMem->n; i++){
58065      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
58066      zCsr += sqlite3Strlen30(zCsr);
58067    }
58068    for(i=0; i<16 && i<pMem->n; i++){
58069      char z = pMem->z[i];
58070      if( z<32 || z>126 ) *zCsr++ = '.';
58071      else *zCsr++ = z;
58072    }
58073
58074    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
58075    zCsr += sqlite3Strlen30(zCsr);
58076    if( f & MEM_Zero ){
58077      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
58078      zCsr += sqlite3Strlen30(zCsr);
58079    }
58080    *zCsr = '\0';
58081  }else if( f & MEM_Str ){
58082    int j, k;
58083    zBuf[0] = ' ';
58084    if( f & MEM_Dyn ){
58085      zBuf[1] = 'z';
58086      assert( (f & (MEM_Static|MEM_Ephem))==0 );
58087    }else if( f & MEM_Static ){
58088      zBuf[1] = 't';
58089      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58090    }else if( f & MEM_Ephem ){
58091      zBuf[1] = 'e';
58092      assert( (f & (MEM_Static|MEM_Dyn))==0 );
58093    }else{
58094      zBuf[1] = 's';
58095    }
58096    k = 2;
58097    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
58098    k += sqlite3Strlen30(&zBuf[k]);
58099    zBuf[k++] = '[';
58100    for(j=0; j<15 && j<pMem->n; j++){
58101      u8 c = pMem->z[j];
58102      if( c>=0x20 && c<0x7f ){
58103        zBuf[k++] = c;
58104      }else{
58105        zBuf[k++] = '.';
58106      }
58107    }
58108    zBuf[k++] = ']';
58109    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
58110    k += sqlite3Strlen30(&zBuf[k]);
58111    zBuf[k++] = 0;
58112  }
58113}
58114#endif
58115
58116#ifdef SQLITE_DEBUG
58117/*
58118** Print the value of a register for tracing purposes:
58119*/
58120static void memTracePrint(FILE *out, Mem *p){
58121  if( p->flags & MEM_Null ){
58122    fprintf(out, " NULL");
58123  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
58124    fprintf(out, " si:%lld", p->u.i);
58125  }else if( p->flags & MEM_Int ){
58126    fprintf(out, " i:%lld", p->u.i);
58127#ifndef SQLITE_OMIT_FLOATING_POINT
58128  }else if( p->flags & MEM_Real ){
58129    fprintf(out, " r:%g", p->r);
58130#endif
58131  }else if( p->flags & MEM_RowSet ){
58132    fprintf(out, " (rowset)");
58133  }else{
58134    char zBuf[200];
58135    sqlite3VdbeMemPrettyPrint(p, zBuf);
58136    fprintf(out, " ");
58137    fprintf(out, "%s", zBuf);
58138  }
58139}
58140static void registerTrace(FILE *out, int iReg, Mem *p){
58141  fprintf(out, "REG[%d] = ", iReg);
58142  memTracePrint(out, p);
58143  fprintf(out, "\n");
58144}
58145#endif
58146
58147#ifdef SQLITE_DEBUG
58148#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
58149#else
58150#  define REGISTER_TRACE(R,M)
58151#endif
58152
58153
58154#ifdef VDBE_PROFILE
58155
58156/*
58157** hwtime.h contains inline assembler code for implementing
58158** high-performance timing routines.
58159*/
58160/************** Include hwtime.h in the middle of vdbe.c *********************/
58161/************** Begin file hwtime.h ******************************************/
58162/*
58163** 2008 May 27
58164**
58165** The author disclaims copyright to this source code.  In place of
58166** a legal notice, here is a blessing:
58167**
58168**    May you do good and not evil.
58169**    May you find forgiveness for yourself and forgive others.
58170**    May you share freely, never taking more than you give.
58171**
58172******************************************************************************
58173**
58174** This file contains inline asm code for retrieving "high-performance"
58175** counters for x86 class CPUs.
58176*/
58177#ifndef _HWTIME_H_
58178#define _HWTIME_H_
58179
58180/*
58181** The following routine only works on pentium-class (or newer) processors.
58182** It uses the RDTSC opcode to read the cycle count value out of the
58183** processor and returns that value.  This can be used for high-res
58184** profiling.
58185*/
58186#if (defined(__GNUC__) || defined(_MSC_VER)) && \
58187      (defined(i386) || defined(__i386__) || defined(_M_IX86))
58188
58189  #if defined(__GNUC__)
58190
58191  __inline__ sqlite_uint64 sqlite3Hwtime(void){
58192     unsigned int lo, hi;
58193     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
58194     return (sqlite_uint64)hi << 32 | lo;
58195  }
58196
58197  #elif defined(_MSC_VER)
58198
58199  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
58200     __asm {
58201        rdtsc
58202        ret       ; return value at EDX:EAX
58203     }
58204  }
58205
58206  #endif
58207
58208#elif (defined(__GNUC__) && defined(__x86_64__))
58209
58210  __inline__ sqlite_uint64 sqlite3Hwtime(void){
58211      unsigned long val;
58212      __asm__ __volatile__ ("rdtsc" : "=A" (val));
58213      return val;
58214  }
58215
58216#elif (defined(__GNUC__) && defined(__ppc__))
58217
58218  __inline__ sqlite_uint64 sqlite3Hwtime(void){
58219      unsigned long long retval;
58220      unsigned long junk;
58221      __asm__ __volatile__ ("\n\
58222          1:      mftbu   %1\n\
58223                  mftb    %L0\n\
58224                  mftbu   %0\n\
58225                  cmpw    %0,%1\n\
58226                  bne     1b"
58227                  : "=r" (retval), "=r" (junk));
58228      return retval;
58229  }
58230
58231#else
58232
58233  #error Need implementation of sqlite3Hwtime() for your platform.
58234
58235  /*
58236  ** To compile without implementing sqlite3Hwtime() for your platform,
58237  ** you can remove the above #error and use the following
58238  ** stub function.  You will lose timing support for many
58239  ** of the debugging and testing utilities, but it should at
58240  ** least compile and run.
58241  */
58242SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
58243
58244#endif
58245
58246#endif /* !defined(_HWTIME_H_) */
58247
58248/************** End of hwtime.h **********************************************/
58249/************** Continuing where we left off in vdbe.c ***********************/
58250
58251#endif
58252
58253/*
58254** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
58255** sqlite3_interrupt() routine has been called.  If it has been, then
58256** processing of the VDBE program is interrupted.
58257**
58258** This macro added to every instruction that does a jump in order to
58259** implement a loop.  This test used to be on every single instruction,
58260** but that meant we more testing that we needed.  By only testing the
58261** flag on jump instructions, we get a (small) speed improvement.
58262*/
58263#define CHECK_FOR_INTERRUPT \
58264   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
58265
58266
58267#ifndef NDEBUG
58268/*
58269** This function is only called from within an assert() expression. It
58270** checks that the sqlite3.nTransaction variable is correctly set to
58271** the number of non-transaction savepoints currently in the
58272** linked list starting at sqlite3.pSavepoint.
58273**
58274** Usage:
58275**
58276**     assert( checkSavepointCount(db) );
58277*/
58278static int checkSavepointCount(sqlite3 *db){
58279  int n = 0;
58280  Savepoint *p;
58281  for(p=db->pSavepoint; p; p=p->pNext) n++;
58282  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
58283  return 1;
58284}
58285#endif
58286
58287/*
58288** Execute as much of a VDBE program as we can then return.
58289**
58290** sqlite3VdbeMakeReady() must be called before this routine in order to
58291** close the program with a final OP_Halt and to set up the callbacks
58292** and the error message pointer.
58293**
58294** Whenever a row or result data is available, this routine will either
58295** invoke the result callback (if there is one) or return with
58296** SQLITE_ROW.
58297**
58298** If an attempt is made to open a locked database, then this routine
58299** will either invoke the busy callback (if there is one) or it will
58300** return SQLITE_BUSY.
58301**
58302** If an error occurs, an error message is written to memory obtained
58303** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
58304** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
58305**
58306** If the callback ever returns non-zero, then the program exits
58307** immediately.  There will be no error message but the p->rc field is
58308** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
58309**
58310** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
58311** routine to return SQLITE_ERROR.
58312**
58313** Other fatal errors return SQLITE_ERROR.
58314**
58315** After this routine has finished, sqlite3VdbeFinalize() should be
58316** used to clean up the mess that was left behind.
58317*/
58318SQLITE_PRIVATE int sqlite3VdbeExec(
58319  Vdbe *p                    /* The VDBE */
58320){
58321  int pc=0;                  /* The program counter */
58322  Op *aOp = p->aOp;          /* Copy of p->aOp */
58323  Op *pOp;                   /* Current operation */
58324  int rc = SQLITE_OK;        /* Value to return */
58325  sqlite3 *db = p->db;       /* The database */
58326  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
58327  u8 encoding = ENC(db);     /* The database encoding */
58328#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
58329  int checkProgress;         /* True if progress callbacks are enabled */
58330  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
58331#endif
58332  Mem *aMem = p->aMem;       /* Copy of p->aMem */
58333  Mem *pIn1 = 0;             /* 1st input operand */
58334  Mem *pIn2 = 0;             /* 2nd input operand */
58335  Mem *pIn3 = 0;             /* 3rd input operand */
58336  Mem *pOut = 0;             /* Output operand */
58337  int iCompare = 0;          /* Result of last OP_Compare operation */
58338  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
58339#ifdef VDBE_PROFILE
58340  u64 start;                 /* CPU clock count at start of opcode */
58341  int origPc;                /* Program counter at start of opcode */
58342#endif
58343  /********************************************************************
58344  ** Automatically generated code
58345  **
58346  ** The following union is automatically generated by the
58347  ** vdbe-compress.tcl script.  The purpose of this union is to
58348  ** reduce the amount of stack space required by this function.
58349  ** See comments in the vdbe-compress.tcl script for details.
58350  */
58351  union vdbeExecUnion {
58352    struct OP_Yield_stack_vars {
58353      int pcDest;
58354    } aa;
58355    struct OP_Variable_stack_vars {
58356      Mem *pVar;       /* Value being transferred */
58357    } ab;
58358    struct OP_Move_stack_vars {
58359      char *zMalloc;   /* Holding variable for allocated memory */
58360      int n;           /* Number of registers left to copy */
58361      int p1;          /* Register to copy from */
58362      int p2;          /* Register to copy to */
58363    } ac;
58364    struct OP_ResultRow_stack_vars {
58365      Mem *pMem;
58366      int i;
58367    } ad;
58368    struct OP_Concat_stack_vars {
58369      i64 nByte;
58370    } ae;
58371    struct OP_Remainder_stack_vars {
58372      int flags;      /* Combined MEM_* flags from both inputs */
58373      i64 iA;         /* Integer value of left operand */
58374      i64 iB;         /* Integer value of right operand */
58375      double rA;      /* Real value of left operand */
58376      double rB;      /* Real value of right operand */
58377    } af;
58378    struct OP_Function_stack_vars {
58379      int i;
58380      Mem *pArg;
58381      sqlite3_context ctx;
58382      sqlite3_value **apVal;
58383      int n;
58384    } ag;
58385    struct OP_ShiftRight_stack_vars {
58386      i64 a;
58387      i64 b;
58388    } ah;
58389    struct OP_Ge_stack_vars {
58390      int res;            /* Result of the comparison of pIn1 against pIn3 */
58391      char affinity;      /* Affinity to use for comparison */
58392      u16 flags1;         /* Copy of initial value of pIn1->flags */
58393      u16 flags3;         /* Copy of initial value of pIn3->flags */
58394    } ai;
58395    struct OP_Compare_stack_vars {
58396      int n;
58397      int i;
58398      int p1;
58399      int p2;
58400      const KeyInfo *pKeyInfo;
58401      int idx;
58402      CollSeq *pColl;    /* Collating sequence to use on this term */
58403      int bRev;          /* True for DESCENDING sort order */
58404    } aj;
58405    struct OP_Or_stack_vars {
58406      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58407      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58408    } ak;
58409    struct OP_IfNot_stack_vars {
58410      int c;
58411    } al;
58412    struct OP_Column_stack_vars {
58413      u32 payloadSize;   /* Number of bytes in the record */
58414      i64 payloadSize64; /* Number of bytes in the record */
58415      int p1;            /* P1 value of the opcode */
58416      int p2;            /* column number to retrieve */
58417      VdbeCursor *pC;    /* The VDBE cursor */
58418      char *zRec;        /* Pointer to complete record-data */
58419      BtCursor *pCrsr;   /* The BTree cursor */
58420      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
58421      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
58422      int nField;        /* number of fields in the record */
58423      int len;           /* The length of the serialized data for the column */
58424      int i;             /* Loop counter */
58425      char *zData;       /* Part of the record being decoded */
58426      Mem *pDest;        /* Where to write the extracted value */
58427      Mem sMem;          /* For storing the record being decoded */
58428      u8 *zIdx;          /* Index into header */
58429      u8 *zEndHdr;       /* Pointer to first byte after the header */
58430      u32 offset;        /* Offset into the data */
58431      u32 szField;       /* Number of bytes in the content of a field */
58432      int szHdr;         /* Size of the header size field at start of record */
58433      int avail;         /* Number of bytes of available data */
58434      Mem *pReg;         /* PseudoTable input register */
58435    } am;
58436    struct OP_Affinity_stack_vars {
58437      const char *zAffinity;   /* The affinity to be applied */
58438      char cAff;               /* A single character of affinity */
58439    } an;
58440    struct OP_MakeRecord_stack_vars {
58441      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
58442      Mem *pRec;             /* The new record */
58443      u64 nData;             /* Number of bytes of data space */
58444      int nHdr;              /* Number of bytes of header space */
58445      i64 nByte;             /* Data space required for this record */
58446      int nZero;             /* Number of zero bytes at the end of the record */
58447      int nVarint;           /* Number of bytes in a varint */
58448      u32 serial_type;       /* Type field */
58449      Mem *pData0;           /* First field to be combined into the record */
58450      Mem *pLast;            /* Last field of the record */
58451      int nField;            /* Number of fields in the record */
58452      char *zAffinity;       /* The affinity string for the record */
58453      int file_format;       /* File format to use for encoding */
58454      int i;                 /* Space used in zNewRecord[] */
58455      int len;               /* Length of a field */
58456    } ao;
58457    struct OP_Count_stack_vars {
58458      i64 nEntry;
58459      BtCursor *pCrsr;
58460    } ap;
58461    struct OP_Savepoint_stack_vars {
58462      int p1;                         /* Value of P1 operand */
58463      char *zName;                    /* Name of savepoint */
58464      int nName;
58465      Savepoint *pNew;
58466      Savepoint *pSavepoint;
58467      Savepoint *pTmp;
58468      int iSavepoint;
58469      int ii;
58470    } aq;
58471    struct OP_AutoCommit_stack_vars {
58472      int desiredAutoCommit;
58473      int iRollback;
58474      int turnOnAC;
58475    } ar;
58476    struct OP_Transaction_stack_vars {
58477      Btree *pBt;
58478    } as;
58479    struct OP_ReadCookie_stack_vars {
58480      int iMeta;
58481      int iDb;
58482      int iCookie;
58483    } at;
58484    struct OP_SetCookie_stack_vars {
58485      Db *pDb;
58486    } au;
58487    struct OP_VerifyCookie_stack_vars {
58488      int iMeta;
58489      Btree *pBt;
58490    } av;
58491    struct OP_OpenWrite_stack_vars {
58492      int nField;
58493      KeyInfo *pKeyInfo;
58494      int p2;
58495      int iDb;
58496      int wrFlag;
58497      Btree *pX;
58498      VdbeCursor *pCur;
58499      Db *pDb;
58500    } aw;
58501    struct OP_OpenEphemeral_stack_vars {
58502      VdbeCursor *pCx;
58503    } ax;
58504    struct OP_OpenPseudo_stack_vars {
58505      VdbeCursor *pCx;
58506    } ay;
58507    struct OP_SeekGt_stack_vars {
58508      int res;
58509      int oc;
58510      VdbeCursor *pC;
58511      UnpackedRecord r;
58512      int nField;
58513      i64 iKey;      /* The rowid we are to seek to */
58514    } az;
58515    struct OP_Seek_stack_vars {
58516      VdbeCursor *pC;
58517    } ba;
58518    struct OP_Found_stack_vars {
58519      int alreadyExists;
58520      VdbeCursor *pC;
58521      int res;
58522      UnpackedRecord *pIdxKey;
58523      UnpackedRecord r;
58524      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
58525    } bb;
58526    struct OP_IsUnique_stack_vars {
58527      u16 ii;
58528      VdbeCursor *pCx;
58529      BtCursor *pCrsr;
58530      u16 nField;
58531      Mem *aMx;
58532      UnpackedRecord r;                  /* B-Tree index search key */
58533      i64 R;                             /* Rowid stored in register P3 */
58534    } bc;
58535    struct OP_NotExists_stack_vars {
58536      VdbeCursor *pC;
58537      BtCursor *pCrsr;
58538      int res;
58539      u64 iKey;
58540    } bd;
58541    struct OP_NewRowid_stack_vars {
58542      i64 v;                 /* The new rowid */
58543      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
58544      int res;               /* Result of an sqlite3BtreeLast() */
58545      int cnt;               /* Counter to limit the number of searches */
58546      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
58547      VdbeFrame *pFrame;     /* Root frame of VDBE */
58548    } be;
58549    struct OP_InsertInt_stack_vars {
58550      Mem *pData;       /* MEM cell holding data for the record to be inserted */
58551      Mem *pKey;        /* MEM cell holding key  for the record */
58552      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
58553      VdbeCursor *pC;   /* Cursor to table into which insert is written */
58554      int nZero;        /* Number of zero-bytes to append */
58555      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
58556      const char *zDb;  /* database name - used by the update hook */
58557      const char *zTbl; /* Table name - used by the opdate hook */
58558      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
58559    } bf;
58560    struct OP_Delete_stack_vars {
58561      i64 iKey;
58562      VdbeCursor *pC;
58563    } bg;
58564    struct OP_RowData_stack_vars {
58565      VdbeCursor *pC;
58566      BtCursor *pCrsr;
58567      u32 n;
58568      i64 n64;
58569    } bh;
58570    struct OP_Rowid_stack_vars {
58571      VdbeCursor *pC;
58572      i64 v;
58573      sqlite3_vtab *pVtab;
58574      const sqlite3_module *pModule;
58575    } bi;
58576    struct OP_NullRow_stack_vars {
58577      VdbeCursor *pC;
58578    } bj;
58579    struct OP_Last_stack_vars {
58580      VdbeCursor *pC;
58581      BtCursor *pCrsr;
58582      int res;
58583    } bk;
58584    struct OP_Rewind_stack_vars {
58585      VdbeCursor *pC;
58586      BtCursor *pCrsr;
58587      int res;
58588    } bl;
58589    struct OP_Next_stack_vars {
58590      VdbeCursor *pC;
58591      BtCursor *pCrsr;
58592      int res;
58593    } bm;
58594    struct OP_IdxInsert_stack_vars {
58595      VdbeCursor *pC;
58596      BtCursor *pCrsr;
58597      int nKey;
58598      const char *zKey;
58599    } bn;
58600    struct OP_IdxDelete_stack_vars {
58601      VdbeCursor *pC;
58602      BtCursor *pCrsr;
58603      int res;
58604      UnpackedRecord r;
58605    } bo;
58606    struct OP_IdxRowid_stack_vars {
58607      BtCursor *pCrsr;
58608      VdbeCursor *pC;
58609      i64 rowid;
58610    } bp;
58611    struct OP_IdxGE_stack_vars {
58612      VdbeCursor *pC;
58613      int res;
58614      UnpackedRecord r;
58615    } bq;
58616    struct OP_Destroy_stack_vars {
58617      int iMoved;
58618      int iCnt;
58619      Vdbe *pVdbe;
58620      int iDb;
58621    } br;
58622    struct OP_Clear_stack_vars {
58623      int nChange;
58624    } bs;
58625    struct OP_CreateTable_stack_vars {
58626      int pgno;
58627      int flags;
58628      Db *pDb;
58629    } bt;
58630    struct OP_ParseSchema_stack_vars {
58631      int iDb;
58632      const char *zMaster;
58633      char *zSql;
58634      InitData initData;
58635    } bu;
58636    struct OP_IntegrityCk_stack_vars {
58637      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
58638      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
58639      int j;          /* Loop counter */
58640      int nErr;       /* Number of errors reported */
58641      char *z;        /* Text of the error report */
58642      Mem *pnErr;     /* Register keeping track of errors remaining */
58643    } bv;
58644    struct OP_RowSetRead_stack_vars {
58645      i64 val;
58646    } bw;
58647    struct OP_RowSetTest_stack_vars {
58648      int iSet;
58649      int exists;
58650    } bx;
58651    struct OP_Program_stack_vars {
58652      int nMem;               /* Number of memory registers for sub-program */
58653      int nByte;              /* Bytes of runtime space required for sub-program */
58654      Mem *pRt;               /* Register to allocate runtime space */
58655      Mem *pMem;              /* Used to iterate through memory cells */
58656      Mem *pEnd;              /* Last memory cell in new array */
58657      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
58658      SubProgram *pProgram;   /* Sub-program to execute */
58659      void *t;                /* Token identifying trigger */
58660    } by;
58661    struct OP_Param_stack_vars {
58662      VdbeFrame *pFrame;
58663      Mem *pIn;
58664    } bz;
58665    struct OP_MemMax_stack_vars {
58666      Mem *pIn1;
58667      VdbeFrame *pFrame;
58668    } ca;
58669    struct OP_AggStep_stack_vars {
58670      int n;
58671      int i;
58672      Mem *pMem;
58673      Mem *pRec;
58674      sqlite3_context ctx;
58675      sqlite3_value **apVal;
58676    } cb;
58677    struct OP_AggFinal_stack_vars {
58678      Mem *pMem;
58679    } cc;
58680    struct OP_JournalMode_stack_vars {
58681      Btree *pBt;                     /* Btree to change journal mode of */
58682      Pager *pPager;                  /* Pager associated with pBt */
58683      int eNew;                       /* New journal mode */
58684      int eOld;                       /* The old journal mode */
58685      const char *zFilename;          /* Name of database file for pPager */
58686    } cd;
58687    struct OP_IncrVacuum_stack_vars {
58688      Btree *pBt;
58689    } ce;
58690    struct OP_VBegin_stack_vars {
58691      VTable *pVTab;
58692    } cf;
58693    struct OP_VOpen_stack_vars {
58694      VdbeCursor *pCur;
58695      sqlite3_vtab_cursor *pVtabCursor;
58696      sqlite3_vtab *pVtab;
58697      sqlite3_module *pModule;
58698    } cg;
58699    struct OP_VFilter_stack_vars {
58700      int nArg;
58701      int iQuery;
58702      const sqlite3_module *pModule;
58703      Mem *pQuery;
58704      Mem *pArgc;
58705      sqlite3_vtab_cursor *pVtabCursor;
58706      sqlite3_vtab *pVtab;
58707      VdbeCursor *pCur;
58708      int res;
58709      int i;
58710      Mem **apArg;
58711    } ch;
58712    struct OP_VColumn_stack_vars {
58713      sqlite3_vtab *pVtab;
58714      const sqlite3_module *pModule;
58715      Mem *pDest;
58716      sqlite3_context sContext;
58717    } ci;
58718    struct OP_VNext_stack_vars {
58719      sqlite3_vtab *pVtab;
58720      const sqlite3_module *pModule;
58721      int res;
58722      VdbeCursor *pCur;
58723    } cj;
58724    struct OP_VRename_stack_vars {
58725      sqlite3_vtab *pVtab;
58726      Mem *pName;
58727    } ck;
58728    struct OP_VUpdate_stack_vars {
58729      sqlite3_vtab *pVtab;
58730      sqlite3_module *pModule;
58731      int nArg;
58732      int i;
58733      sqlite_int64 rowid;
58734      Mem **apArg;
58735      Mem *pX;
58736    } cl;
58737    struct OP_Trace_stack_vars {
58738      char *zTrace;
58739    } cm;
58740  } u;
58741  /* End automatically generated code
58742  ********************************************************************/
58743
58744  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
58745  sqlite3VdbeMutexArrayEnter(p);
58746  if( p->rc==SQLITE_NOMEM ){
58747    /* This happens if a malloc() inside a call to sqlite3_column_text() or
58748    ** sqlite3_column_text16() failed.  */
58749    goto no_mem;
58750  }
58751  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
58752  p->rc = SQLITE_OK;
58753  assert( p->explain==0 );
58754  p->pResultSet = 0;
58755  db->busyHandler.nBusy = 0;
58756  CHECK_FOR_INTERRUPT;
58757  sqlite3VdbeIOTraceSql(p);
58758#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
58759  checkProgress = db->xProgress!=0;
58760#endif
58761#ifdef SQLITE_DEBUG
58762  sqlite3BeginBenignMalloc();
58763  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
58764    int i;
58765    printf("VDBE Program Listing:\n");
58766    sqlite3VdbePrintSql(p);
58767    for(i=0; i<p->nOp; i++){
58768      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
58769    }
58770  }
58771  sqlite3EndBenignMalloc();
58772#endif
58773  for(pc=p->pc; rc==SQLITE_OK; pc++){
58774    assert( pc>=0 && pc<p->nOp );
58775    if( db->mallocFailed ) goto no_mem;
58776#ifdef VDBE_PROFILE
58777    origPc = pc;
58778    start = sqlite3Hwtime();
58779#endif
58780    pOp = &aOp[pc];
58781
58782    /* Only allow tracing if SQLITE_DEBUG is defined.
58783    */
58784#ifdef SQLITE_DEBUG
58785    if( p->trace ){
58786      if( pc==0 ){
58787        printf("VDBE Execution Trace:\n");
58788        sqlite3VdbePrintSql(p);
58789      }
58790      sqlite3VdbePrintOp(p->trace, pc, pOp);
58791    }
58792#endif
58793
58794
58795    /* Check to see if we need to simulate an interrupt.  This only happens
58796    ** if we have a special test build.
58797    */
58798#ifdef SQLITE_TEST
58799    if( sqlite3_interrupt_count>0 ){
58800      sqlite3_interrupt_count--;
58801      if( sqlite3_interrupt_count==0 ){
58802        sqlite3_interrupt(db);
58803      }
58804    }
58805#endif
58806
58807#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
58808    /* Call the progress callback if it is configured and the required number
58809    ** of VDBE ops have been executed (either since this invocation of
58810    ** sqlite3VdbeExec() or since last time the progress callback was called).
58811    ** If the progress callback returns non-zero, exit the virtual machine with
58812    ** a return code SQLITE_ABORT.
58813    */
58814    if( checkProgress ){
58815      if( db->nProgressOps==nProgressOps ){
58816        int prc;
58817        prc = db->xProgress(db->pProgressArg);
58818        if( prc!=0 ){
58819          rc = SQLITE_INTERRUPT;
58820          goto vdbe_error_halt;
58821        }
58822        nProgressOps = 0;
58823      }
58824      nProgressOps++;
58825    }
58826#endif
58827
58828    /* On any opcode with the "out2-prerelase" tag, free any
58829    ** external allocations out of mem[p2] and set mem[p2] to be
58830    ** an undefined integer.  Opcodes will either fill in the integer
58831    ** value or convert mem[p2] to a different type.
58832    */
58833    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
58834    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
58835      assert( pOp->p2>0 );
58836      assert( pOp->p2<=p->nMem );
58837      pOut = &aMem[pOp->p2];
58838      sqlite3VdbeMemReleaseExternal(pOut);
58839      pOut->flags = MEM_Int;
58840    }
58841
58842    /* Sanity checking on other operands */
58843#ifdef SQLITE_DEBUG
58844    if( (pOp->opflags & OPFLG_IN1)!=0 ){
58845      assert( pOp->p1>0 );
58846      assert( pOp->p1<=p->nMem );
58847      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
58848    }
58849    if( (pOp->opflags & OPFLG_IN2)!=0 ){
58850      assert( pOp->p2>0 );
58851      assert( pOp->p2<=p->nMem );
58852      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
58853    }
58854    if( (pOp->opflags & OPFLG_IN3)!=0 ){
58855      assert( pOp->p3>0 );
58856      assert( pOp->p3<=p->nMem );
58857      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
58858    }
58859    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
58860      assert( pOp->p2>0 );
58861      assert( pOp->p2<=p->nMem );
58862    }
58863    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
58864      assert( pOp->p3>0 );
58865      assert( pOp->p3<=p->nMem );
58866    }
58867#endif
58868
58869    switch( pOp->opcode ){
58870
58871/*****************************************************************************
58872** What follows is a massive switch statement where each case implements a
58873** separate instruction in the virtual machine.  If we follow the usual
58874** indentation conventions, each case should be indented by 6 spaces.  But
58875** that is a lot of wasted space on the left margin.  So the code within
58876** the switch statement will break with convention and be flush-left. Another
58877** big comment (similar to this one) will mark the point in the code where
58878** we transition back to normal indentation.
58879**
58880** The formatting of each case is important.  The makefile for SQLite
58881** generates two C files "opcodes.h" and "opcodes.c" by scanning this
58882** file looking for lines that begin with "case OP_".  The opcodes.h files
58883** will be filled with #defines that give unique integer values to each
58884** opcode and the opcodes.c file is filled with an array of strings where
58885** each string is the symbolic name for the corresponding opcode.  If the
58886** case statement is followed by a comment of the form "/# same as ... #/"
58887** that comment is used to determine the particular value of the opcode.
58888**
58889** Other keywords in the comment that follows each case are used to
58890** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
58891** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
58892** the mkopcodeh.awk script for additional information.
58893**
58894** Documentation about VDBE opcodes is generated by scanning this file
58895** for lines of that contain "Opcode:".  That line and all subsequent
58896** comment lines are used in the generation of the opcode.html documentation
58897** file.
58898**
58899** SUMMARY:
58900**
58901**     Formatting is important to scripts that scan this file.
58902**     Do not deviate from the formatting style currently in use.
58903**
58904*****************************************************************************/
58905
58906/* Opcode:  Goto * P2 * * *
58907**
58908** An unconditional jump to address P2.
58909** The next instruction executed will be
58910** the one at index P2 from the beginning of
58911** the program.
58912*/
58913case OP_Goto: {             /* jump */
58914  CHECK_FOR_INTERRUPT;
58915  pc = pOp->p2 - 1;
58916  break;
58917}
58918
58919/* Opcode:  Gosub P1 P2 * * *
58920**
58921** Write the current address onto register P1
58922** and then jump to address P2.
58923*/
58924case OP_Gosub: {            /* jump, in1 */
58925  pIn1 = &aMem[pOp->p1];
58926  assert( (pIn1->flags & MEM_Dyn)==0 );
58927  pIn1->flags = MEM_Int;
58928  pIn1->u.i = pc;
58929  REGISTER_TRACE(pOp->p1, pIn1);
58930  pc = pOp->p2 - 1;
58931  break;
58932}
58933
58934/* Opcode:  Return P1 * * * *
58935**
58936** Jump to the next instruction after the address in register P1.
58937*/
58938case OP_Return: {           /* in1 */
58939  pIn1 = &aMem[pOp->p1];
58940  assert( pIn1->flags & MEM_Int );
58941  pc = (int)pIn1->u.i;
58942  break;
58943}
58944
58945/* Opcode:  Yield P1 * * * *
58946**
58947** Swap the program counter with the value in register P1.
58948*/
58949case OP_Yield: {            /* in1 */
58950#if 0  /* local variables moved into u.aa */
58951  int pcDest;
58952#endif /* local variables moved into u.aa */
58953  pIn1 = &aMem[pOp->p1];
58954  assert( (pIn1->flags & MEM_Dyn)==0 );
58955  pIn1->flags = MEM_Int;
58956  u.aa.pcDest = (int)pIn1->u.i;
58957  pIn1->u.i = pc;
58958  REGISTER_TRACE(pOp->p1, pIn1);
58959  pc = u.aa.pcDest;
58960  break;
58961}
58962
58963/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
58964**
58965** Check the value in register P3.  If is is NULL then Halt using
58966** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
58967** value in register P3 is not NULL, then this routine is a no-op.
58968*/
58969case OP_HaltIfNull: {      /* in3 */
58970  pIn3 = &aMem[pOp->p3];
58971  if( (pIn3->flags & MEM_Null)==0 ) break;
58972  /* Fall through into OP_Halt */
58973}
58974
58975/* Opcode:  Halt P1 P2 * P4 *
58976**
58977** Exit immediately.  All open cursors, etc are closed
58978** automatically.
58979**
58980** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
58981** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
58982** For errors, it can be some other value.  If P1!=0 then P2 will determine
58983** whether or not to rollback the current transaction.  Do not rollback
58984** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
58985** then back out all changes that have occurred during this execution of the
58986** VDBE, but do not rollback the transaction.
58987**
58988** If P4 is not null then it is an error message string.
58989**
58990** There is an implied "Halt 0 0 0" instruction inserted at the very end of
58991** every program.  So a jump past the last instruction of the program
58992** is the same as executing Halt.
58993*/
58994case OP_Halt: {
58995  if( pOp->p1==SQLITE_OK && p->pFrame ){
58996    /* Halt the sub-program. Return control to the parent frame. */
58997    VdbeFrame *pFrame = p->pFrame;
58998    p->pFrame = pFrame->pParent;
58999    p->nFrame--;
59000    sqlite3VdbeSetChanges(db, p->nChange);
59001    pc = sqlite3VdbeFrameRestore(pFrame);
59002    if( pOp->p2==OE_Ignore ){
59003      /* Instruction pc is the OP_Program that invoked the sub-program
59004      ** currently being halted. If the p2 instruction of this OP_Halt
59005      ** instruction is set to OE_Ignore, then the sub-program is throwing
59006      ** an IGNORE exception. In this case jump to the address specified
59007      ** as the p2 of the calling OP_Program.  */
59008      pc = p->aOp[pc].p2-1;
59009    }
59010    aOp = p->aOp;
59011    aMem = p->aMem;
59012    break;
59013  }
59014
59015  p->rc = pOp->p1;
59016  p->errorAction = (u8)pOp->p2;
59017  p->pc = pc;
59018  if( pOp->p4.z ){
59019    assert( p->rc!=SQLITE_OK );
59020    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
59021    testcase( sqlite3GlobalConfig.xLog!=0 );
59022    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
59023  }else if( p->rc ){
59024    testcase( sqlite3GlobalConfig.xLog!=0 );
59025    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
59026  }
59027  rc = sqlite3VdbeHalt(p);
59028  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
59029  if( rc==SQLITE_BUSY ){
59030    p->rc = rc = SQLITE_BUSY;
59031  }else{
59032    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
59033    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
59034    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
59035  }
59036  goto vdbe_return;
59037}
59038
59039/* Opcode: Integer P1 P2 * * *
59040**
59041** The 32-bit integer value P1 is written into register P2.
59042*/
59043case OP_Integer: {         /* out2-prerelease */
59044  pOut->u.i = pOp->p1;
59045  break;
59046}
59047
59048/* Opcode: Int64 * P2 * P4 *
59049**
59050** P4 is a pointer to a 64-bit integer value.
59051** Write that value into register P2.
59052*/
59053case OP_Int64: {           /* out2-prerelease */
59054  assert( pOp->p4.pI64!=0 );
59055  pOut->u.i = *pOp->p4.pI64;
59056  break;
59057}
59058
59059#ifndef SQLITE_OMIT_FLOATING_POINT
59060/* Opcode: Real * P2 * P4 *
59061**
59062** P4 is a pointer to a 64-bit floating point value.
59063** Write that value into register P2.
59064*/
59065case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
59066  pOut->flags = MEM_Real;
59067  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
59068  pOut->r = *pOp->p4.pReal;
59069  break;
59070}
59071#endif
59072
59073/* Opcode: String8 * P2 * P4 *
59074**
59075** P4 points to a nul terminated UTF-8 string. This opcode is transformed
59076** into an OP_String before it is executed for the first time.
59077*/
59078case OP_String8: {         /* same as TK_STRING, out2-prerelease */
59079  assert( pOp->p4.z!=0 );
59080  pOp->opcode = OP_String;
59081  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
59082
59083#ifndef SQLITE_OMIT_UTF16
59084  if( encoding!=SQLITE_UTF8 ){
59085    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
59086    if( rc==SQLITE_TOOBIG ) goto too_big;
59087    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
59088    assert( pOut->zMalloc==pOut->z );
59089    assert( pOut->flags & MEM_Dyn );
59090    pOut->zMalloc = 0;
59091    pOut->flags |= MEM_Static;
59092    pOut->flags &= ~MEM_Dyn;
59093    if( pOp->p4type==P4_DYNAMIC ){
59094      sqlite3DbFree(db, pOp->p4.z);
59095    }
59096    pOp->p4type = P4_DYNAMIC;
59097    pOp->p4.z = pOut->z;
59098    pOp->p1 = pOut->n;
59099  }
59100#endif
59101  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59102    goto too_big;
59103  }
59104  /* Fall through to the next case, OP_String */
59105}
59106
59107/* Opcode: String P1 P2 * P4 *
59108**
59109** The string value P4 of length P1 (bytes) is stored in register P2.
59110*/
59111case OP_String: {          /* out2-prerelease */
59112  assert( pOp->p4.z!=0 );
59113  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
59114  pOut->z = pOp->p4.z;
59115  pOut->n = pOp->p1;
59116  pOut->enc = encoding;
59117  UPDATE_MAX_BLOBSIZE(pOut);
59118  break;
59119}
59120
59121/* Opcode: Null * P2 * * *
59122**
59123** Write a NULL into register P2.
59124*/
59125case OP_Null: {           /* out2-prerelease */
59126  pOut->flags = MEM_Null;
59127  break;
59128}
59129
59130
59131/* Opcode: Blob P1 P2 * P4
59132**
59133** P4 points to a blob of data P1 bytes long.  Store this
59134** blob in register P2. This instruction is not coded directly
59135** by the compiler. Instead, the compiler layer specifies
59136** an OP_HexBlob opcode, with the hex string representation of
59137** the blob as P4. This opcode is transformed to an OP_Blob
59138** the first time it is executed.
59139*/
59140case OP_Blob: {                /* out2-prerelease */
59141  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
59142  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
59143  pOut->enc = encoding;
59144  UPDATE_MAX_BLOBSIZE(pOut);
59145  break;
59146}
59147
59148/* Opcode: Variable P1 P2 * P4 *
59149**
59150** Transfer the values of bound parameter P1 into register P2
59151**
59152** If the parameter is named, then its name appears in P4 and P3==1.
59153** The P4 value is used by sqlite3_bind_parameter_name().
59154*/
59155case OP_Variable: {            /* out2-prerelease */
59156#if 0  /* local variables moved into u.ab */
59157  Mem *pVar;       /* Value being transferred */
59158#endif /* local variables moved into u.ab */
59159
59160  assert( pOp->p1>0 && pOp->p1<=p->nVar );
59161  u.ab.pVar = &p->aVar[pOp->p1 - 1];
59162  if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
59163    goto too_big;
59164  }
59165  sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
59166  UPDATE_MAX_BLOBSIZE(pOut);
59167  break;
59168}
59169
59170/* Opcode: Move P1 P2 P3 * *
59171**
59172** Move the values in register P1..P1+P3-1 over into
59173** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
59174** left holding a NULL.  It is an error for register ranges
59175** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
59176*/
59177case OP_Move: {
59178#if 0  /* local variables moved into u.ac */
59179  char *zMalloc;   /* Holding variable for allocated memory */
59180  int n;           /* Number of registers left to copy */
59181  int p1;          /* Register to copy from */
59182  int p2;          /* Register to copy to */
59183#endif /* local variables moved into u.ac */
59184
59185  u.ac.n = pOp->p3;
59186  u.ac.p1 = pOp->p1;
59187  u.ac.p2 = pOp->p2;
59188  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
59189  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
59190
59191  pIn1 = &aMem[u.ac.p1];
59192  pOut = &aMem[u.ac.p2];
59193  while( u.ac.n-- ){
59194    assert( pOut<=&aMem[p->nMem] );
59195    assert( pIn1<=&aMem[p->nMem] );
59196    u.ac.zMalloc = pOut->zMalloc;
59197    pOut->zMalloc = 0;
59198    sqlite3VdbeMemMove(pOut, pIn1);
59199    pIn1->zMalloc = u.ac.zMalloc;
59200    REGISTER_TRACE(u.ac.p2++, pOut);
59201    pIn1++;
59202    pOut++;
59203  }
59204  break;
59205}
59206
59207/* Opcode: Copy P1 P2 * * *
59208**
59209** Make a copy of register P1 into register P2.
59210**
59211** This instruction makes a deep copy of the value.  A duplicate
59212** is made of any string or blob constant.  See also OP_SCopy.
59213*/
59214case OP_Copy: {             /* in1, out2 */
59215  pIn1 = &aMem[pOp->p1];
59216  pOut = &aMem[pOp->p2];
59217  assert( pOut!=pIn1 );
59218  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59219  Deephemeralize(pOut);
59220  REGISTER_TRACE(pOp->p2, pOut);
59221  break;
59222}
59223
59224/* Opcode: SCopy P1 P2 * * *
59225**
59226** Make a shallow copy of register P1 into register P2.
59227**
59228** This instruction makes a shallow copy of the value.  If the value
59229** is a string or blob, then the copy is only a pointer to the
59230** original and hence if the original changes so will the copy.
59231** Worse, if the original is deallocated, the copy becomes invalid.
59232** Thus the program must guarantee that the original will not change
59233** during the lifetime of the copy.  Use OP_Copy to make a complete
59234** copy.
59235*/
59236case OP_SCopy: {            /* in1, out2 */
59237  pIn1 = &aMem[pOp->p1];
59238  pOut = &aMem[pOp->p2];
59239  assert( pOut!=pIn1 );
59240  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59241  REGISTER_TRACE(pOp->p2, pOut);
59242  break;
59243}
59244
59245/* Opcode: ResultRow P1 P2 * * *
59246**
59247** The registers P1 through P1+P2-1 contain a single row of
59248** results. This opcode causes the sqlite3_step() call to terminate
59249** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
59250** structure to provide access to the top P1 values as the result
59251** row.
59252*/
59253case OP_ResultRow: {
59254#if 0  /* local variables moved into u.ad */
59255  Mem *pMem;
59256  int i;
59257#endif /* local variables moved into u.ad */
59258  assert( p->nResColumn==pOp->p2 );
59259  assert( pOp->p1>0 );
59260  assert( pOp->p1+pOp->p2<=p->nMem+1 );
59261
59262  /* If this statement has violated immediate foreign key constraints, do
59263  ** not return the number of rows modified. And do not RELEASE the statement
59264  ** transaction. It needs to be rolled back.  */
59265  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
59266    assert( db->flags&SQLITE_CountRows );
59267    assert( p->usesStmtJournal );
59268    break;
59269  }
59270
59271  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
59272  ** DML statements invoke this opcode to return the number of rows
59273  ** modified to the user. This is the only way that a VM that
59274  ** opens a statement transaction may invoke this opcode.
59275  **
59276  ** In case this is such a statement, close any statement transaction
59277  ** opened by this VM before returning control to the user. This is to
59278  ** ensure that statement-transactions are always nested, not overlapping.
59279  ** If the open statement-transaction is not closed here, then the user
59280  ** may step another VM that opens its own statement transaction. This
59281  ** may lead to overlapping statement transactions.
59282  **
59283  ** The statement transaction is never a top-level transaction.  Hence
59284  ** the RELEASE call below can never fail.
59285  */
59286  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
59287  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
59288  if( NEVER(rc!=SQLITE_OK) ){
59289    break;
59290  }
59291
59292  /* Invalidate all ephemeral cursor row caches */
59293  p->cacheCtr = (p->cacheCtr + 2)|1;
59294
59295  /* Make sure the results of the current row are \000 terminated
59296  ** and have an assigned type.  The results are de-ephemeralized as
59297  ** as side effect.
59298  */
59299  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
59300  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
59301    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
59302    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
59303    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
59304  }
59305  if( db->mallocFailed ) goto no_mem;
59306
59307  /* Return SQLITE_ROW
59308  */
59309  p->pc = pc + 1;
59310  rc = SQLITE_ROW;
59311  goto vdbe_return;
59312}
59313
59314/* Opcode: Concat P1 P2 P3 * *
59315**
59316** Add the text in register P1 onto the end of the text in
59317** register P2 and store the result in register P3.
59318** If either the P1 or P2 text are NULL then store NULL in P3.
59319**
59320**   P3 = P2 || P1
59321**
59322** It is illegal for P1 and P3 to be the same register. Sometimes,
59323** if P3 is the same register as P2, the implementation is able
59324** to avoid a memcpy().
59325*/
59326case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
59327#if 0  /* local variables moved into u.ae */
59328  i64 nByte;
59329#endif /* local variables moved into u.ae */
59330
59331  pIn1 = &aMem[pOp->p1];
59332  pIn2 = &aMem[pOp->p2];
59333  pOut = &aMem[pOp->p3];
59334  assert( pIn1!=pOut );
59335  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
59336    sqlite3VdbeMemSetNull(pOut);
59337    break;
59338  }
59339  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
59340  Stringify(pIn1, encoding);
59341  Stringify(pIn2, encoding);
59342  u.ae.nByte = pIn1->n + pIn2->n;
59343  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59344    goto too_big;
59345  }
59346  MemSetTypeFlag(pOut, MEM_Str);
59347  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
59348    goto no_mem;
59349  }
59350  if( pOut!=pIn2 ){
59351    memcpy(pOut->z, pIn2->z, pIn2->n);
59352  }
59353  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
59354  pOut->z[u.ae.nByte] = 0;
59355  pOut->z[u.ae.nByte+1] = 0;
59356  pOut->flags |= MEM_Term;
59357  pOut->n = (int)u.ae.nByte;
59358  pOut->enc = encoding;
59359  UPDATE_MAX_BLOBSIZE(pOut);
59360  break;
59361}
59362
59363/* Opcode: Add P1 P2 P3 * *
59364**
59365** Add the value in register P1 to the value in register P2
59366** and store the result in register P3.
59367** If either input is NULL, the result is NULL.
59368*/
59369/* Opcode: Multiply P1 P2 P3 * *
59370**
59371**
59372** Multiply the value in register P1 by the value in register P2
59373** and store the result in register P3.
59374** If either input is NULL, the result is NULL.
59375*/
59376/* Opcode: Subtract P1 P2 P3 * *
59377**
59378** Subtract the value in register P1 from the value in register P2
59379** and store the result in register P3.
59380** If either input is NULL, the result is NULL.
59381*/
59382/* Opcode: Divide P1 P2 P3 * *
59383**
59384** Divide the value in register P1 by the value in register P2
59385** and store the result in register P3 (P3=P2/P1). If the value in
59386** register P1 is zero, then the result is NULL. If either input is
59387** NULL, the result is NULL.
59388*/
59389/* Opcode: Remainder P1 P2 P3 * *
59390**
59391** Compute the remainder after integer division of the value in
59392** register P1 by the value in register P2 and store the result in P3.
59393** If the value in register P2 is zero the result is NULL.
59394** If either operand is NULL, the result is NULL.
59395*/
59396case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
59397case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
59398case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
59399case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
59400case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
59401#if 0  /* local variables moved into u.af */
59402  int flags;      /* Combined MEM_* flags from both inputs */
59403  i64 iA;         /* Integer value of left operand */
59404  i64 iB;         /* Integer value of right operand */
59405  double rA;      /* Real value of left operand */
59406  double rB;      /* Real value of right operand */
59407#endif /* local variables moved into u.af */
59408
59409  pIn1 = &aMem[pOp->p1];
59410  applyNumericAffinity(pIn1);
59411  pIn2 = &aMem[pOp->p2];
59412  applyNumericAffinity(pIn2);
59413  pOut = &aMem[pOp->p3];
59414  u.af.flags = pIn1->flags | pIn2->flags;
59415  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
59416  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
59417    u.af.iA = pIn1->u.i;
59418    u.af.iB = pIn2->u.i;
59419    switch( pOp->opcode ){
59420      case OP_Add:         u.af.iB += u.af.iA;       break;
59421      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
59422      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
59423      case OP_Divide: {
59424        if( u.af.iA==0 ) goto arithmetic_result_is_null;
59425        /* Dividing the largest possible negative 64-bit integer (1<<63) by
59426        ** -1 returns an integer too large to store in a 64-bit data-type. On
59427        ** some architectures, the value overflows to (1<<63). On others,
59428        ** a SIGFPE is issued. The following statement normalizes this
59429        ** behavior so that all architectures behave as if integer
59430        ** overflow occurred.
59431        */
59432        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
59433        u.af.iB /= u.af.iA;
59434        break;
59435      }
59436      default: {
59437        if( u.af.iA==0 ) goto arithmetic_result_is_null;
59438        if( u.af.iA==-1 ) u.af.iA = 1;
59439        u.af.iB %= u.af.iA;
59440        break;
59441      }
59442    }
59443    pOut->u.i = u.af.iB;
59444    MemSetTypeFlag(pOut, MEM_Int);
59445  }else{
59446    u.af.rA = sqlite3VdbeRealValue(pIn1);
59447    u.af.rB = sqlite3VdbeRealValue(pIn2);
59448    switch( pOp->opcode ){
59449      case OP_Add:         u.af.rB += u.af.rA;       break;
59450      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
59451      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
59452      case OP_Divide: {
59453        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59454        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
59455        u.af.rB /= u.af.rA;
59456        break;
59457      }
59458      default: {
59459        u.af.iA = (i64)u.af.rA;
59460        u.af.iB = (i64)u.af.rB;
59461        if( u.af.iA==0 ) goto arithmetic_result_is_null;
59462        if( u.af.iA==-1 ) u.af.iA = 1;
59463        u.af.rB = (double)(u.af.iB % u.af.iA);
59464        break;
59465      }
59466    }
59467#ifdef SQLITE_OMIT_FLOATING_POINT
59468    pOut->u.i = u.af.rB;
59469    MemSetTypeFlag(pOut, MEM_Int);
59470#else
59471    if( sqlite3IsNaN(u.af.rB) ){
59472      goto arithmetic_result_is_null;
59473    }
59474    pOut->r = u.af.rB;
59475    MemSetTypeFlag(pOut, MEM_Real);
59476    if( (u.af.flags & MEM_Real)==0 ){
59477      sqlite3VdbeIntegerAffinity(pOut);
59478    }
59479#endif
59480  }
59481  break;
59482
59483arithmetic_result_is_null:
59484  sqlite3VdbeMemSetNull(pOut);
59485  break;
59486}
59487
59488/* Opcode: CollSeq * * P4
59489**
59490** P4 is a pointer to a CollSeq struct. If the next call to a user function
59491** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
59492** be returned. This is used by the built-in min(), max() and nullif()
59493** functions.
59494**
59495** The interface used by the implementation of the aforementioned functions
59496** to retrieve the collation sequence set by this opcode is not available
59497** publicly, only to user functions defined in func.c.
59498*/
59499case OP_CollSeq: {
59500  assert( pOp->p4type==P4_COLLSEQ );
59501  break;
59502}
59503
59504/* Opcode: Function P1 P2 P3 P4 P5
59505**
59506** Invoke a user function (P4 is a pointer to a Function structure that
59507** defines the function) with P5 arguments taken from register P2 and
59508** successors.  The result of the function is stored in register P3.
59509** Register P3 must not be one of the function inputs.
59510**
59511** P1 is a 32-bit bitmask indicating whether or not each argument to the
59512** function was determined to be constant at compile time. If the first
59513** argument was constant then bit 0 of P1 is set. This is used to determine
59514** whether meta data associated with a user function argument using the
59515** sqlite3_set_auxdata() API may be safely retained until the next
59516** invocation of this opcode.
59517**
59518** See also: AggStep and AggFinal
59519*/
59520case OP_Function: {
59521#if 0  /* local variables moved into u.ag */
59522  int i;
59523  Mem *pArg;
59524  sqlite3_context ctx;
59525  sqlite3_value **apVal;
59526  int n;
59527#endif /* local variables moved into u.ag */
59528
59529  u.ag.n = pOp->p5;
59530  u.ag.apVal = p->apArg;
59531  assert( u.ag.apVal || u.ag.n==0 );
59532
59533  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
59534  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
59535  u.ag.pArg = &aMem[pOp->p2];
59536  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
59537    u.ag.apVal[u.ag.i] = u.ag.pArg;
59538    sqlite3VdbeMemStoreType(u.ag.pArg);
59539    REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
59540  }
59541
59542  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
59543  if( pOp->p4type==P4_FUNCDEF ){
59544    u.ag.ctx.pFunc = pOp->p4.pFunc;
59545    u.ag.ctx.pVdbeFunc = 0;
59546  }else{
59547    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
59548    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
59549  }
59550
59551  assert( pOp->p3>0 && pOp->p3<=p->nMem );
59552  pOut = &aMem[pOp->p3];
59553  u.ag.ctx.s.flags = MEM_Null;
59554  u.ag.ctx.s.db = db;
59555  u.ag.ctx.s.xDel = 0;
59556  u.ag.ctx.s.zMalloc = 0;
59557
59558  /* The output cell may already have a buffer allocated. Move
59559  ** the pointer to u.ag.ctx.s so in case the user-function can use
59560  ** the already allocated buffer instead of allocating a new one.
59561  */
59562  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
59563  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
59564
59565  u.ag.ctx.isError = 0;
59566  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
59567    assert( pOp>aOp );
59568    assert( pOp[-1].p4type==P4_COLLSEQ );
59569    assert( pOp[-1].opcode==OP_CollSeq );
59570    u.ag.ctx.pColl = pOp[-1].p4.pColl;
59571  }
59572  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
59573  if( db->mallocFailed ){
59574    /* Even though a malloc() has failed, the implementation of the
59575    ** user function may have called an sqlite3_result_XXX() function
59576    ** to return a value. The following call releases any resources
59577    ** associated with such a value.
59578    */
59579    sqlite3VdbeMemRelease(&u.ag.ctx.s);
59580    goto no_mem;
59581  }
59582
59583  /* If any auxiliary data functions have been called by this user function,
59584  ** immediately call the destructor for any non-static values.
59585  */
59586  if( u.ag.ctx.pVdbeFunc ){
59587    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
59588    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
59589    pOp->p4type = P4_VDBEFUNC;
59590  }
59591
59592  /* If the function returned an error, throw an exception */
59593  if( u.ag.ctx.isError ){
59594    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
59595    rc = u.ag.ctx.isError;
59596  }
59597
59598  /* Copy the result of the function into register P3 */
59599  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
59600  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
59601  if( sqlite3VdbeMemTooBig(pOut) ){
59602    goto too_big;
59603  }
59604  REGISTER_TRACE(pOp->p3, pOut);
59605  UPDATE_MAX_BLOBSIZE(pOut);
59606  break;
59607}
59608
59609/* Opcode: BitAnd P1 P2 P3 * *
59610**
59611** Take the bit-wise AND of the values in register P1 and P2 and
59612** store the result in register P3.
59613** If either input is NULL, the result is NULL.
59614*/
59615/* Opcode: BitOr P1 P2 P3 * *
59616**
59617** Take the bit-wise OR of the values in register P1 and P2 and
59618** store the result in register P3.
59619** If either input is NULL, the result is NULL.
59620*/
59621/* Opcode: ShiftLeft P1 P2 P3 * *
59622**
59623** Shift the integer value in register P2 to the left by the
59624** number of bits specified by the integer in regiser P1.
59625** Store the result in register P3.
59626** If either input is NULL, the result is NULL.
59627*/
59628/* Opcode: ShiftRight P1 P2 P3 * *
59629**
59630** Shift the integer value in register P2 to the right by the
59631** number of bits specified by the integer in register P1.
59632** Store the result in register P3.
59633** If either input is NULL, the result is NULL.
59634*/
59635case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
59636case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
59637case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
59638case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
59639#if 0  /* local variables moved into u.ah */
59640  i64 a;
59641  i64 b;
59642#endif /* local variables moved into u.ah */
59643
59644  pIn1 = &aMem[pOp->p1];
59645  pIn2 = &aMem[pOp->p2];
59646  pOut = &aMem[pOp->p3];
59647  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
59648    sqlite3VdbeMemSetNull(pOut);
59649    break;
59650  }
59651  u.ah.a = sqlite3VdbeIntValue(pIn2);
59652  u.ah.b = sqlite3VdbeIntValue(pIn1);
59653  switch( pOp->opcode ){
59654    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
59655    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
59656    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
59657    default:  assert( pOp->opcode==OP_ShiftRight );
59658                         u.ah.a >>= u.ah.b;    break;
59659  }
59660  pOut->u.i = u.ah.a;
59661  MemSetTypeFlag(pOut, MEM_Int);
59662  break;
59663}
59664
59665/* Opcode: AddImm  P1 P2 * * *
59666**
59667** Add the constant P2 to the value in register P1.
59668** The result is always an integer.
59669**
59670** To force any register to be an integer, just add 0.
59671*/
59672case OP_AddImm: {            /* in1 */
59673  pIn1 = &aMem[pOp->p1];
59674  sqlite3VdbeMemIntegerify(pIn1);
59675  pIn1->u.i += pOp->p2;
59676  break;
59677}
59678
59679/* Opcode: MustBeInt P1 P2 * * *
59680**
59681** Force the value in register P1 to be an integer.  If the value
59682** in P1 is not an integer and cannot be converted into an integer
59683** without data loss, then jump immediately to P2, or if P2==0
59684** raise an SQLITE_MISMATCH exception.
59685*/
59686case OP_MustBeInt: {            /* jump, in1 */
59687  pIn1 = &aMem[pOp->p1];
59688  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
59689  if( (pIn1->flags & MEM_Int)==0 ){
59690    if( pOp->p2==0 ){
59691      rc = SQLITE_MISMATCH;
59692      goto abort_due_to_error;
59693    }else{
59694      pc = pOp->p2 - 1;
59695    }
59696  }else{
59697    MemSetTypeFlag(pIn1, MEM_Int);
59698  }
59699  break;
59700}
59701
59702#ifndef SQLITE_OMIT_FLOATING_POINT
59703/* Opcode: RealAffinity P1 * * * *
59704**
59705** If register P1 holds an integer convert it to a real value.
59706**
59707** This opcode is used when extracting information from a column that
59708** has REAL affinity.  Such column values may still be stored as
59709** integers, for space efficiency, but after extraction we want them
59710** to have only a real value.
59711*/
59712case OP_RealAffinity: {                  /* in1 */
59713  pIn1 = &aMem[pOp->p1];
59714  if( pIn1->flags & MEM_Int ){
59715    sqlite3VdbeMemRealify(pIn1);
59716  }
59717  break;
59718}
59719#endif
59720
59721#ifndef SQLITE_OMIT_CAST
59722/* Opcode: ToText P1 * * * *
59723**
59724** Force the value in register P1 to be text.
59725** If the value is numeric, convert it to a string using the
59726** equivalent of printf().  Blob values are unchanged and
59727** are afterwards simply interpreted as text.
59728**
59729** A NULL value is not changed by this routine.  It remains NULL.
59730*/
59731case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
59732  pIn1 = &aMem[pOp->p1];
59733  if( pIn1->flags & MEM_Null ) break;
59734  assert( MEM_Str==(MEM_Blob>>3) );
59735  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
59736  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
59737  rc = ExpandBlob(pIn1);
59738  assert( pIn1->flags & MEM_Str || db->mallocFailed );
59739  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
59740  UPDATE_MAX_BLOBSIZE(pIn1);
59741  break;
59742}
59743
59744/* Opcode: ToBlob P1 * * * *
59745**
59746** Force the value in register P1 to be a BLOB.
59747** If the value is numeric, convert it to a string first.
59748** Strings are simply reinterpreted as blobs with no change
59749** to the underlying data.
59750**
59751** A NULL value is not changed by this routine.  It remains NULL.
59752*/
59753case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
59754  pIn1 = &aMem[pOp->p1];
59755  if( pIn1->flags & MEM_Null ) break;
59756  if( (pIn1->flags & MEM_Blob)==0 ){
59757    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
59758    assert( pIn1->flags & MEM_Str || db->mallocFailed );
59759    MemSetTypeFlag(pIn1, MEM_Blob);
59760  }else{
59761    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
59762  }
59763  UPDATE_MAX_BLOBSIZE(pIn1);
59764  break;
59765}
59766
59767/* Opcode: ToNumeric P1 * * * *
59768**
59769** Force the value in register P1 to be numeric (either an
59770** integer or a floating-point number.)
59771** If the value is text or blob, try to convert it to an using the
59772** equivalent of atoi() or atof() and store 0 if no such conversion
59773** is possible.
59774**
59775** A NULL value is not changed by this routine.  It remains NULL.
59776*/
59777case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
59778  pIn1 = &aMem[pOp->p1];
59779  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
59780    sqlite3VdbeMemNumerify(pIn1);
59781  }
59782  break;
59783}
59784#endif /* SQLITE_OMIT_CAST */
59785
59786/* Opcode: ToInt P1 * * * *
59787**
59788** Force the value in register P1 be an integer.  If
59789** The value is currently a real number, drop its fractional part.
59790** If the value is text or blob, try to convert it to an integer using the
59791** equivalent of atoi() and store 0 if no such conversion is possible.
59792**
59793** A NULL value is not changed by this routine.  It remains NULL.
59794*/
59795case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
59796  pIn1 = &aMem[pOp->p1];
59797  if( (pIn1->flags & MEM_Null)==0 ){
59798    sqlite3VdbeMemIntegerify(pIn1);
59799  }
59800  break;
59801}
59802
59803#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
59804/* Opcode: ToReal P1 * * * *
59805**
59806** Force the value in register P1 to be a floating point number.
59807** If The value is currently an integer, convert it.
59808** If the value is text or blob, try to convert it to an integer using the
59809** equivalent of atoi() and store 0.0 if no such conversion is possible.
59810**
59811** A NULL value is not changed by this routine.  It remains NULL.
59812*/
59813case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
59814  pIn1 = &aMem[pOp->p1];
59815  if( (pIn1->flags & MEM_Null)==0 ){
59816    sqlite3VdbeMemRealify(pIn1);
59817  }
59818  break;
59819}
59820#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
59821
59822/* Opcode: Lt P1 P2 P3 P4 P5
59823**
59824** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
59825** jump to address P2.
59826**
59827** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
59828** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
59829** bit is clear then fall thru if either operand is NULL.
59830**
59831** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
59832** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
59833** to coerce both inputs according to this affinity before the
59834** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
59835** affinity is used. Note that the affinity conversions are stored
59836** back into the input registers P1 and P3.  So this opcode can cause
59837** persistent changes to registers P1 and P3.
59838**
59839** Once any conversions have taken place, and neither value is NULL,
59840** the values are compared. If both values are blobs then memcmp() is
59841** used to determine the results of the comparison.  If both values
59842** are text, then the appropriate collating function specified in
59843** P4 is  used to do the comparison.  If P4 is not specified then
59844** memcmp() is used to compare text string.  If both values are
59845** numeric, then a numeric comparison is used. If the two values
59846** are of different types, then numbers are considered less than
59847** strings and strings are considered less than blobs.
59848**
59849** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
59850** store a boolean result (either 0, or 1, or NULL) in register P2.
59851*/
59852/* Opcode: Ne P1 P2 P3 P4 P5
59853**
59854** This works just like the Lt opcode except that the jump is taken if
59855** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
59856** additional information.
59857**
59858** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
59859** true or false and is never NULL.  If both operands are NULL then the result
59860** of comparison is false.  If either operand is NULL then the result is true.
59861** If neither operand is NULL the the result is the same as it would be if
59862** the SQLITE_NULLEQ flag were omitted from P5.
59863*/
59864/* Opcode: Eq P1 P2 P3 P4 P5
59865**
59866** This works just like the Lt opcode except that the jump is taken if
59867** the operands in registers P1 and P3 are equal.
59868** See the Lt opcode for additional information.
59869**
59870** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
59871** true or false and is never NULL.  If both operands are NULL then the result
59872** of comparison is true.  If either operand is NULL then the result is false.
59873** If neither operand is NULL the the result is the same as it would be if
59874** the SQLITE_NULLEQ flag were omitted from P5.
59875*/
59876/* Opcode: Le P1 P2 P3 P4 P5
59877**
59878** This works just like the Lt opcode except that the jump is taken if
59879** the content of register P3 is less than or equal to the content of
59880** register P1.  See the Lt opcode for additional information.
59881*/
59882/* Opcode: Gt P1 P2 P3 P4 P5
59883**
59884** This works just like the Lt opcode except that the jump is taken if
59885** the content of register P3 is greater than the content of
59886** register P1.  See the Lt opcode for additional information.
59887*/
59888/* Opcode: Ge P1 P2 P3 P4 P5
59889**
59890** This works just like the Lt opcode except that the jump is taken if
59891** the content of register P3 is greater than or equal to the content of
59892** register P1.  See the Lt opcode for additional information.
59893*/
59894case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
59895case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
59896case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
59897case OP_Le:               /* same as TK_LE, jump, in1, in3 */
59898case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
59899case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
59900#if 0  /* local variables moved into u.ai */
59901  int res;            /* Result of the comparison of pIn1 against pIn3 */
59902  char affinity;      /* Affinity to use for comparison */
59903  u16 flags1;         /* Copy of initial value of pIn1->flags */
59904  u16 flags3;         /* Copy of initial value of pIn3->flags */
59905#endif /* local variables moved into u.ai */
59906
59907  pIn1 = &aMem[pOp->p1];
59908  pIn3 = &aMem[pOp->p3];
59909  u.ai.flags1 = pIn1->flags;
59910  u.ai.flags3 = pIn3->flags;
59911  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
59912    /* One or both operands are NULL */
59913    if( pOp->p5 & SQLITE_NULLEQ ){
59914      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
59915      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
59916      ** or not both operands are null.
59917      */
59918      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
59919      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
59920    }else{
59921      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
59922      ** then the result is always NULL.
59923      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
59924      */
59925      if( pOp->p5 & SQLITE_STOREP2 ){
59926        pOut = &aMem[pOp->p2];
59927        MemSetTypeFlag(pOut, MEM_Null);
59928        REGISTER_TRACE(pOp->p2, pOut);
59929      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
59930        pc = pOp->p2-1;
59931      }
59932      break;
59933    }
59934  }else{
59935    /* Neither operand is NULL.  Do a comparison. */
59936    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
59937    if( u.ai.affinity ){
59938      applyAffinity(pIn1, u.ai.affinity, encoding);
59939      applyAffinity(pIn3, u.ai.affinity, encoding);
59940      if( db->mallocFailed ) goto no_mem;
59941    }
59942
59943    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
59944    ExpandBlob(pIn1);
59945    ExpandBlob(pIn3);
59946    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
59947  }
59948  switch( pOp->opcode ){
59949    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
59950    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
59951    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
59952    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
59953    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
59954    default:       u.ai.res = u.ai.res>=0;     break;
59955  }
59956
59957  if( pOp->p5 & SQLITE_STOREP2 ){
59958    pOut = &aMem[pOp->p2];
59959    MemSetTypeFlag(pOut, MEM_Int);
59960    pOut->u.i = u.ai.res;
59961    REGISTER_TRACE(pOp->p2, pOut);
59962  }else if( u.ai.res ){
59963    pc = pOp->p2-1;
59964  }
59965
59966  /* Undo any changes made by applyAffinity() to the input registers. */
59967  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
59968  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
59969  break;
59970}
59971
59972/* Opcode: Permutation * * * P4 *
59973**
59974** Set the permutation used by the OP_Compare operator to be the array
59975** of integers in P4.
59976**
59977** The permutation is only valid until the next OP_Permutation, OP_Compare,
59978** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
59979** immediately prior to the OP_Compare.
59980*/
59981case OP_Permutation: {
59982  assert( pOp->p4type==P4_INTARRAY );
59983  assert( pOp->p4.ai );
59984  aPermute = pOp->p4.ai;
59985  break;
59986}
59987
59988/* Opcode: Compare P1 P2 P3 P4 *
59989**
59990** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
59991** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
59992** the comparison for use by the next OP_Jump instruct.
59993**
59994** P4 is a KeyInfo structure that defines collating sequences and sort
59995** orders for the comparison.  The permutation applies to registers
59996** only.  The KeyInfo elements are used sequentially.
59997**
59998** The comparison is a sort comparison, so NULLs compare equal,
59999** NULLs are less than numbers, numbers are less than strings,
60000** and strings are less than blobs.
60001*/
60002case OP_Compare: {
60003#if 0  /* local variables moved into u.aj */
60004  int n;
60005  int i;
60006  int p1;
60007  int p2;
60008  const KeyInfo *pKeyInfo;
60009  int idx;
60010  CollSeq *pColl;    /* Collating sequence to use on this term */
60011  int bRev;          /* True for DESCENDING sort order */
60012#endif /* local variables moved into u.aj */
60013
60014  u.aj.n = pOp->p3;
60015  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
60016  assert( u.aj.n>0 );
60017  assert( u.aj.pKeyInfo!=0 );
60018  u.aj.p1 = pOp->p1;
60019  u.aj.p2 = pOp->p2;
60020#if SQLITE_DEBUG
60021  if( aPermute ){
60022    int k, mx = 0;
60023    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
60024    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
60025    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
60026  }else{
60027    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
60028    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
60029  }
60030#endif /* SQLITE_DEBUG */
60031  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
60032    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
60033    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
60034    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
60035    assert( u.aj.i<u.aj.pKeyInfo->nField );
60036    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
60037    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
60038    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
60039    if( iCompare ){
60040      if( u.aj.bRev ) iCompare = -iCompare;
60041      break;
60042    }
60043  }
60044  aPermute = 0;
60045  break;
60046}
60047
60048/* Opcode: Jump P1 P2 P3 * *
60049**
60050** Jump to the instruction at address P1, P2, or P3 depending on whether
60051** in the most recent OP_Compare instruction the P1 vector was less than
60052** equal to, or greater than the P2 vector, respectively.
60053*/
60054case OP_Jump: {             /* jump */
60055  if( iCompare<0 ){
60056    pc = pOp->p1 - 1;
60057  }else if( iCompare==0 ){
60058    pc = pOp->p2 - 1;
60059  }else{
60060    pc = pOp->p3 - 1;
60061  }
60062  break;
60063}
60064
60065/* Opcode: And P1 P2 P3 * *
60066**
60067** Take the logical AND of the values in registers P1 and P2 and
60068** write the result into register P3.
60069**
60070** If either P1 or P2 is 0 (false) then the result is 0 even if
60071** the other input is NULL.  A NULL and true or two NULLs give
60072** a NULL output.
60073*/
60074/* Opcode: Or P1 P2 P3 * *
60075**
60076** Take the logical OR of the values in register P1 and P2 and
60077** store the answer in register P3.
60078**
60079** If either P1 or P2 is nonzero (true) then the result is 1 (true)
60080** even if the other input is NULL.  A NULL and false or two NULLs
60081** give a NULL output.
60082*/
60083case OP_And:              /* same as TK_AND, in1, in2, out3 */
60084case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
60085#if 0  /* local variables moved into u.ak */
60086  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60087  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60088#endif /* local variables moved into u.ak */
60089
60090  pIn1 = &aMem[pOp->p1];
60091  if( pIn1->flags & MEM_Null ){
60092    u.ak.v1 = 2;
60093  }else{
60094    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
60095  }
60096  pIn2 = &aMem[pOp->p2];
60097  if( pIn2->flags & MEM_Null ){
60098    u.ak.v2 = 2;
60099  }else{
60100    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
60101  }
60102  if( pOp->opcode==OP_And ){
60103    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
60104    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
60105  }else{
60106    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
60107    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
60108  }
60109  pOut = &aMem[pOp->p3];
60110  if( u.ak.v1==2 ){
60111    MemSetTypeFlag(pOut, MEM_Null);
60112  }else{
60113    pOut->u.i = u.ak.v1;
60114    MemSetTypeFlag(pOut, MEM_Int);
60115  }
60116  break;
60117}
60118
60119/* Opcode: Not P1 P2 * * *
60120**
60121** Interpret the value in register P1 as a boolean value.  Store the
60122** boolean complement in register P2.  If the value in register P1 is
60123** NULL, then a NULL is stored in P2.
60124*/
60125case OP_Not: {                /* same as TK_NOT, in1, out2 */
60126  pIn1 = &aMem[pOp->p1];
60127  pOut = &aMem[pOp->p2];
60128  if( pIn1->flags & MEM_Null ){
60129    sqlite3VdbeMemSetNull(pOut);
60130  }else{
60131    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
60132  }
60133  break;
60134}
60135
60136/* Opcode: BitNot P1 P2 * * *
60137**
60138** Interpret the content of register P1 as an integer.  Store the
60139** ones-complement of the P1 value into register P2.  If P1 holds
60140** a NULL then store a NULL in P2.
60141*/
60142case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
60143  pIn1 = &aMem[pOp->p1];
60144  pOut = &aMem[pOp->p2];
60145  if( pIn1->flags & MEM_Null ){
60146    sqlite3VdbeMemSetNull(pOut);
60147  }else{
60148    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
60149  }
60150  break;
60151}
60152
60153/* Opcode: If P1 P2 P3 * *
60154**
60155** Jump to P2 if the value in register P1 is true.  The value is
60156** is considered true if it is numeric and non-zero.  If the value
60157** in P1 is NULL then take the jump if P3 is true.
60158*/
60159/* Opcode: IfNot P1 P2 P3 * *
60160**
60161** Jump to P2 if the value in register P1 is False.  The value is
60162** is considered true if it has a numeric value of zero.  If the value
60163** in P1 is NULL then take the jump if P3 is true.
60164*/
60165case OP_If:                 /* jump, in1 */
60166case OP_IfNot: {            /* jump, in1 */
60167#if 0  /* local variables moved into u.al */
60168  int c;
60169#endif /* local variables moved into u.al */
60170  pIn1 = &aMem[pOp->p1];
60171  if( pIn1->flags & MEM_Null ){
60172    u.al.c = pOp->p3;
60173  }else{
60174#ifdef SQLITE_OMIT_FLOATING_POINT
60175    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
60176#else
60177    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
60178#endif
60179    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
60180  }
60181  if( u.al.c ){
60182    pc = pOp->p2-1;
60183  }
60184  break;
60185}
60186
60187/* Opcode: IsNull P1 P2 * * *
60188**
60189** Jump to P2 if the value in register P1 is NULL.
60190*/
60191case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
60192  pIn1 = &aMem[pOp->p1];
60193  if( (pIn1->flags & MEM_Null)!=0 ){
60194    pc = pOp->p2 - 1;
60195  }
60196  break;
60197}
60198
60199/* Opcode: NotNull P1 P2 * * *
60200**
60201** Jump to P2 if the value in register P1 is not NULL.
60202*/
60203case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
60204  pIn1 = &aMem[pOp->p1];
60205  if( (pIn1->flags & MEM_Null)==0 ){
60206    pc = pOp->p2 - 1;
60207  }
60208  break;
60209}
60210
60211/* Opcode: Column P1 P2 P3 P4 P5
60212**
60213** Interpret the data that cursor P1 points to as a structure built using
60214** the MakeRecord instruction.  (See the MakeRecord opcode for additional
60215** information about the format of the data.)  Extract the P2-th column
60216** from this record.  If there are less that (P2+1)
60217** values in the record, extract a NULL.
60218**
60219** The value extracted is stored in register P3.
60220**
60221** If the column contains fewer than P2 fields, then extract a NULL.  Or,
60222** if the P4 argument is a P4_MEM use the value of the P4 argument as
60223** the result.
60224**
60225** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
60226** then the cache of the cursor is reset prior to extracting the column.
60227** The first OP_Column against a pseudo-table after the value of the content
60228** register has changed should have this bit set.
60229*/
60230case OP_Column: {
60231#if 0  /* local variables moved into u.am */
60232  u32 payloadSize;   /* Number of bytes in the record */
60233  i64 payloadSize64; /* Number of bytes in the record */
60234  int p1;            /* P1 value of the opcode */
60235  int p2;            /* column number to retrieve */
60236  VdbeCursor *pC;    /* The VDBE cursor */
60237  char *zRec;        /* Pointer to complete record-data */
60238  BtCursor *pCrsr;   /* The BTree cursor */
60239  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60240  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60241  int nField;        /* number of fields in the record */
60242  int len;           /* The length of the serialized data for the column */
60243  int i;             /* Loop counter */
60244  char *zData;       /* Part of the record being decoded */
60245  Mem *pDest;        /* Where to write the extracted value */
60246  Mem sMem;          /* For storing the record being decoded */
60247  u8 *zIdx;          /* Index into header */
60248  u8 *zEndHdr;       /* Pointer to first byte after the header */
60249  u32 offset;        /* Offset into the data */
60250  u32 szField;       /* Number of bytes in the content of a field */
60251  int szHdr;         /* Size of the header size field at start of record */
60252  int avail;         /* Number of bytes of available data */
60253  Mem *pReg;         /* PseudoTable input register */
60254#endif /* local variables moved into u.am */
60255
60256
60257  u.am.p1 = pOp->p1;
60258  u.am.p2 = pOp->p2;
60259  u.am.pC = 0;
60260  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
60261  assert( u.am.p1<p->nCursor );
60262  assert( pOp->p3>0 && pOp->p3<=p->nMem );
60263  u.am.pDest = &aMem[pOp->p3];
60264  MemSetTypeFlag(u.am.pDest, MEM_Null);
60265  u.am.zRec = 0;
60266
60267  /* This block sets the variable u.am.payloadSize to be the total number of
60268  ** bytes in the record.
60269  **
60270  ** u.am.zRec is set to be the complete text of the record if it is available.
60271  ** The complete record text is always available for pseudo-tables
60272  ** If the record is stored in a cursor, the complete record text
60273  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
60274  ** If the data is unavailable,  u.am.zRec is set to NULL.
60275  **
60276  ** We also compute the number of columns in the record.  For cursors,
60277  ** the number of columns is stored in the VdbeCursor.nField element.
60278  */
60279  u.am.pC = p->apCsr[u.am.p1];
60280  assert( u.am.pC!=0 );
60281#ifndef SQLITE_OMIT_VIRTUALTABLE
60282  assert( u.am.pC->pVtabCursor==0 );
60283#endif
60284  u.am.pCrsr = u.am.pC->pCursor;
60285  if( u.am.pCrsr!=0 ){
60286    /* The record is stored in a B-Tree */
60287    rc = sqlite3VdbeCursorMoveto(u.am.pC);
60288    if( rc ) goto abort_due_to_error;
60289    if( u.am.pC->nullRow ){
60290      u.am.payloadSize = 0;
60291    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
60292      u.am.payloadSize = u.am.pC->payloadSize;
60293      u.am.zRec = (char*)u.am.pC->aRow;
60294    }else if( u.am.pC->isIndex ){
60295      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60296      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
60297      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
60298      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
60299      ** payload size, so it is impossible for u.am.payloadSize64 to be
60300      ** larger than 32 bits. */
60301      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
60302      u.am.payloadSize = (u32)u.am.payloadSize64;
60303    }else{
60304      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60305      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
60306      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
60307    }
60308  }else if( u.am.pC->pseudoTableReg>0 ){
60309    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
60310    assert( u.am.pReg->flags & MEM_Blob );
60311    u.am.payloadSize = u.am.pReg->n;
60312    u.am.zRec = u.am.pReg->z;
60313    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
60314    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
60315  }else{
60316    /* Consider the row to be NULL */
60317    u.am.payloadSize = 0;
60318  }
60319
60320  /* If u.am.payloadSize is 0, then just store a NULL */
60321  if( u.am.payloadSize==0 ){
60322    assert( u.am.pDest->flags&MEM_Null );
60323    goto op_column_out;
60324  }
60325  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
60326  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
60327    goto too_big;
60328  }
60329
60330  u.am.nField = u.am.pC->nField;
60331  assert( u.am.p2<u.am.nField );
60332
60333  /* Read and parse the table header.  Store the results of the parse
60334  ** into the record header cache fields of the cursor.
60335  */
60336  u.am.aType = u.am.pC->aType;
60337  if( u.am.pC->cacheStatus==p->cacheCtr ){
60338    u.am.aOffset = u.am.pC->aOffset;
60339  }else{
60340    assert(u.am.aType);
60341    u.am.avail = 0;
60342    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
60343    u.am.pC->payloadSize = u.am.payloadSize;
60344    u.am.pC->cacheStatus = p->cacheCtr;
60345
60346    /* Figure out how many bytes are in the header */
60347    if( u.am.zRec ){
60348      u.am.zData = u.am.zRec;
60349    }else{
60350      if( u.am.pC->isIndex ){
60351        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
60352      }else{
60353        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
60354      }
60355      /* If KeyFetch()/DataFetch() managed to get the entire payload,
60356      ** save the payload in the u.am.pC->aRow cache.  That will save us from
60357      ** having to make additional calls to fetch the content portion of
60358      ** the record.
60359      */
60360      assert( u.am.avail>=0 );
60361      if( u.am.payloadSize <= (u32)u.am.avail ){
60362        u.am.zRec = u.am.zData;
60363        u.am.pC->aRow = (u8*)u.am.zData;
60364      }else{
60365        u.am.pC->aRow = 0;
60366      }
60367    }
60368    /* The following assert is true in all cases accept when
60369    ** the database file has been corrupted externally.
60370    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
60371    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
60372
60373    /* Make sure a corrupt database has not given us an oversize header.
60374    ** Do this now to avoid an oversize memory allocation.
60375    **
60376    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
60377    ** types use so much data space that there can only be 4096 and 32 of
60378    ** them, respectively.  So the maximum header length results from a
60379    ** 3-byte type for each of the maximum of 32768 columns plus three
60380    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
60381    */
60382    if( u.am.offset > 98307 ){
60383      rc = SQLITE_CORRUPT_BKPT;
60384      goto op_column_out;
60385    }
60386
60387    /* Compute in u.am.len the number of bytes of data we need to read in order
60388    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
60389    ** u.am.nField might be significantly less than the true number of columns
60390    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
60391    ** We want to minimize u.am.len in order to limit the size of the memory
60392    ** allocation, especially if a corrupt database file has caused u.am.offset
60393    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
60394    ** still exceed Robson memory allocation limits on some configurations.
60395    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
60396    ** will likely be much smaller since u.am.nField will likely be less than
60397    ** 20 or so.  This insures that Robson memory allocation limits are
60398    ** not exceeded even for corrupt database files.
60399    */
60400    u.am.len = u.am.nField*5 + 3;
60401    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
60402
60403    /* The KeyFetch() or DataFetch() above are fast and will get the entire
60404    ** record header in most cases.  But they will fail to get the complete
60405    ** record header if the record header does not fit on a single page
60406    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
60407    ** acquire the complete header text.
60408    */
60409    if( !u.am.zRec && u.am.avail<u.am.len ){
60410      u.am.sMem.flags = 0;
60411      u.am.sMem.db = 0;
60412      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
60413      if( rc!=SQLITE_OK ){
60414        goto op_column_out;
60415      }
60416      u.am.zData = u.am.sMem.z;
60417    }
60418    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
60419    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
60420
60421    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
60422    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
60423    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
60424    ** of the record to the start of the data for the u.am.i-th column
60425    */
60426    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
60427      if( u.am.zIdx<u.am.zEndHdr ){
60428        u.am.aOffset[u.am.i] = u.am.offset;
60429        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
60430        u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
60431        u.am.offset += u.am.szField;
60432        if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
60433          u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
60434          break;
60435        }
60436      }else{
60437        /* If u.am.i is less that u.am.nField, then there are less fields in this
60438        ** record than SetNumColumns indicated there are columns in the
60439        ** table. Set the u.am.offset for any extra columns not present in
60440        ** the record to 0. This tells code below to store a NULL
60441        ** instead of deserializing a value from the record.
60442        */
60443        u.am.aOffset[u.am.i] = 0;
60444      }
60445    }
60446    sqlite3VdbeMemRelease(&u.am.sMem);
60447    u.am.sMem.flags = MEM_Null;
60448
60449    /* If we have read more header data than was contained in the header,
60450    ** or if the end of the last field appears to be past the end of the
60451    ** record, or if the end of the last field appears to be before the end
60452    ** of the record (when all fields present), then we must be dealing
60453    ** with a corrupt database.
60454    */
60455    if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
60456         || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
60457      rc = SQLITE_CORRUPT_BKPT;
60458      goto op_column_out;
60459    }
60460  }
60461
60462  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
60463  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
60464  ** then there are not enough fields in the record to satisfy the
60465  ** request.  In this case, set the value NULL or to P4 if P4 is
60466  ** a pointer to a Mem object.
60467  */
60468  if( u.am.aOffset[u.am.p2] ){
60469    assert( rc==SQLITE_OK );
60470    if( u.am.zRec ){
60471      sqlite3VdbeMemReleaseExternal(u.am.pDest);
60472      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
60473    }else{
60474      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
60475      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
60476      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
60477      if( rc!=SQLITE_OK ){
60478        goto op_column_out;
60479      }
60480      u.am.zData = u.am.sMem.z;
60481      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
60482    }
60483    u.am.pDest->enc = encoding;
60484  }else{
60485    if( pOp->p4type==P4_MEM ){
60486      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
60487    }else{
60488      assert( u.am.pDest->flags&MEM_Null );
60489    }
60490  }
60491
60492  /* If we dynamically allocated space to hold the data (in the
60493  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
60494  ** dynamically allocated space over to the u.am.pDest structure.
60495  ** This prevents a memory copy.
60496  */
60497  if( u.am.sMem.zMalloc ){
60498    assert( u.am.sMem.z==u.am.sMem.zMalloc );
60499    assert( !(u.am.pDest->flags & MEM_Dyn) );
60500    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
60501    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
60502    u.am.pDest->flags |= MEM_Term;
60503    u.am.pDest->z = u.am.sMem.z;
60504    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
60505  }
60506
60507  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
60508
60509op_column_out:
60510  UPDATE_MAX_BLOBSIZE(u.am.pDest);
60511  REGISTER_TRACE(pOp->p3, u.am.pDest);
60512  break;
60513}
60514
60515/* Opcode: Affinity P1 P2 * P4 *
60516**
60517** Apply affinities to a range of P2 registers starting with P1.
60518**
60519** P4 is a string that is P2 characters long. The nth character of the
60520** string indicates the column affinity that should be used for the nth
60521** memory cell in the range.
60522*/
60523case OP_Affinity: {
60524#if 0  /* local variables moved into u.an */
60525  const char *zAffinity;   /* The affinity to be applied */
60526  char cAff;               /* A single character of affinity */
60527#endif /* local variables moved into u.an */
60528
60529  u.an.zAffinity = pOp->p4.z;
60530  assert( u.an.zAffinity!=0 );
60531  assert( u.an.zAffinity[pOp->p2]==0 );
60532  pIn1 = &aMem[pOp->p1];
60533  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
60534    assert( pIn1 <= &p->aMem[p->nMem] );
60535    ExpandBlob(pIn1);
60536    applyAffinity(pIn1, u.an.cAff, encoding);
60537    pIn1++;
60538  }
60539  break;
60540}
60541
60542/* Opcode: MakeRecord P1 P2 P3 P4 *
60543**
60544** Convert P2 registers beginning with P1 into a single entry
60545** suitable for use as a data record in a database table or as a key
60546** in an index.  The details of the format are irrelevant as long as
60547** the OP_Column opcode can decode the record later.
60548** Refer to source code comments for the details of the record
60549** format.
60550**
60551** P4 may be a string that is P2 characters long.  The nth character of the
60552** string indicates the column affinity that should be used for the nth
60553** field of the index key.
60554**
60555** The mapping from character to affinity is given by the SQLITE_AFF_
60556** macros defined in sqliteInt.h.
60557**
60558** If P4 is NULL then all index fields have the affinity NONE.
60559*/
60560case OP_MakeRecord: {
60561#if 0  /* local variables moved into u.ao */
60562  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60563  Mem *pRec;             /* The new record */
60564  u64 nData;             /* Number of bytes of data space */
60565  int nHdr;              /* Number of bytes of header space */
60566  i64 nByte;             /* Data space required for this record */
60567  int nZero;             /* Number of zero bytes at the end of the record */
60568  int nVarint;           /* Number of bytes in a varint */
60569  u32 serial_type;       /* Type field */
60570  Mem *pData0;           /* First field to be combined into the record */
60571  Mem *pLast;            /* Last field of the record */
60572  int nField;            /* Number of fields in the record */
60573  char *zAffinity;       /* The affinity string for the record */
60574  int file_format;       /* File format to use for encoding */
60575  int i;                 /* Space used in zNewRecord[] */
60576  int len;               /* Length of a field */
60577#endif /* local variables moved into u.ao */
60578
60579  /* Assuming the record contains N fields, the record format looks
60580  ** like this:
60581  **
60582  ** ------------------------------------------------------------------------
60583  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
60584  ** ------------------------------------------------------------------------
60585  **
60586  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
60587  ** and so froth.
60588  **
60589  ** Each type field is a varint representing the serial type of the
60590  ** corresponding data element (see sqlite3VdbeSerialType()). The
60591  ** hdr-size field is also a varint which is the offset from the beginning
60592  ** of the record to data0.
60593  */
60594  u.ao.nData = 0;         /* Number of bytes of data space */
60595  u.ao.nHdr = 0;          /* Number of bytes of header space */
60596  u.ao.nByte = 0;         /* Data space required for this record */
60597  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
60598  u.ao.nField = pOp->p1;
60599  u.ao.zAffinity = pOp->p4.z;
60600  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
60601  u.ao.pData0 = &aMem[u.ao.nField];
60602  u.ao.nField = pOp->p2;
60603  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
60604  u.ao.file_format = p->minWriteFileFormat;
60605
60606  /* Loop through the elements that will make up the record to figure
60607  ** out how much space is required for the new record.
60608  */
60609  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
60610    if( u.ao.zAffinity ){
60611      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
60612    }
60613    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
60614      sqlite3VdbeMemExpandBlob(u.ao.pRec);
60615    }
60616    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
60617    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
60618    u.ao.nData += u.ao.len;
60619    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
60620    if( u.ao.pRec->flags & MEM_Zero ){
60621      /* Only pure zero-filled BLOBs can be input to this Opcode.
60622      ** We do not allow blobs with a prefix and a zero-filled tail. */
60623      u.ao.nZero += u.ao.pRec->u.nZero;
60624    }else if( u.ao.len ){
60625      u.ao.nZero = 0;
60626    }
60627  }
60628
60629  /* Add the initial header varint and total the size */
60630  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
60631  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
60632    u.ao.nHdr++;
60633  }
60634  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
60635  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60636    goto too_big;
60637  }
60638
60639  /* Make sure the output register has a buffer large enough to store
60640  ** the new record. The output register (pOp->p3) is not allowed to
60641  ** be one of the input registers (because the following call to
60642  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
60643  */
60644  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
60645  pOut = &aMem[pOp->p3];
60646  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
60647    goto no_mem;
60648  }
60649  u.ao.zNewRecord = (u8 *)pOut->z;
60650
60651  /* Write the record */
60652  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
60653  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
60654    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
60655    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
60656  }
60657  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
60658    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
60659  }
60660  assert( u.ao.i==u.ao.nByte );
60661
60662  assert( pOp->p3>0 && pOp->p3<=p->nMem );
60663  pOut->n = (int)u.ao.nByte;
60664  pOut->flags = MEM_Blob | MEM_Dyn;
60665  pOut->xDel = 0;
60666  if( u.ao.nZero ){
60667    pOut->u.nZero = u.ao.nZero;
60668    pOut->flags |= MEM_Zero;
60669  }
60670  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
60671  REGISTER_TRACE(pOp->p3, pOut);
60672  UPDATE_MAX_BLOBSIZE(pOut);
60673  break;
60674}
60675
60676/* Opcode: Count P1 P2 * * *
60677**
60678** Store the number of entries (an integer value) in the table or index
60679** opened by cursor P1 in register P2
60680*/
60681#ifndef SQLITE_OMIT_BTREECOUNT
60682case OP_Count: {         /* out2-prerelease */
60683#if 0  /* local variables moved into u.ap */
60684  i64 nEntry;
60685  BtCursor *pCrsr;
60686#endif /* local variables moved into u.ap */
60687
60688  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
60689  if( u.ap.pCrsr ){
60690    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
60691  }else{
60692    u.ap.nEntry = 0;
60693  }
60694  pOut->u.i = u.ap.nEntry;
60695  break;
60696}
60697#endif
60698
60699/* Opcode: Savepoint P1 * * P4 *
60700**
60701** Open, release or rollback the savepoint named by parameter P4, depending
60702** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
60703** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
60704*/
60705case OP_Savepoint: {
60706#if 0  /* local variables moved into u.aq */
60707  int p1;                         /* Value of P1 operand */
60708  char *zName;                    /* Name of savepoint */
60709  int nName;
60710  Savepoint *pNew;
60711  Savepoint *pSavepoint;
60712  Savepoint *pTmp;
60713  int iSavepoint;
60714  int ii;
60715#endif /* local variables moved into u.aq */
60716
60717  u.aq.p1 = pOp->p1;
60718  u.aq.zName = pOp->p4.z;
60719
60720  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
60721  ** transaction, then there cannot be any savepoints.
60722  */
60723  assert( db->pSavepoint==0 || db->autoCommit==0 );
60724  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
60725  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
60726  assert( checkSavepointCount(db) );
60727
60728  if( u.aq.p1==SAVEPOINT_BEGIN ){
60729    if( db->writeVdbeCnt>0 ){
60730      /* A new savepoint cannot be created if there are active write
60731      ** statements (i.e. open read/write incremental blob handles).
60732      */
60733      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
60734        "SQL statements in progress");
60735      rc = SQLITE_BUSY;
60736    }else{
60737      u.aq.nName = sqlite3Strlen30(u.aq.zName);
60738
60739      /* Create a new savepoint structure. */
60740      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
60741      if( u.aq.pNew ){
60742        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
60743        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
60744
60745        /* If there is no open transaction, then mark this as a special
60746        ** "transaction savepoint". */
60747        if( db->autoCommit ){
60748          db->autoCommit = 0;
60749          db->isTransactionSavepoint = 1;
60750        }else{
60751          db->nSavepoint++;
60752        }
60753
60754        /* Link the new savepoint into the database handle's list. */
60755        u.aq.pNew->pNext = db->pSavepoint;
60756        db->pSavepoint = u.aq.pNew;
60757        u.aq.pNew->nDeferredCons = db->nDeferredCons;
60758      }
60759    }
60760  }else{
60761    u.aq.iSavepoint = 0;
60762
60763    /* Find the named savepoint. If there is no such savepoint, then an
60764    ** an error is returned to the user.  */
60765    for(
60766      u.aq.pSavepoint = db->pSavepoint;
60767      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
60768      u.aq.pSavepoint = u.aq.pSavepoint->pNext
60769    ){
60770      u.aq.iSavepoint++;
60771    }
60772    if( !u.aq.pSavepoint ){
60773      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
60774      rc = SQLITE_ERROR;
60775    }else if(
60776        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
60777    ){
60778      /* It is not possible to release (commit) a savepoint if there are
60779      ** active write statements. It is not possible to rollback a savepoint
60780      ** if there are any active statements at all.
60781      */
60782      sqlite3SetString(&p->zErrMsg, db,
60783        "cannot %s savepoint - SQL statements in progress",
60784        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
60785      );
60786      rc = SQLITE_BUSY;
60787    }else{
60788
60789      /* Determine whether or not this is a transaction savepoint. If so,
60790      ** and this is a RELEASE command, then the current transaction
60791      ** is committed.
60792      */
60793      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
60794      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
60795        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
60796          goto vdbe_return;
60797        }
60798        db->autoCommit = 1;
60799        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
60800          p->pc = pc;
60801          db->autoCommit = 0;
60802          p->rc = rc = SQLITE_BUSY;
60803          goto vdbe_return;
60804        }
60805        db->isTransactionSavepoint = 0;
60806        rc = p->rc;
60807      }else{
60808        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
60809        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
60810          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
60811          if( rc!=SQLITE_OK ){
60812            goto abort_due_to_error;
60813          }
60814        }
60815        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
60816          sqlite3ExpirePreparedStatements(db);
60817          sqlite3ResetInternalSchema(db, 0);
60818        }
60819      }
60820
60821      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
60822      ** savepoints nested inside of the savepoint being operated on. */
60823      while( db->pSavepoint!=u.aq.pSavepoint ){
60824        u.aq.pTmp = db->pSavepoint;
60825        db->pSavepoint = u.aq.pTmp->pNext;
60826        sqlite3DbFree(db, u.aq.pTmp);
60827        db->nSavepoint--;
60828      }
60829
60830      /* If it is a RELEASE, then destroy the savepoint being operated on
60831      ** too. If it is a ROLLBACK TO, then set the number of deferred
60832      ** constraint violations present in the database to the value stored
60833      ** when the savepoint was created.  */
60834      if( u.aq.p1==SAVEPOINT_RELEASE ){
60835        assert( u.aq.pSavepoint==db->pSavepoint );
60836        db->pSavepoint = u.aq.pSavepoint->pNext;
60837        sqlite3DbFree(db, u.aq.pSavepoint);
60838        if( !isTransaction ){
60839          db->nSavepoint--;
60840        }
60841      }else{
60842        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
60843      }
60844    }
60845  }
60846
60847  break;
60848}
60849
60850/* Opcode: AutoCommit P1 P2 * * *
60851**
60852** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
60853** back any currently active btree transactions. If there are any active
60854** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
60855** there are active writing VMs or active VMs that use shared cache.
60856**
60857** This instruction causes the VM to halt.
60858*/
60859case OP_AutoCommit: {
60860#if 0  /* local variables moved into u.ar */
60861  int desiredAutoCommit;
60862  int iRollback;
60863  int turnOnAC;
60864#endif /* local variables moved into u.ar */
60865
60866  u.ar.desiredAutoCommit = pOp->p1;
60867  u.ar.iRollback = pOp->p2;
60868  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
60869  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
60870  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
60871  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
60872
60873  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
60874    /* If this instruction implements a ROLLBACK and other VMs are
60875    ** still running, and a transaction is active, return an error indicating
60876    ** that the other VMs must complete first.
60877    */
60878    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
60879        "SQL statements in progress");
60880    rc = SQLITE_BUSY;
60881  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
60882    /* If this instruction implements a COMMIT and other VMs are writing
60883    ** return an error indicating that the other VMs must complete first.
60884    */
60885    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
60886        "SQL statements in progress");
60887    rc = SQLITE_BUSY;
60888  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
60889    if( u.ar.iRollback ){
60890      assert( u.ar.desiredAutoCommit==1 );
60891      sqlite3RollbackAll(db);
60892      db->autoCommit = 1;
60893    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
60894      goto vdbe_return;
60895    }else{
60896      db->autoCommit = (u8)u.ar.desiredAutoCommit;
60897      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
60898        p->pc = pc;
60899        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
60900        p->rc = rc = SQLITE_BUSY;
60901        goto vdbe_return;
60902      }
60903    }
60904    assert( db->nStatement==0 );
60905    sqlite3CloseSavepoints(db);
60906    if( p->rc==SQLITE_OK ){
60907      rc = SQLITE_DONE;
60908    }else{
60909      rc = SQLITE_ERROR;
60910    }
60911    goto vdbe_return;
60912  }else{
60913    sqlite3SetString(&p->zErrMsg, db,
60914        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
60915        (u.ar.iRollback)?"cannot rollback - no transaction is active":
60916                   "cannot commit - no transaction is active"));
60917
60918    rc = SQLITE_ERROR;
60919  }
60920  break;
60921}
60922
60923/* Opcode: Transaction P1 P2 * * *
60924**
60925** Begin a transaction.  The transaction ends when a Commit or Rollback
60926** opcode is encountered.  Depending on the ON CONFLICT setting, the
60927** transaction might also be rolled back if an error is encountered.
60928**
60929** P1 is the index of the database file on which the transaction is
60930** started.  Index 0 is the main database file and index 1 is the
60931** file used for temporary tables.  Indices of 2 or more are used for
60932** attached databases.
60933**
60934** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
60935** obtained on the database file when a write-transaction is started.  No
60936** other process can start another write transaction while this transaction is
60937** underway.  Starting a write transaction also creates a rollback journal. A
60938** write transaction must be started before any changes can be made to the
60939** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
60940** on the file.
60941**
60942** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
60943** true (this flag is set if the Vdbe may modify more than one row and may
60944** throw an ABORT exception), a statement transaction may also be opened.
60945** More specifically, a statement transaction is opened iff the database
60946** connection is currently not in autocommit mode, or if there are other
60947** active statements. A statement transaction allows the affects of this
60948** VDBE to be rolled back after an error without having to roll back the
60949** entire transaction. If no error is encountered, the statement transaction
60950** will automatically commit when the VDBE halts.
60951**
60952** If P2 is zero, then a read-lock is obtained on the database file.
60953*/
60954case OP_Transaction: {
60955#if 0  /* local variables moved into u.as */
60956  Btree *pBt;
60957#endif /* local variables moved into u.as */
60958
60959  assert( pOp->p1>=0 && pOp->p1<db->nDb );
60960  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
60961  u.as.pBt = db->aDb[pOp->p1].pBt;
60962
60963  if( u.as.pBt ){
60964    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
60965    if( rc==SQLITE_BUSY ){
60966      p->pc = pc;
60967      p->rc = rc = SQLITE_BUSY;
60968      goto vdbe_return;
60969    }
60970    if( rc!=SQLITE_OK ){
60971      goto abort_due_to_error;
60972    }
60973
60974    if( pOp->p2 && p->usesStmtJournal
60975     && (db->autoCommit==0 || db->activeVdbeCnt>1)
60976    ){
60977      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
60978      if( p->iStatement==0 ){
60979        assert( db->nStatement>=0 && db->nSavepoint>=0 );
60980        db->nStatement++;
60981        p->iStatement = db->nSavepoint + db->nStatement;
60982      }
60983      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
60984
60985      /* Store the current value of the database handles deferred constraint
60986      ** counter. If the statement transaction needs to be rolled back,
60987      ** the value of this counter needs to be restored too.  */
60988      p->nStmtDefCons = db->nDeferredCons;
60989    }
60990  }
60991  break;
60992}
60993
60994/* Opcode: ReadCookie P1 P2 P3 * *
60995**
60996** Read cookie number P3 from database P1 and write it into register P2.
60997** P3==1 is the schema version.  P3==2 is the database format.
60998** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
60999** the main database file and P1==1 is the database file used to store
61000** temporary tables.
61001**
61002** There must be a read-lock on the database (either a transaction
61003** must be started or there must be an open cursor) before
61004** executing this instruction.
61005*/
61006case OP_ReadCookie: {               /* out2-prerelease */
61007#if 0  /* local variables moved into u.at */
61008  int iMeta;
61009  int iDb;
61010  int iCookie;
61011#endif /* local variables moved into u.at */
61012
61013  u.at.iDb = pOp->p1;
61014  u.at.iCookie = pOp->p3;
61015  assert( pOp->p3<SQLITE_N_BTREE_META );
61016  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
61017  assert( db->aDb[u.at.iDb].pBt!=0 );
61018  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
61019
61020  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
61021  pOut->u.i = u.at.iMeta;
61022  break;
61023}
61024
61025/* Opcode: SetCookie P1 P2 P3 * *
61026**
61027** Write the content of register P3 (interpreted as an integer)
61028** into cookie number P2 of database P1.  P2==1 is the schema version.
61029** P2==2 is the database format. P2==3 is the recommended pager cache
61030** size, and so forth.  P1==0 is the main database file and P1==1 is the
61031** database file used to store temporary tables.
61032**
61033** A transaction must be started before executing this opcode.
61034*/
61035case OP_SetCookie: {       /* in3 */
61036#if 0  /* local variables moved into u.au */
61037  Db *pDb;
61038#endif /* local variables moved into u.au */
61039  assert( pOp->p2<SQLITE_N_BTREE_META );
61040  assert( pOp->p1>=0 && pOp->p1<db->nDb );
61041  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61042  u.au.pDb = &db->aDb[pOp->p1];
61043  assert( u.au.pDb->pBt!=0 );
61044  pIn3 = &aMem[pOp->p3];
61045  sqlite3VdbeMemIntegerify(pIn3);
61046  /* See note about index shifting on OP_ReadCookie */
61047  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
61048  if( pOp->p2==BTREE_SCHEMA_VERSION ){
61049    /* When the schema cookie changes, record the new cookie internally */
61050    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
61051    db->flags |= SQLITE_InternChanges;
61052  }else if( pOp->p2==BTREE_FILE_FORMAT ){
61053    /* Record changes in the file format */
61054    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
61055  }
61056  if( pOp->p1==1 ){
61057    /* Invalidate all prepared statements whenever the TEMP database
61058    ** schema is changed.  Ticket #1644 */
61059    sqlite3ExpirePreparedStatements(db);
61060    p->expired = 0;
61061  }
61062  break;
61063}
61064
61065/* Opcode: VerifyCookie P1 P2 *
61066**
61067** Check the value of global database parameter number 0 (the
61068** schema version) and make sure it is equal to P2.
61069** P1 is the database number which is 0 for the main database file
61070** and 1 for the file holding temporary tables and some higher number
61071** for auxiliary databases.
61072**
61073** The cookie changes its value whenever the database schema changes.
61074** This operation is used to detect when that the cookie has changed
61075** and that the current process needs to reread the schema.
61076**
61077** Either a transaction needs to have been started or an OP_Open needs
61078** to be executed (to establish a read lock) before this opcode is
61079** invoked.
61080*/
61081case OP_VerifyCookie: {
61082#if 0  /* local variables moved into u.av */
61083  int iMeta;
61084  Btree *pBt;
61085#endif /* local variables moved into u.av */
61086  assert( pOp->p1>=0 && pOp->p1<db->nDb );
61087  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61088  u.av.pBt = db->aDb[pOp->p1].pBt;
61089  if( u.av.pBt ){
61090    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
61091  }else{
61092    u.av.iMeta = 0;
61093  }
61094  if( u.av.iMeta!=pOp->p2 ){
61095    sqlite3DbFree(db, p->zErrMsg);
61096    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
61097    /* If the schema-cookie from the database file matches the cookie
61098    ** stored with the in-memory representation of the schema, do
61099    ** not reload the schema from the database file.
61100    **
61101    ** If virtual-tables are in use, this is not just an optimization.
61102    ** Often, v-tables store their data in other SQLite tables, which
61103    ** are queried from within xNext() and other v-table methods using
61104    ** prepared queries. If such a query is out-of-date, we do not want to
61105    ** discard the database schema, as the user code implementing the
61106    ** v-table would have to be ready for the sqlite3_vtab structure itself
61107    ** to be invalidated whenever sqlite3_step() is called from within
61108    ** a v-table method.
61109    */
61110    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
61111      sqlite3ResetInternalSchema(db, pOp->p1);
61112    }
61113
61114    sqlite3ExpirePreparedStatements(db);
61115    rc = SQLITE_SCHEMA;
61116  }
61117  break;
61118}
61119
61120/* Opcode: OpenRead P1 P2 P3 P4 P5
61121**
61122** Open a read-only cursor for the database table whose root page is
61123** P2 in a database file.  The database file is determined by P3.
61124** P3==0 means the main database, P3==1 means the database used for
61125** temporary tables, and P3>1 means used the corresponding attached
61126** database.  Give the new cursor an identifier of P1.  The P1
61127** values need not be contiguous but all P1 values should be small integers.
61128** It is an error for P1 to be negative.
61129**
61130** If P5!=0 then use the content of register P2 as the root page, not
61131** the value of P2 itself.
61132**
61133** There will be a read lock on the database whenever there is an
61134** open cursor.  If the database was unlocked prior to this instruction
61135** then a read lock is acquired as part of this instruction.  A read
61136** lock allows other processes to read the database but prohibits
61137** any other process from modifying the database.  The read lock is
61138** released when all cursors are closed.  If this instruction attempts
61139** to get a read lock but fails, the script terminates with an
61140** SQLITE_BUSY error code.
61141**
61142** The P4 value may be either an integer (P4_INT32) or a pointer to
61143** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
61144** structure, then said structure defines the content and collating
61145** sequence of the index being opened. Otherwise, if P4 is an integer
61146** value, it is set to the number of columns in the table.
61147**
61148** See also OpenWrite.
61149*/
61150/* Opcode: OpenWrite P1 P2 P3 P4 P5
61151**
61152** Open a read/write cursor named P1 on the table or index whose root
61153** page is P2.  Or if P5!=0 use the content of register P2 to find the
61154** root page.
61155**
61156** The P4 value may be either an integer (P4_INT32) or a pointer to
61157** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
61158** structure, then said structure defines the content and collating
61159** sequence of the index being opened. Otherwise, if P4 is an integer
61160** value, it is set to the number of columns in the table, or to the
61161** largest index of any column of the table that is actually used.
61162**
61163** This instruction works just like OpenRead except that it opens the cursor
61164** in read/write mode.  For a given table, there can be one or more read-only
61165** cursors or a single read/write cursor but not both.
61166**
61167** See also OpenRead.
61168*/
61169case OP_OpenRead:
61170case OP_OpenWrite: {
61171#if 0  /* local variables moved into u.aw */
61172  int nField;
61173  KeyInfo *pKeyInfo;
61174  int p2;
61175  int iDb;
61176  int wrFlag;
61177  Btree *pX;
61178  VdbeCursor *pCur;
61179  Db *pDb;
61180#endif /* local variables moved into u.aw */
61181
61182  if( p->expired ){
61183    rc = SQLITE_ABORT;
61184    break;
61185  }
61186
61187  u.aw.nField = 0;
61188  u.aw.pKeyInfo = 0;
61189  u.aw.p2 = pOp->p2;
61190  u.aw.iDb = pOp->p3;
61191  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
61192  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
61193  u.aw.pDb = &db->aDb[u.aw.iDb];
61194  u.aw.pX = u.aw.pDb->pBt;
61195  assert( u.aw.pX!=0 );
61196  if( pOp->opcode==OP_OpenWrite ){
61197    u.aw.wrFlag = 1;
61198    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
61199      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
61200    }
61201  }else{
61202    u.aw.wrFlag = 0;
61203  }
61204  if( pOp->p5 ){
61205    assert( u.aw.p2>0 );
61206    assert( u.aw.p2<=p->nMem );
61207    pIn2 = &aMem[u.aw.p2];
61208    sqlite3VdbeMemIntegerify(pIn2);
61209    u.aw.p2 = (int)pIn2->u.i;
61210    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
61211    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
61212    ** If there were a failure, the prepared statement would have halted
61213    ** before reaching this instruction. */
61214    if( NEVER(u.aw.p2<2) ) {
61215      rc = SQLITE_CORRUPT_BKPT;
61216      goto abort_due_to_error;
61217    }
61218  }
61219  if( pOp->p4type==P4_KEYINFO ){
61220    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
61221    u.aw.pKeyInfo->enc = ENC(p->db);
61222    u.aw.nField = u.aw.pKeyInfo->nField+1;
61223  }else if( pOp->p4type==P4_INT32 ){
61224    u.aw.nField = pOp->p4.i;
61225  }
61226  assert( pOp->p1>=0 );
61227  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
61228  if( u.aw.pCur==0 ) goto no_mem;
61229  u.aw.pCur->nullRow = 1;
61230  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
61231  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
61232
61233  /* Since it performs no memory allocation or IO, the only values that
61234  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
61235  ** SQLITE_EMPTY is only returned when attempting to open the table
61236  ** rooted at page 1 of a zero-byte database.  */
61237  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
61238  if( rc==SQLITE_EMPTY ){
61239    u.aw.pCur->pCursor = 0;
61240    rc = SQLITE_OK;
61241  }
61242
61243  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
61244  ** SQLite used to check if the root-page flags were sane at this point
61245  ** and report database corruption if they were not, but this check has
61246  ** since moved into the btree layer.  */
61247  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
61248  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
61249  break;
61250}
61251
61252/* Opcode: OpenEphemeral P1 P2 * P4 *
61253**
61254** Open a new cursor P1 to a transient table.
61255** The cursor is always opened read/write even if
61256** the main database is read-only.  The ephemeral
61257** table is deleted automatically when the cursor is closed.
61258**
61259** P2 is the number of columns in the ephemeral table.
61260** The cursor points to a BTree table if P4==0 and to a BTree index
61261** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
61262** that defines the format of keys in the index.
61263**
61264** This opcode was once called OpenTemp.  But that created
61265** confusion because the term "temp table", might refer either
61266** to a TEMP table at the SQL level, or to a table opened by
61267** this opcode.  Then this opcode was call OpenVirtual.  But
61268** that created confusion with the whole virtual-table idea.
61269*/
61270/* Opcode: OpenAutoindex P1 P2 * P4 *
61271**
61272** This opcode works the same as OP_OpenEphemeral.  It has a
61273** different name to distinguish its use.  Tables created using
61274** by this opcode will be used for automatically created transient
61275** indices in joins.
61276*/
61277case OP_OpenAutoindex:
61278case OP_OpenEphemeral: {
61279#if 0  /* local variables moved into u.ax */
61280  VdbeCursor *pCx;
61281#endif /* local variables moved into u.ax */
61282  static const int openFlags =
61283      SQLITE_OPEN_READWRITE |
61284      SQLITE_OPEN_CREATE |
61285      SQLITE_OPEN_EXCLUSIVE |
61286      SQLITE_OPEN_DELETEONCLOSE |
61287      SQLITE_OPEN_TRANSIENT_DB;
61288
61289  assert( pOp->p1>=0 );
61290  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
61291  if( u.ax.pCx==0 ) goto no_mem;
61292  u.ax.pCx->nullRow = 1;
61293  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
61294                           &u.ax.pCx->pBt);
61295  if( rc==SQLITE_OK ){
61296    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
61297  }
61298  if( rc==SQLITE_OK ){
61299    /* If a transient index is required, create it by calling
61300    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
61301    ** opening it. If a transient table is required, just use the
61302    ** automatically created table with root-page 1 (an INTKEY table).
61303    */
61304    if( pOp->p4.pKeyInfo ){
61305      int pgno;
61306      assert( pOp->p4type==P4_KEYINFO );
61307      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
61308      if( rc==SQLITE_OK ){
61309        assert( pgno==MASTER_ROOT+1 );
61310        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
61311                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
61312        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
61313        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
61314      }
61315      u.ax.pCx->isTable = 0;
61316    }else{
61317      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
61318      u.ax.pCx->isTable = 1;
61319    }
61320  }
61321  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
61322  break;
61323}
61324
61325/* Opcode: OpenPseudo P1 P2 P3 * *
61326**
61327** Open a new cursor that points to a fake table that contains a single
61328** row of data.  The content of that one row in the content of memory
61329** register P2.  In other words, cursor P1 becomes an alias for the
61330** MEM_Blob content contained in register P2.
61331**
61332** A pseudo-table created by this opcode is used to hold a single
61333** row output from the sorter so that the row can be decomposed into
61334** individual columns using the OP_Column opcode.  The OP_Column opcode
61335** is the only cursor opcode that works with a pseudo-table.
61336**
61337** P3 is the number of fields in the records that will be stored by
61338** the pseudo-table.
61339*/
61340case OP_OpenPseudo: {
61341#if 0  /* local variables moved into u.ay */
61342  VdbeCursor *pCx;
61343#endif /* local variables moved into u.ay */
61344
61345  assert( pOp->p1>=0 );
61346  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
61347  if( u.ay.pCx==0 ) goto no_mem;
61348  u.ay.pCx->nullRow = 1;
61349  u.ay.pCx->pseudoTableReg = pOp->p2;
61350  u.ay.pCx->isTable = 1;
61351  u.ay.pCx->isIndex = 0;
61352  break;
61353}
61354
61355/* Opcode: Close P1 * * * *
61356**
61357** Close a cursor previously opened as P1.  If P1 is not
61358** currently open, this instruction is a no-op.
61359*/
61360case OP_Close: {
61361  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61362  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
61363  p->apCsr[pOp->p1] = 0;
61364  break;
61365}
61366
61367/* Opcode: SeekGe P1 P2 P3 P4 *
61368**
61369** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
61370** use the value in register P3 as the key.  If cursor P1 refers
61371** to an SQL index, then P3 is the first in an array of P4 registers
61372** that are used as an unpacked index key.
61373**
61374** Reposition cursor P1 so that  it points to the smallest entry that
61375** is greater than or equal to the key value. If there are no records
61376** greater than or equal to the key and P2 is not zero, then jump to P2.
61377**
61378** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
61379*/
61380/* Opcode: SeekGt P1 P2 P3 P4 *
61381**
61382** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
61383** use the value in register P3 as a key. If cursor P1 refers
61384** to an SQL index, then P3 is the first in an array of P4 registers
61385** that are used as an unpacked index key.
61386**
61387** Reposition cursor P1 so that  it points to the smallest entry that
61388** is greater than the key value. If there are no records greater than
61389** the key and P2 is not zero, then jump to P2.
61390**
61391** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
61392*/
61393/* Opcode: SeekLt P1 P2 P3 P4 *
61394**
61395** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
61396** use the value in register P3 as a key. If cursor P1 refers
61397** to an SQL index, then P3 is the first in an array of P4 registers
61398** that are used as an unpacked index key.
61399**
61400** Reposition cursor P1 so that  it points to the largest entry that
61401** is less than the key value. If there are no records less than
61402** the key and P2 is not zero, then jump to P2.
61403**
61404** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
61405*/
61406/* Opcode: SeekLe P1 P2 P3 P4 *
61407**
61408** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
61409** use the value in register P3 as a key. If cursor P1 refers
61410** to an SQL index, then P3 is the first in an array of P4 registers
61411** that are used as an unpacked index key.
61412**
61413** Reposition cursor P1 so that it points to the largest entry that
61414** is less than or equal to the key value. If there are no records
61415** less than or equal to the key and P2 is not zero, then jump to P2.
61416**
61417** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
61418*/
61419case OP_SeekLt:         /* jump, in3 */
61420case OP_SeekLe:         /* jump, in3 */
61421case OP_SeekGe:         /* jump, in3 */
61422case OP_SeekGt: {       /* jump, in3 */
61423#if 0  /* local variables moved into u.az */
61424  int res;
61425  int oc;
61426  VdbeCursor *pC;
61427  UnpackedRecord r;
61428  int nField;
61429  i64 iKey;      /* The rowid we are to seek to */
61430#endif /* local variables moved into u.az */
61431
61432  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61433  assert( pOp->p2!=0 );
61434  u.az.pC = p->apCsr[pOp->p1];
61435  assert( u.az.pC!=0 );
61436  assert( u.az.pC->pseudoTableReg==0 );
61437  assert( OP_SeekLe == OP_SeekLt+1 );
61438  assert( OP_SeekGe == OP_SeekLt+2 );
61439  assert( OP_SeekGt == OP_SeekLt+3 );
61440  if( u.az.pC->pCursor!=0 ){
61441    u.az.oc = pOp->opcode;
61442    u.az.pC->nullRow = 0;
61443    if( u.az.pC->isTable ){
61444      /* The input value in P3 might be of any type: integer, real, string,
61445      ** blob, or NULL.  But it needs to be an integer before we can do
61446      ** the seek, so covert it. */
61447      pIn3 = &aMem[pOp->p3];
61448      applyNumericAffinity(pIn3);
61449      u.az.iKey = sqlite3VdbeIntValue(pIn3);
61450      u.az.pC->rowidIsValid = 0;
61451
61452      /* If the P3 value could not be converted into an integer without
61453      ** loss of information, then special processing is required... */
61454      if( (pIn3->flags & MEM_Int)==0 ){
61455        if( (pIn3->flags & MEM_Real)==0 ){
61456          /* If the P3 value cannot be converted into any kind of a number,
61457          ** then the seek is not possible, so jump to P2 */
61458          pc = pOp->p2 - 1;
61459          break;
61460        }
61461        /* If we reach this point, then the P3 value must be a floating
61462        ** point number. */
61463        assert( (pIn3->flags & MEM_Real)!=0 );
61464
61465        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
61466          /* The P3 value is too large in magnitude to be expressed as an
61467          ** integer. */
61468          u.az.res = 1;
61469          if( pIn3->r<0 ){
61470            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61471              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
61472              if( rc!=SQLITE_OK ) goto abort_due_to_error;
61473            }
61474          }else{
61475            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61476              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
61477              if( rc!=SQLITE_OK ) goto abort_due_to_error;
61478            }
61479          }
61480          if( u.az.res ){
61481            pc = pOp->p2 - 1;
61482          }
61483          break;
61484        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
61485          /* Use the ceiling() function to convert real->int */
61486          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
61487        }else{
61488          /* Use the floor() function to convert real->int */
61489          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
61490          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
61491        }
61492      }
61493      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
61494      if( rc!=SQLITE_OK ){
61495        goto abort_due_to_error;
61496      }
61497      if( u.az.res==0 ){
61498        u.az.pC->rowidIsValid = 1;
61499        u.az.pC->lastRowid = u.az.iKey;
61500      }
61501    }else{
61502      u.az.nField = pOp->p4.i;
61503      assert( pOp->p4type==P4_INT32 );
61504      assert( u.az.nField>0 );
61505      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
61506      u.az.r.nField = (u16)u.az.nField;
61507
61508      /* The next line of code computes as follows, only faster:
61509      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
61510      **     u.az.r.flags = UNPACKED_INCRKEY;
61511      **   }else{
61512      **     u.az.r.flags = 0;
61513      **   }
61514      */
61515      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
61516      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
61517      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
61518      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
61519      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
61520
61521      u.az.r.aMem = &aMem[pOp->p3];
61522      ExpandBlob(u.az.r.aMem);
61523      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
61524      if( rc!=SQLITE_OK ){
61525        goto abort_due_to_error;
61526      }
61527      u.az.pC->rowidIsValid = 0;
61528    }
61529    u.az.pC->deferredMoveto = 0;
61530    u.az.pC->cacheStatus = CACHE_STALE;
61531#ifdef SQLITE_TEST
61532    sqlite3_search_count++;
61533#endif
61534    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61535      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
61536        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
61537        if( rc!=SQLITE_OK ) goto abort_due_to_error;
61538        u.az.pC->rowidIsValid = 0;
61539      }else{
61540        u.az.res = 0;
61541      }
61542    }else{
61543      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61544      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
61545        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
61546        if( rc!=SQLITE_OK ) goto abort_due_to_error;
61547        u.az.pC->rowidIsValid = 0;
61548      }else{
61549        /* u.az.res might be negative because the table is empty.  Check to
61550        ** see if this is the case.
61551        */
61552        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
61553      }
61554    }
61555    assert( pOp->p2>0 );
61556    if( u.az.res ){
61557      pc = pOp->p2 - 1;
61558    }
61559  }else{
61560    /* This happens when attempting to open the sqlite3_master table
61561    ** for read access returns SQLITE_EMPTY. In this case always
61562    ** take the jump (since there are no records in the table).
61563    */
61564    pc = pOp->p2 - 1;
61565  }
61566  break;
61567}
61568
61569/* Opcode: Seek P1 P2 * * *
61570**
61571** P1 is an open table cursor and P2 is a rowid integer.  Arrange
61572** for P1 to move so that it points to the rowid given by P2.
61573**
61574** This is actually a deferred seek.  Nothing actually happens until
61575** the cursor is used to read a record.  That way, if no reads
61576** occur, no unnecessary I/O happens.
61577*/
61578case OP_Seek: {    /* in2 */
61579#if 0  /* local variables moved into u.ba */
61580  VdbeCursor *pC;
61581#endif /* local variables moved into u.ba */
61582
61583  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61584  u.ba.pC = p->apCsr[pOp->p1];
61585  assert( u.ba.pC!=0 );
61586  if( ALWAYS(u.ba.pC->pCursor!=0) ){
61587    assert( u.ba.pC->isTable );
61588    u.ba.pC->nullRow = 0;
61589    pIn2 = &aMem[pOp->p2];
61590    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
61591    u.ba.pC->rowidIsValid = 0;
61592    u.ba.pC->deferredMoveto = 1;
61593  }
61594  break;
61595}
61596
61597
61598/* Opcode: Found P1 P2 P3 P4 *
61599**
61600** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61601** P4>0 then register P3 is the first of P4 registers that form an unpacked
61602** record.
61603**
61604** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61605** is a prefix of any entry in P1 then a jump is made to P2 and
61606** P1 is left pointing at the matching entry.
61607*/
61608/* Opcode: NotFound P1 P2 P3 P4 *
61609**
61610** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61611** P4>0 then register P3 is the first of P4 registers that form an unpacked
61612** record.
61613**
61614** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61615** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
61616** does contain an entry whose prefix matches the P3/P4 record then control
61617** falls through to the next instruction and P1 is left pointing at the
61618** matching entry.
61619**
61620** See also: Found, NotExists, IsUnique
61621*/
61622case OP_NotFound:       /* jump, in3 */
61623case OP_Found: {        /* jump, in3 */
61624#if 0  /* local variables moved into u.bb */
61625  int alreadyExists;
61626  VdbeCursor *pC;
61627  int res;
61628  UnpackedRecord *pIdxKey;
61629  UnpackedRecord r;
61630  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
61631#endif /* local variables moved into u.bb */
61632
61633#ifdef SQLITE_TEST
61634  sqlite3_found_count++;
61635#endif
61636
61637  u.bb.alreadyExists = 0;
61638  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61639  assert( pOp->p4type==P4_INT32 );
61640  u.bb.pC = p->apCsr[pOp->p1];
61641  assert( u.bb.pC!=0 );
61642  pIn3 = &aMem[pOp->p3];
61643  if( ALWAYS(u.bb.pC->pCursor!=0) ){
61644
61645    assert( u.bb.pC->isTable==0 );
61646    if( pOp->p4.i>0 ){
61647      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
61648      u.bb.r.nField = (u16)pOp->p4.i;
61649      u.bb.r.aMem = pIn3;
61650      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
61651      u.bb.pIdxKey = &u.bb.r;
61652    }else{
61653      assert( pIn3->flags & MEM_Blob );
61654      ExpandBlob(pIn3);
61655      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
61656                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
61657      if( u.bb.pIdxKey==0 ){
61658        goto no_mem;
61659      }
61660      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
61661    }
61662    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
61663    if( pOp->p4.i==0 ){
61664      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
61665    }
61666    if( rc!=SQLITE_OK ){
61667      break;
61668    }
61669    u.bb.alreadyExists = (u.bb.res==0);
61670    u.bb.pC->deferredMoveto = 0;
61671    u.bb.pC->cacheStatus = CACHE_STALE;
61672  }
61673  if( pOp->opcode==OP_Found ){
61674    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
61675  }else{
61676    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
61677  }
61678  break;
61679}
61680
61681/* Opcode: IsUnique P1 P2 P3 P4 *
61682**
61683** Cursor P1 is open on an index b-tree - that is to say, a btree which
61684** no data and where the key are records generated by OP_MakeRecord with
61685** the list field being the integer ROWID of the entry that the index
61686** entry refers to.
61687**
61688** The P3 register contains an integer record number. Call this record
61689** number R. Register P4 is the first in a set of N contiguous registers
61690** that make up an unpacked index key that can be used with cursor P1.
61691** The value of N can be inferred from the cursor. N includes the rowid
61692** value appended to the end of the index record. This rowid value may
61693** or may not be the same as R.
61694**
61695** If any of the N registers beginning with register P4 contains a NULL
61696** value, jump immediately to P2.
61697**
61698** Otherwise, this instruction checks if cursor P1 contains an entry
61699** where the first (N-1) fields match but the rowid value at the end
61700** of the index entry is not R. If there is no such entry, control jumps
61701** to instruction P2. Otherwise, the rowid of the conflicting index
61702** entry is copied to register P3 and control falls through to the next
61703** instruction.
61704**
61705** See also: NotFound, NotExists, Found
61706*/
61707case OP_IsUnique: {        /* jump, in3 */
61708#if 0  /* local variables moved into u.bc */
61709  u16 ii;
61710  VdbeCursor *pCx;
61711  BtCursor *pCrsr;
61712  u16 nField;
61713  Mem *aMx;
61714  UnpackedRecord r;                  /* B-Tree index search key */
61715  i64 R;                             /* Rowid stored in register P3 */
61716#endif /* local variables moved into u.bc */
61717
61718  pIn3 = &aMem[pOp->p3];
61719  u.bc.aMx = &aMem[pOp->p4.i];
61720  /* Assert that the values of parameters P1 and P4 are in range. */
61721  assert( pOp->p4type==P4_INT32 );
61722  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
61723  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61724
61725  /* Find the index cursor. */
61726  u.bc.pCx = p->apCsr[pOp->p1];
61727  assert( u.bc.pCx->deferredMoveto==0 );
61728  u.bc.pCx->seekResult = 0;
61729  u.bc.pCx->cacheStatus = CACHE_STALE;
61730  u.bc.pCrsr = u.bc.pCx->pCursor;
61731
61732  /* If any of the values are NULL, take the jump. */
61733  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
61734  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
61735    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
61736      pc = pOp->p2 - 1;
61737      u.bc.pCrsr = 0;
61738      break;
61739    }
61740  }
61741  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
61742
61743  if( u.bc.pCrsr!=0 ){
61744    /* Populate the index search key. */
61745    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
61746    u.bc.r.nField = u.bc.nField + 1;
61747    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
61748    u.bc.r.aMem = u.bc.aMx;
61749
61750    /* Extract the value of u.bc.R from register P3. */
61751    sqlite3VdbeMemIntegerify(pIn3);
61752    u.bc.R = pIn3->u.i;
61753
61754    /* Search the B-Tree index. If no conflicting record is found, jump
61755    ** to P2. Otherwise, copy the rowid of the conflicting record to
61756    ** register P3 and fall through to the next instruction.  */
61757    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
61758    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
61759      pc = pOp->p2 - 1;
61760    }else{
61761      pIn3->u.i = u.bc.r.rowid;
61762    }
61763  }
61764  break;
61765}
61766
61767/* Opcode: NotExists P1 P2 P3 * *
61768**
61769** Use the content of register P3 as a integer key.  If a record
61770** with that key does not exist in table of P1, then jump to P2.
61771** If the record does exist, then fall thru.  The cursor is left
61772** pointing to the record if it exists.
61773**
61774** The difference between this operation and NotFound is that this
61775** operation assumes the key is an integer and that P1 is a table whereas
61776** NotFound assumes key is a blob constructed from MakeRecord and
61777** P1 is an index.
61778**
61779** See also: Found, NotFound, IsUnique
61780*/
61781case OP_NotExists: {        /* jump, in3 */
61782#if 0  /* local variables moved into u.bd */
61783  VdbeCursor *pC;
61784  BtCursor *pCrsr;
61785  int res;
61786  u64 iKey;
61787#endif /* local variables moved into u.bd */
61788
61789  pIn3 = &aMem[pOp->p3];
61790  assert( pIn3->flags & MEM_Int );
61791  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61792  u.bd.pC = p->apCsr[pOp->p1];
61793  assert( u.bd.pC!=0 );
61794  assert( u.bd.pC->isTable );
61795  assert( u.bd.pC->pseudoTableReg==0 );
61796  u.bd.pCrsr = u.bd.pC->pCursor;
61797  if( u.bd.pCrsr!=0 ){
61798    u.bd.res = 0;
61799    u.bd.iKey = pIn3->u.i;
61800    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
61801    u.bd.pC->lastRowid = pIn3->u.i;
61802    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
61803    u.bd.pC->nullRow = 0;
61804    u.bd.pC->cacheStatus = CACHE_STALE;
61805    u.bd.pC->deferredMoveto = 0;
61806    if( u.bd.res!=0 ){
61807      pc = pOp->p2 - 1;
61808      assert( u.bd.pC->rowidIsValid==0 );
61809    }
61810    u.bd.pC->seekResult = u.bd.res;
61811  }else{
61812    /* This happens when an attempt to open a read cursor on the
61813    ** sqlite_master table returns SQLITE_EMPTY.
61814    */
61815    pc = pOp->p2 - 1;
61816    assert( u.bd.pC->rowidIsValid==0 );
61817    u.bd.pC->seekResult = 0;
61818  }
61819  break;
61820}
61821
61822/* Opcode: Sequence P1 P2 * * *
61823**
61824** Find the next available sequence number for cursor P1.
61825** Write the sequence number into register P2.
61826** The sequence number on the cursor is incremented after this
61827** instruction.
61828*/
61829case OP_Sequence: {           /* out2-prerelease */
61830  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61831  assert( p->apCsr[pOp->p1]!=0 );
61832  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
61833  break;
61834}
61835
61836
61837/* Opcode: NewRowid P1 P2 P3 * *
61838**
61839** Get a new integer record number (a.k.a "rowid") used as the key to a table.
61840** The record number is not previously used as a key in the database
61841** table that cursor P1 points to.  The new record number is written
61842** written to register P2.
61843**
61844** If P3>0 then P3 is a register in the root frame of this VDBE that holds
61845** the largest previously generated record number. No new record numbers are
61846** allowed to be less than this value. When this value reaches its maximum,
61847** a SQLITE_FULL error is generated. The P3 register is updated with the '
61848** generated record number. This P3 mechanism is used to help implement the
61849** AUTOINCREMENT feature.
61850*/
61851case OP_NewRowid: {           /* out2-prerelease */
61852#if 0  /* local variables moved into u.be */
61853  i64 v;                 /* The new rowid */
61854  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
61855  int res;               /* Result of an sqlite3BtreeLast() */
61856  int cnt;               /* Counter to limit the number of searches */
61857  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
61858  VdbeFrame *pFrame;     /* Root frame of VDBE */
61859#endif /* local variables moved into u.be */
61860
61861  u.be.v = 0;
61862  u.be.res = 0;
61863  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61864  u.be.pC = p->apCsr[pOp->p1];
61865  assert( u.be.pC!=0 );
61866  if( NEVER(u.be.pC->pCursor==0) ){
61867    /* The zero initialization above is all that is needed */
61868  }else{
61869    /* The next rowid or record number (different terms for the same
61870    ** thing) is obtained in a two-step algorithm.
61871    **
61872    ** First we attempt to find the largest existing rowid and add one
61873    ** to that.  But if the largest existing rowid is already the maximum
61874    ** positive integer, we have to fall through to the second
61875    ** probabilistic algorithm
61876    **
61877    ** The second algorithm is to select a rowid at random and see if
61878    ** it already exists in the table.  If it does not exist, we have
61879    ** succeeded.  If the random rowid does exist, we select a new one
61880    ** and try again, up to 100 times.
61881    */
61882    assert( u.be.pC->isTable );
61883    u.be.cnt = 0;
61884
61885#ifdef SQLITE_32BIT_ROWID
61886#   define MAX_ROWID 0x7fffffff
61887#else
61888    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
61889    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
61890    ** to provide the constant while making all compilers happy.
61891    */
61892#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
61893#endif
61894
61895    if( !u.be.pC->useRandomRowid ){
61896      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
61897      if( u.be.v==0 ){
61898        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
61899        if( rc!=SQLITE_OK ){
61900          goto abort_due_to_error;
61901        }
61902        if( u.be.res ){
61903          u.be.v = 1;   /* IMP: R-61914-48074 */
61904        }else{
61905          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
61906          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
61907          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
61908          if( u.be.v==MAX_ROWID ){
61909            u.be.pC->useRandomRowid = 1;
61910          }else{
61911            u.be.v++;   /* IMP: R-29538-34987 */
61912          }
61913        }
61914      }
61915
61916#ifndef SQLITE_OMIT_AUTOINCREMENT
61917      if( pOp->p3 ){
61918        /* Assert that P3 is a valid memory cell. */
61919        assert( pOp->p3>0 );
61920        if( p->pFrame ){
61921          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
61922          /* Assert that P3 is a valid memory cell. */
61923          assert( pOp->p3<=u.be.pFrame->nMem );
61924          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
61925        }else{
61926          /* Assert that P3 is a valid memory cell. */
61927          assert( pOp->p3<=p->nMem );
61928          u.be.pMem = &aMem[pOp->p3];
61929        }
61930
61931        REGISTER_TRACE(pOp->p3, u.be.pMem);
61932        sqlite3VdbeMemIntegerify(u.be.pMem);
61933        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
61934        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
61935          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
61936          goto abort_due_to_error;
61937        }
61938        if( u.be.v<u.be.pMem->u.i+1 ){
61939          u.be.v = u.be.pMem->u.i + 1;
61940        }
61941        u.be.pMem->u.i = u.be.v;
61942      }
61943#endif
61944
61945      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
61946    }
61947    if( u.be.pC->useRandomRowid ){
61948      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
61949      ** largest possible integer (9223372036854775807) then the database
61950      ** engine starts picking candidate ROWIDs at random until it finds one
61951      ** that is not previously used.
61952      */
61953      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
61954                             ** an AUTOINCREMENT table. */
61955      u.be.v = db->lastRowid;
61956      u.be.cnt = 0;
61957      do{
61958        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
61959          u.be.v++;
61960        }else{
61961          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
61962          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
61963        }
61964        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
61965        u.be.cnt++;
61966      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
61967      if( rc==SQLITE_OK && u.be.res==0 ){
61968        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
61969        goto abort_due_to_error;
61970      }
61971    }
61972    u.be.pC->rowidIsValid = 0;
61973    u.be.pC->deferredMoveto = 0;
61974    u.be.pC->cacheStatus = CACHE_STALE;
61975  }
61976  pOut->u.i = u.be.v;
61977  break;
61978}
61979
61980/* Opcode: Insert P1 P2 P3 P4 P5
61981**
61982** Write an entry into the table of cursor P1.  A new entry is
61983** created if it doesn't already exist or the data for an existing
61984** entry is overwritten.  The data is the value MEM_Blob stored in register
61985** number P2. The key is stored in register P3. The key must
61986** be a MEM_Int.
61987**
61988** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
61989** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
61990** then rowid is stored for subsequent return by the
61991** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
61992**
61993** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
61994** the last seek operation (OP_NotExists) was a success, then this
61995** operation will not attempt to find the appropriate row before doing
61996** the insert but will instead overwrite the row that the cursor is
61997** currently pointing to.  Presumably, the prior OP_NotExists opcode
61998** has already positioned the cursor correctly.  This is an optimization
61999** that boosts performance by avoiding redundant seeks.
62000**
62001** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
62002** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
62003** is part of an INSERT operation.  The difference is only important to
62004** the update hook.
62005**
62006** Parameter P4 may point to a string containing the table-name, or
62007** may be NULL. If it is not NULL, then the update-hook
62008** (sqlite3.xUpdateCallback) is invoked following a successful insert.
62009**
62010** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
62011** allocated, then ownership of P2 is transferred to the pseudo-cursor
62012** and register P2 becomes ephemeral.  If the cursor is changed, the
62013** value of register P2 will then change.  Make sure this does not
62014** cause any problems.)
62015**
62016** This instruction only works on tables.  The equivalent instruction
62017** for indices is OP_IdxInsert.
62018*/
62019/* Opcode: InsertInt P1 P2 P3 P4 P5
62020**
62021** This works exactly like OP_Insert except that the key is the
62022** integer value P3, not the value of the integer stored in register P3.
62023*/
62024case OP_Insert:
62025case OP_InsertInt: {
62026#if 0  /* local variables moved into u.bf */
62027  Mem *pData;       /* MEM cell holding data for the record to be inserted */
62028  Mem *pKey;        /* MEM cell holding key  for the record */
62029  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62030  VdbeCursor *pC;   /* Cursor to table into which insert is written */
62031  int nZero;        /* Number of zero-bytes to append */
62032  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62033  const char *zDb;  /* database name - used by the update hook */
62034  const char *zTbl; /* Table name - used by the opdate hook */
62035  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62036#endif /* local variables moved into u.bf */
62037
62038  u.bf.pData = &aMem[pOp->p2];
62039  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62040  u.bf.pC = p->apCsr[pOp->p1];
62041  assert( u.bf.pC!=0 );
62042  assert( u.bf.pC->pCursor!=0 );
62043  assert( u.bf.pC->pseudoTableReg==0 );
62044  assert( u.bf.pC->isTable );
62045  REGISTER_TRACE(pOp->p2, u.bf.pData);
62046
62047  if( pOp->opcode==OP_Insert ){
62048    u.bf.pKey = &aMem[pOp->p3];
62049    assert( u.bf.pKey->flags & MEM_Int );
62050    REGISTER_TRACE(pOp->p3, u.bf.pKey);
62051    u.bf.iKey = u.bf.pKey->u.i;
62052  }else{
62053    assert( pOp->opcode==OP_InsertInt );
62054    u.bf.iKey = pOp->p3;
62055  }
62056
62057  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
62058  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
62059  if( u.bf.pData->flags & MEM_Null ){
62060    u.bf.pData->z = 0;
62061    u.bf.pData->n = 0;
62062  }else{
62063    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
62064  }
62065  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
62066  if( u.bf.pData->flags & MEM_Zero ){
62067    u.bf.nZero = u.bf.pData->u.nZero;
62068  }else{
62069    u.bf.nZero = 0;
62070  }
62071  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
62072  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
62073                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
62074                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
62075  );
62076  u.bf.pC->rowidIsValid = 0;
62077  u.bf.pC->deferredMoveto = 0;
62078  u.bf.pC->cacheStatus = CACHE_STALE;
62079
62080  /* Invoke the update-hook if required. */
62081  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62082    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
62083    u.bf.zTbl = pOp->p4.z;
62084    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
62085    assert( u.bf.pC->isTable );
62086    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
62087    assert( u.bf.pC->iDb>=0 );
62088  }
62089  break;
62090}
62091
62092/* Opcode: Delete P1 P2 * P4 *
62093**
62094** Delete the record at which the P1 cursor is currently pointing.
62095**
62096** The cursor will be left pointing at either the next or the previous
62097** record in the table. If it is left pointing at the next record, then
62098** the next Next instruction will be a no-op.  Hence it is OK to delete
62099** a record from within an Next loop.
62100**
62101** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
62102** incremented (otherwise not).
62103**
62104** P1 must not be pseudo-table.  It has to be a real table with
62105** multiple rows.
62106**
62107** If P4 is not NULL, then it is the name of the table that P1 is
62108** pointing to.  The update hook will be invoked, if it exists.
62109** If P4 is not NULL then the P1 cursor must have been positioned
62110** using OP_NotFound prior to invoking this opcode.
62111*/
62112case OP_Delete: {
62113#if 0  /* local variables moved into u.bg */
62114  i64 iKey;
62115  VdbeCursor *pC;
62116#endif /* local variables moved into u.bg */
62117
62118  u.bg.iKey = 0;
62119  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62120  u.bg.pC = p->apCsr[pOp->p1];
62121  assert( u.bg.pC!=0 );
62122  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
62123
62124  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
62125  ** row being deleted.
62126  */
62127  if( db->xUpdateCallback && pOp->p4.z ){
62128    assert( u.bg.pC->isTable );
62129    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
62130    u.bg.iKey = u.bg.pC->lastRowid;
62131  }
62132
62133  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
62134  ** OP_Column on the same table without any intervening operations that
62135  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
62136  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
62137  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
62138  ** to guard against future changes to the code generator.
62139  **/
62140  assert( u.bg.pC->deferredMoveto==0 );
62141  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
62142  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62143
62144  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
62145  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
62146  u.bg.pC->cacheStatus = CACHE_STALE;
62147
62148  /* Invoke the update-hook if required. */
62149  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62150    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
62151    const char *zTbl = pOp->p4.z;
62152    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
62153    assert( u.bg.pC->iDb>=0 );
62154  }
62155  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
62156  break;
62157}
62158/* Opcode: ResetCount * * * * *
62159**
62160** The value of the change counter is copied to the database handle
62161** change counter (returned by subsequent calls to sqlite3_changes()).
62162** Then the VMs internal change counter resets to 0.
62163** This is used by trigger programs.
62164*/
62165case OP_ResetCount: {
62166  sqlite3VdbeSetChanges(db, p->nChange);
62167  p->nChange = 0;
62168  break;
62169}
62170
62171/* Opcode: RowData P1 P2 * * *
62172**
62173** Write into register P2 the complete row data for cursor P1.
62174** There is no interpretation of the data.
62175** It is just copied onto the P2 register exactly as
62176** it is found in the database file.
62177**
62178** If the P1 cursor must be pointing to a valid row (not a NULL row)
62179** of a real table, not a pseudo-table.
62180*/
62181/* Opcode: RowKey P1 P2 * * *
62182**
62183** Write into register P2 the complete row key for cursor P1.
62184** There is no interpretation of the data.
62185** The key is copied onto the P3 register exactly as
62186** it is found in the database file.
62187**
62188** If the P1 cursor must be pointing to a valid row (not a NULL row)
62189** of a real table, not a pseudo-table.
62190*/
62191case OP_RowKey:
62192case OP_RowData: {
62193#if 0  /* local variables moved into u.bh */
62194  VdbeCursor *pC;
62195  BtCursor *pCrsr;
62196  u32 n;
62197  i64 n64;
62198#endif /* local variables moved into u.bh */
62199
62200  pOut = &aMem[pOp->p2];
62201
62202  /* Note that RowKey and RowData are really exactly the same instruction */
62203  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62204  u.bh.pC = p->apCsr[pOp->p1];
62205  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
62206  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
62207  assert( u.bh.pC!=0 );
62208  assert( u.bh.pC->nullRow==0 );
62209  assert( u.bh.pC->pseudoTableReg==0 );
62210  assert( u.bh.pC->pCursor!=0 );
62211  u.bh.pCrsr = u.bh.pC->pCursor;
62212  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
62213
62214  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
62215  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
62216  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
62217  ** a no-op and can never fail.  But we leave it in place as a safety.
62218  */
62219  assert( u.bh.pC->deferredMoveto==0 );
62220  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
62221  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62222
62223  if( u.bh.pC->isIndex ){
62224    assert( !u.bh.pC->isTable );
62225    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
62226    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
62227    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
62228      goto too_big;
62229    }
62230    u.bh.n = (u32)u.bh.n64;
62231  }else{
62232    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
62233    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
62234    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62235      goto too_big;
62236    }
62237  }
62238  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
62239    goto no_mem;
62240  }
62241  pOut->n = u.bh.n;
62242  MemSetTypeFlag(pOut, MEM_Blob);
62243  if( u.bh.pC->isIndex ){
62244    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62245  }else{
62246    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62247  }
62248  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
62249  UPDATE_MAX_BLOBSIZE(pOut);
62250  break;
62251}
62252
62253/* Opcode: Rowid P1 P2 * * *
62254**
62255** Store in register P2 an integer which is the key of the table entry that
62256** P1 is currently point to.
62257**
62258** P1 can be either an ordinary table or a virtual table.  There used to
62259** be a separate OP_VRowid opcode for use with virtual tables, but this
62260** one opcode now works for both table types.
62261*/
62262case OP_Rowid: {                 /* out2-prerelease */
62263#if 0  /* local variables moved into u.bi */
62264  VdbeCursor *pC;
62265  i64 v;
62266  sqlite3_vtab *pVtab;
62267  const sqlite3_module *pModule;
62268#endif /* local variables moved into u.bi */
62269
62270  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62271  u.bi.pC = p->apCsr[pOp->p1];
62272  assert( u.bi.pC!=0 );
62273  assert( u.bi.pC->pseudoTableReg==0 );
62274  if( u.bi.pC->nullRow ){
62275    pOut->flags = MEM_Null;
62276    break;
62277  }else if( u.bi.pC->deferredMoveto ){
62278    u.bi.v = u.bi.pC->movetoTarget;
62279#ifndef SQLITE_OMIT_VIRTUALTABLE
62280  }else if( u.bi.pC->pVtabCursor ){
62281    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
62282    u.bi.pModule = u.bi.pVtab->pModule;
62283    assert( u.bi.pModule->xRowid );
62284    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
62285    sqlite3DbFree(db, p->zErrMsg);
62286    p->zErrMsg = u.bi.pVtab->zErrMsg;
62287    u.bi.pVtab->zErrMsg = 0;
62288#endif /* SQLITE_OMIT_VIRTUALTABLE */
62289  }else{
62290    assert( u.bi.pC->pCursor!=0 );
62291    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
62292    if( rc ) goto abort_due_to_error;
62293    if( u.bi.pC->rowidIsValid ){
62294      u.bi.v = u.bi.pC->lastRowid;
62295    }else{
62296      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
62297      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
62298    }
62299  }
62300  pOut->u.i = u.bi.v;
62301  break;
62302}
62303
62304/* Opcode: NullRow P1 * * * *
62305**
62306** Move the cursor P1 to a null row.  Any OP_Column operations
62307** that occur while the cursor is on the null row will always
62308** write a NULL.
62309*/
62310case OP_NullRow: {
62311#if 0  /* local variables moved into u.bj */
62312  VdbeCursor *pC;
62313#endif /* local variables moved into u.bj */
62314
62315  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62316  u.bj.pC = p->apCsr[pOp->p1];
62317  assert( u.bj.pC!=0 );
62318  u.bj.pC->nullRow = 1;
62319  u.bj.pC->rowidIsValid = 0;
62320  if( u.bj.pC->pCursor ){
62321    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
62322  }
62323  break;
62324}
62325
62326/* Opcode: Last P1 P2 * * *
62327**
62328** The next use of the Rowid or Column or Next instruction for P1
62329** will refer to the last entry in the database table or index.
62330** If the table or index is empty and P2>0, then jump immediately to P2.
62331** If P2 is 0 or if the table or index is not empty, fall through
62332** to the following instruction.
62333*/
62334case OP_Last: {        /* jump */
62335#if 0  /* local variables moved into u.bk */
62336  VdbeCursor *pC;
62337  BtCursor *pCrsr;
62338  int res;
62339#endif /* local variables moved into u.bk */
62340
62341  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62342  u.bk.pC = p->apCsr[pOp->p1];
62343  assert( u.bk.pC!=0 );
62344  u.bk.pCrsr = u.bk.pC->pCursor;
62345  if( u.bk.pCrsr==0 ){
62346    u.bk.res = 1;
62347  }else{
62348    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
62349  }
62350  u.bk.pC->nullRow = (u8)u.bk.res;
62351  u.bk.pC->deferredMoveto = 0;
62352  u.bk.pC->rowidIsValid = 0;
62353  u.bk.pC->cacheStatus = CACHE_STALE;
62354  if( pOp->p2>0 && u.bk.res ){
62355    pc = pOp->p2 - 1;
62356  }
62357  break;
62358}
62359
62360
62361/* Opcode: Sort P1 P2 * * *
62362**
62363** This opcode does exactly the same thing as OP_Rewind except that
62364** it increments an undocumented global variable used for testing.
62365**
62366** Sorting is accomplished by writing records into a sorting index,
62367** then rewinding that index and playing it back from beginning to
62368** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
62369** rewinding so that the global variable will be incremented and
62370** regression tests can determine whether or not the optimizer is
62371** correctly optimizing out sorts.
62372*/
62373case OP_Sort: {        /* jump */
62374#ifdef SQLITE_TEST
62375  sqlite3_sort_count++;
62376  sqlite3_search_count--;
62377#endif
62378  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
62379  /* Fall through into OP_Rewind */
62380}
62381/* Opcode: Rewind P1 P2 * * *
62382**
62383** The next use of the Rowid or Column or Next instruction for P1
62384** will refer to the first entry in the database table or index.
62385** If the table or index is empty and P2>0, then jump immediately to P2.
62386** If P2 is 0 or if the table or index is not empty, fall through
62387** to the following instruction.
62388*/
62389case OP_Rewind: {        /* jump */
62390#if 0  /* local variables moved into u.bl */
62391  VdbeCursor *pC;
62392  BtCursor *pCrsr;
62393  int res;
62394#endif /* local variables moved into u.bl */
62395
62396  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62397  u.bl.pC = p->apCsr[pOp->p1];
62398  assert( u.bl.pC!=0 );
62399  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
62400    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
62401    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
62402    u.bl.pC->deferredMoveto = 0;
62403    u.bl.pC->cacheStatus = CACHE_STALE;
62404    u.bl.pC->rowidIsValid = 0;
62405  }else{
62406    u.bl.res = 1;
62407  }
62408  u.bl.pC->nullRow = (u8)u.bl.res;
62409  assert( pOp->p2>0 && pOp->p2<p->nOp );
62410  if( u.bl.res ){
62411    pc = pOp->p2 - 1;
62412  }
62413  break;
62414}
62415
62416/* Opcode: Next P1 P2 * * P5
62417**
62418** Advance cursor P1 so that it points to the next key/data pair in its
62419** table or index.  If there are no more key/value pairs then fall through
62420** to the following instruction.  But if the cursor advance was successful,
62421** jump immediately to P2.
62422**
62423** The P1 cursor must be for a real table, not a pseudo-table.
62424**
62425** If P5 is positive and the jump is taken, then event counter
62426** number P5-1 in the prepared statement is incremented.
62427**
62428** See also: Prev
62429*/
62430/* Opcode: Prev P1 P2 * * P5
62431**
62432** Back up cursor P1 so that it points to the previous key/data pair in its
62433** table or index.  If there is no previous key/value pairs then fall through
62434** to the following instruction.  But if the cursor backup was successful,
62435** jump immediately to P2.
62436**
62437** The P1 cursor must be for a real table, not a pseudo-table.
62438**
62439** If P5 is positive and the jump is taken, then event counter
62440** number P5-1 in the prepared statement is incremented.
62441*/
62442case OP_Prev:          /* jump */
62443case OP_Next: {        /* jump */
62444#if 0  /* local variables moved into u.bm */
62445  VdbeCursor *pC;
62446  BtCursor *pCrsr;
62447  int res;
62448#endif /* local variables moved into u.bm */
62449
62450  CHECK_FOR_INTERRUPT;
62451  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62452  assert( pOp->p5<=ArraySize(p->aCounter) );
62453  u.bm.pC = p->apCsr[pOp->p1];
62454  if( u.bm.pC==0 ){
62455    break;  /* See ticket #2273 */
62456  }
62457  u.bm.pCrsr = u.bm.pC->pCursor;
62458  if( u.bm.pCrsr==0 ){
62459    u.bm.pC->nullRow = 1;
62460    break;
62461  }
62462  u.bm.res = 1;
62463  assert( u.bm.pC->deferredMoveto==0 );
62464  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
62465                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
62466  u.bm.pC->nullRow = (u8)u.bm.res;
62467  u.bm.pC->cacheStatus = CACHE_STALE;
62468  if( u.bm.res==0 ){
62469    pc = pOp->p2 - 1;
62470    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
62471#ifdef SQLITE_TEST
62472    sqlite3_search_count++;
62473#endif
62474  }
62475  u.bm.pC->rowidIsValid = 0;
62476  break;
62477}
62478
62479/* Opcode: IdxInsert P1 P2 P3 * P5
62480**
62481** Register P2 holds a SQL index key made using the
62482** MakeRecord instructions.  This opcode writes that key
62483** into the index P1.  Data for the entry is nil.
62484**
62485** P3 is a flag that provides a hint to the b-tree layer that this
62486** insert is likely to be an append.
62487**
62488** This instruction only works for indices.  The equivalent instruction
62489** for tables is OP_Insert.
62490*/
62491case OP_IdxInsert: {        /* in2 */
62492#if 0  /* local variables moved into u.bn */
62493  VdbeCursor *pC;
62494  BtCursor *pCrsr;
62495  int nKey;
62496  const char *zKey;
62497#endif /* local variables moved into u.bn */
62498
62499  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62500  u.bn.pC = p->apCsr[pOp->p1];
62501  assert( u.bn.pC!=0 );
62502  pIn2 = &aMem[pOp->p2];
62503  assert( pIn2->flags & MEM_Blob );
62504  u.bn.pCrsr = u.bn.pC->pCursor;
62505  if( ALWAYS(u.bn.pCrsr!=0) ){
62506    assert( u.bn.pC->isTable==0 );
62507    rc = ExpandBlob(pIn2);
62508    if( rc==SQLITE_OK ){
62509      u.bn.nKey = pIn2->n;
62510      u.bn.zKey = pIn2->z;
62511      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
62512          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
62513      );
62514      assert( u.bn.pC->deferredMoveto==0 );
62515      u.bn.pC->cacheStatus = CACHE_STALE;
62516    }
62517  }
62518  break;
62519}
62520
62521/* Opcode: IdxDelete P1 P2 P3 * *
62522**
62523** The content of P3 registers starting at register P2 form
62524** an unpacked index key. This opcode removes that entry from the
62525** index opened by cursor P1.
62526*/
62527case OP_IdxDelete: {
62528#if 0  /* local variables moved into u.bo */
62529  VdbeCursor *pC;
62530  BtCursor *pCrsr;
62531  int res;
62532  UnpackedRecord r;
62533#endif /* local variables moved into u.bo */
62534
62535  assert( pOp->p3>0 );
62536  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
62537  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62538  u.bo.pC = p->apCsr[pOp->p1];
62539  assert( u.bo.pC!=0 );
62540  u.bo.pCrsr = u.bo.pC->pCursor;
62541  if( ALWAYS(u.bo.pCrsr!=0) ){
62542    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
62543    u.bo.r.nField = (u16)pOp->p3;
62544    u.bo.r.flags = 0;
62545    u.bo.r.aMem = &aMem[pOp->p2];
62546    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
62547    if( rc==SQLITE_OK && u.bo.res==0 ){
62548      rc = sqlite3BtreeDelete(u.bo.pCrsr);
62549    }
62550    assert( u.bo.pC->deferredMoveto==0 );
62551    u.bo.pC->cacheStatus = CACHE_STALE;
62552  }
62553  break;
62554}
62555
62556/* Opcode: IdxRowid P1 P2 * * *
62557**
62558** Write into register P2 an integer which is the last entry in the record at
62559** the end of the index key pointed to by cursor P1.  This integer should be
62560** the rowid of the table entry to which this index entry points.
62561**
62562** See also: Rowid, MakeRecord.
62563*/
62564case OP_IdxRowid: {              /* out2-prerelease */
62565#if 0  /* local variables moved into u.bp */
62566  BtCursor *pCrsr;
62567  VdbeCursor *pC;
62568  i64 rowid;
62569#endif /* local variables moved into u.bp */
62570
62571  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62572  u.bp.pC = p->apCsr[pOp->p1];
62573  assert( u.bp.pC!=0 );
62574  u.bp.pCrsr = u.bp.pC->pCursor;
62575  pOut->flags = MEM_Null;
62576  if( ALWAYS(u.bp.pCrsr!=0) ){
62577    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
62578    if( NEVER(rc) ) goto abort_due_to_error;
62579    assert( u.bp.pC->deferredMoveto==0 );
62580    assert( u.bp.pC->isTable==0 );
62581    if( !u.bp.pC->nullRow ){
62582      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
62583      if( rc!=SQLITE_OK ){
62584        goto abort_due_to_error;
62585      }
62586      pOut->u.i = u.bp.rowid;
62587      pOut->flags = MEM_Int;
62588    }
62589  }
62590  break;
62591}
62592
62593/* Opcode: IdxGE P1 P2 P3 P4 P5
62594**
62595** The P4 register values beginning with P3 form an unpacked index
62596** key that omits the ROWID.  Compare this key value against the index
62597** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62598**
62599** If the P1 index entry is greater than or equal to the key value
62600** then jump to P2.  Otherwise fall through to the next instruction.
62601**
62602** If P5 is non-zero then the key value is increased by an epsilon
62603** prior to the comparison.  This make the opcode work like IdxGT except
62604** that if the key from register P3 is a prefix of the key in the cursor,
62605** the result is false whereas it would be true with IdxGT.
62606*/
62607/* Opcode: IdxLT P1 P2 P3 * P5
62608**
62609** The P4 register values beginning with P3 form an unpacked index
62610** key that omits the ROWID.  Compare this key value against the index
62611** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62612**
62613** If the P1 index entry is less than the key value then jump to P2.
62614** Otherwise fall through to the next instruction.
62615**
62616** If P5 is non-zero then the key value is increased by an epsilon prior
62617** to the comparison.  This makes the opcode work like IdxLE.
62618*/
62619case OP_IdxLT:          /* jump */
62620case OP_IdxGE: {        /* jump */
62621#if 0  /* local variables moved into u.bq */
62622  VdbeCursor *pC;
62623  int res;
62624  UnpackedRecord r;
62625#endif /* local variables moved into u.bq */
62626
62627  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62628  u.bq.pC = p->apCsr[pOp->p1];
62629  assert( u.bq.pC!=0 );
62630  if( ALWAYS(u.bq.pC->pCursor!=0) ){
62631    assert( u.bq.pC->deferredMoveto==0 );
62632    assert( pOp->p5==0 || pOp->p5==1 );
62633    assert( pOp->p4type==P4_INT32 );
62634    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
62635    u.bq.r.nField = (u16)pOp->p4.i;
62636    if( pOp->p5 ){
62637      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
62638    }else{
62639      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
62640    }
62641    u.bq.r.aMem = &aMem[pOp->p3];
62642    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
62643    if( pOp->opcode==OP_IdxLT ){
62644      u.bq.res = -u.bq.res;
62645    }else{
62646      assert( pOp->opcode==OP_IdxGE );
62647      u.bq.res++;
62648    }
62649    if( u.bq.res>0 ){
62650      pc = pOp->p2 - 1 ;
62651    }
62652  }
62653  break;
62654}
62655
62656/* Opcode: Destroy P1 P2 P3 * *
62657**
62658** Delete an entire database table or index whose root page in the database
62659** file is given by P1.
62660**
62661** The table being destroyed is in the main database file if P3==0.  If
62662** P3==1 then the table to be clear is in the auxiliary database file
62663** that is used to store tables create using CREATE TEMPORARY TABLE.
62664**
62665** If AUTOVACUUM is enabled then it is possible that another root page
62666** might be moved into the newly deleted root page in order to keep all
62667** root pages contiguous at the beginning of the database.  The former
62668** value of the root page that moved - its value before the move occurred -
62669** is stored in register P2.  If no page
62670** movement was required (because the table being dropped was already
62671** the last one in the database) then a zero is stored in register P2.
62672** If AUTOVACUUM is disabled then a zero is stored in register P2.
62673**
62674** See also: Clear
62675*/
62676case OP_Destroy: {     /* out2-prerelease */
62677#if 0  /* local variables moved into u.br */
62678  int iMoved;
62679  int iCnt;
62680  Vdbe *pVdbe;
62681  int iDb;
62682#endif /* local variables moved into u.br */
62683#ifndef SQLITE_OMIT_VIRTUALTABLE
62684  u.br.iCnt = 0;
62685  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
62686    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
62687      u.br.iCnt++;
62688    }
62689  }
62690#else
62691  u.br.iCnt = db->activeVdbeCnt;
62692#endif
62693  pOut->flags = MEM_Null;
62694  if( u.br.iCnt>1 ){
62695    rc = SQLITE_LOCKED;
62696    p->errorAction = OE_Abort;
62697  }else{
62698    u.br.iDb = pOp->p3;
62699    assert( u.br.iCnt==1 );
62700    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
62701    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
62702    pOut->flags = MEM_Int;
62703    pOut->u.i = u.br.iMoved;
62704#ifndef SQLITE_OMIT_AUTOVACUUM
62705    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
62706      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
62707      resetSchemaOnFault = 1;
62708    }
62709#endif
62710  }
62711  break;
62712}
62713
62714/* Opcode: Clear P1 P2 P3
62715**
62716** Delete all contents of the database table or index whose root page
62717** in the database file is given by P1.  But, unlike Destroy, do not
62718** remove the table or index from the database file.
62719**
62720** The table being clear is in the main database file if P2==0.  If
62721** P2==1 then the table to be clear is in the auxiliary database file
62722** that is used to store tables create using CREATE TEMPORARY TABLE.
62723**
62724** If the P3 value is non-zero, then the table referred to must be an
62725** intkey table (an SQL table, not an index). In this case the row change
62726** count is incremented by the number of rows in the table being cleared.
62727** If P3 is greater than zero, then the value stored in register P3 is
62728** also incremented by the number of rows in the table being cleared.
62729**
62730** See also: Destroy
62731*/
62732case OP_Clear: {
62733#if 0  /* local variables moved into u.bs */
62734  int nChange;
62735#endif /* local variables moved into u.bs */
62736
62737  u.bs.nChange = 0;
62738  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
62739  rc = sqlite3BtreeClearTable(
62740      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
62741  );
62742  if( pOp->p3 ){
62743    p->nChange += u.bs.nChange;
62744    if( pOp->p3>0 ){
62745      aMem[pOp->p3].u.i += u.bs.nChange;
62746    }
62747  }
62748  break;
62749}
62750
62751/* Opcode: CreateTable P1 P2 * * *
62752**
62753** Allocate a new table in the main database file if P1==0 or in the
62754** auxiliary database file if P1==1 or in an attached database if
62755** P1>1.  Write the root page number of the new table into
62756** register P2
62757**
62758** The difference between a table and an index is this:  A table must
62759** have a 4-byte integer key and can have arbitrary data.  An index
62760** has an arbitrary key but no data.
62761**
62762** See also: CreateIndex
62763*/
62764/* Opcode: CreateIndex P1 P2 * * *
62765**
62766** Allocate a new index in the main database file if P1==0 or in the
62767** auxiliary database file if P1==1 or in an attached database if
62768** P1>1.  Write the root page number of the new table into
62769** register P2.
62770**
62771** See documentation on OP_CreateTable for additional information.
62772*/
62773case OP_CreateIndex:            /* out2-prerelease */
62774case OP_CreateTable: {          /* out2-prerelease */
62775#if 0  /* local variables moved into u.bt */
62776  int pgno;
62777  int flags;
62778  Db *pDb;
62779#endif /* local variables moved into u.bt */
62780
62781  u.bt.pgno = 0;
62782  assert( pOp->p1>=0 && pOp->p1<db->nDb );
62783  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62784  u.bt.pDb = &db->aDb[pOp->p1];
62785  assert( u.bt.pDb->pBt!=0 );
62786  if( pOp->opcode==OP_CreateTable ){
62787    /* u.bt.flags = BTREE_INTKEY; */
62788    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
62789  }else{
62790    u.bt.flags = BTREE_ZERODATA;
62791  }
62792  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
62793  pOut->u.i = u.bt.pgno;
62794  break;
62795}
62796
62797/* Opcode: ParseSchema P1 P2 * P4 *
62798**
62799** Read and parse all entries from the SQLITE_MASTER table of database P1
62800** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
62801** the parsing if P2 is true.  If P2 is false, then this routine is a
62802** no-op if the schema is not currently loaded.  In other words, if P2
62803** is false, the SQLITE_MASTER table is only parsed if the rest of the
62804** schema is already loaded into the symbol table.
62805**
62806** This opcode invokes the parser to create a new virtual machine,
62807** then runs the new virtual machine.  It is thus a re-entrant opcode.
62808*/
62809case OP_ParseSchema: {
62810#if 0  /* local variables moved into u.bu */
62811  int iDb;
62812  const char *zMaster;
62813  char *zSql;
62814  InitData initData;
62815#endif /* local variables moved into u.bu */
62816
62817  u.bu.iDb = pOp->p1;
62818  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
62819
62820  /* If pOp->p2 is 0, then this opcode is being executed to read a
62821  ** single row, for example the row corresponding to a new index
62822  ** created by this VDBE, from the sqlite_master table. It only
62823  ** does this if the corresponding in-memory schema is currently
62824  ** loaded. Otherwise, the new index definition can be loaded along
62825  ** with the rest of the schema when it is required.
62826  **
62827  ** Although the mutex on the BtShared object that corresponds to
62828  ** database u.bu.iDb (the database containing the sqlite_master table
62829  ** read by this instruction) is currently held, it is necessary to
62830  ** obtain the mutexes on all attached databases before checking if
62831  ** the schema of u.bu.iDb is loaded. This is because, at the start of
62832  ** the sqlite3_exec() call below, SQLite will invoke
62833  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
62834  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
62835  ** this happens, then some other thread may delete the in-memory
62836  ** schema of database u.bu.iDb before the SQL statement runs. The schema
62837  ** will not be reloaded becuase the db->init.busy flag is set. This
62838  ** can result in a "no such table: sqlite_master" or "malformed
62839  ** database schema" error being returned to the user.
62840  */
62841  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
62842  sqlite3BtreeEnterAll(db);
62843  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
62844    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
62845    u.bu.initData.db = db;
62846    u.bu.initData.iDb = pOp->p1;
62847    u.bu.initData.pzErrMsg = &p->zErrMsg;
62848    u.bu.zSql = sqlite3MPrintf(db,
62849       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
62850       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
62851    if( u.bu.zSql==0 ){
62852      rc = SQLITE_NOMEM;
62853    }else{
62854      assert( db->init.busy==0 );
62855      db->init.busy = 1;
62856      u.bu.initData.rc = SQLITE_OK;
62857      assert( !db->mallocFailed );
62858      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
62859      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
62860      sqlite3DbFree(db, u.bu.zSql);
62861      db->init.busy = 0;
62862    }
62863  }
62864  sqlite3BtreeLeaveAll(db);
62865  if( rc==SQLITE_NOMEM ){
62866    goto no_mem;
62867  }
62868  break;
62869}
62870
62871#if !defined(SQLITE_OMIT_ANALYZE)
62872/* Opcode: LoadAnalysis P1 * * * *
62873**
62874** Read the sqlite_stat1 table for database P1 and load the content
62875** of that table into the internal index hash table.  This will cause
62876** the analysis to be used when preparing all subsequent queries.
62877*/
62878case OP_LoadAnalysis: {
62879  assert( pOp->p1>=0 && pOp->p1<db->nDb );
62880  rc = sqlite3AnalysisLoad(db, pOp->p1);
62881  break;
62882}
62883#endif /* !defined(SQLITE_OMIT_ANALYZE) */
62884
62885/* Opcode: DropTable P1 * * P4 *
62886**
62887** Remove the internal (in-memory) data structures that describe
62888** the table named P4 in database P1.  This is called after a table
62889** is dropped in order to keep the internal representation of the
62890** schema consistent with what is on disk.
62891*/
62892case OP_DropTable: {
62893  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
62894  break;
62895}
62896
62897/* Opcode: DropIndex P1 * * P4 *
62898**
62899** Remove the internal (in-memory) data structures that describe
62900** the index named P4 in database P1.  This is called after an index
62901** is dropped in order to keep the internal representation of the
62902** schema consistent with what is on disk.
62903*/
62904case OP_DropIndex: {
62905  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
62906  break;
62907}
62908
62909/* Opcode: DropTrigger P1 * * P4 *
62910**
62911** Remove the internal (in-memory) data structures that describe
62912** the trigger named P4 in database P1.  This is called after a trigger
62913** is dropped in order to keep the internal representation of the
62914** schema consistent with what is on disk.
62915*/
62916case OP_DropTrigger: {
62917  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
62918  break;
62919}
62920
62921
62922#ifndef SQLITE_OMIT_INTEGRITY_CHECK
62923/* Opcode: IntegrityCk P1 P2 P3 * P5
62924**
62925** Do an analysis of the currently open database.  Store in
62926** register P1 the text of an error message describing any problems.
62927** If no problems are found, store a NULL in register P1.
62928**
62929** The register P3 contains the maximum number of allowed errors.
62930** At most reg(P3) errors will be reported.
62931** In other words, the analysis stops as soon as reg(P1) errors are
62932** seen.  Reg(P1) is updated with the number of errors remaining.
62933**
62934** The root page numbers of all tables in the database are integer
62935** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
62936** total.
62937**
62938** If P5 is not zero, the check is done on the auxiliary database
62939** file, not the main database file.
62940**
62941** This opcode is used to implement the integrity_check pragma.
62942*/
62943case OP_IntegrityCk: {
62944#if 0  /* local variables moved into u.bv */
62945  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
62946  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
62947  int j;          /* Loop counter */
62948  int nErr;       /* Number of errors reported */
62949  char *z;        /* Text of the error report */
62950  Mem *pnErr;     /* Register keeping track of errors remaining */
62951#endif /* local variables moved into u.bv */
62952
62953  u.bv.nRoot = pOp->p2;
62954  assert( u.bv.nRoot>0 );
62955  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
62956  if( u.bv.aRoot==0 ) goto no_mem;
62957  assert( pOp->p3>0 && pOp->p3<=p->nMem );
62958  u.bv.pnErr = &aMem[pOp->p3];
62959  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
62960  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
62961  pIn1 = &aMem[pOp->p1];
62962  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
62963    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
62964  }
62965  u.bv.aRoot[u.bv.j] = 0;
62966  assert( pOp->p5<db->nDb );
62967  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
62968  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
62969                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
62970  sqlite3DbFree(db, u.bv.aRoot);
62971  u.bv.pnErr->u.i -= u.bv.nErr;
62972  sqlite3VdbeMemSetNull(pIn1);
62973  if( u.bv.nErr==0 ){
62974    assert( u.bv.z==0 );
62975  }else if( u.bv.z==0 ){
62976    goto no_mem;
62977  }else{
62978    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
62979  }
62980  UPDATE_MAX_BLOBSIZE(pIn1);
62981  sqlite3VdbeChangeEncoding(pIn1, encoding);
62982  break;
62983}
62984#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
62985
62986/* Opcode: RowSetAdd P1 P2 * * *
62987**
62988** Insert the integer value held by register P2 into a boolean index
62989** held in register P1.
62990**
62991** An assertion fails if P2 is not an integer.
62992*/
62993case OP_RowSetAdd: {       /* in1, in2 */
62994  pIn1 = &aMem[pOp->p1];
62995  pIn2 = &aMem[pOp->p2];
62996  assert( (pIn2->flags & MEM_Int)!=0 );
62997  if( (pIn1->flags & MEM_RowSet)==0 ){
62998    sqlite3VdbeMemSetRowSet(pIn1);
62999    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63000  }
63001  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
63002  break;
63003}
63004
63005/* Opcode: RowSetRead P1 P2 P3 * *
63006**
63007** Extract the smallest value from boolean index P1 and put that value into
63008** register P3.  Or, if boolean index P1 is initially empty, leave P3
63009** unchanged and jump to instruction P2.
63010*/
63011case OP_RowSetRead: {       /* jump, in1, out3 */
63012#if 0  /* local variables moved into u.bw */
63013  i64 val;
63014#endif /* local variables moved into u.bw */
63015  CHECK_FOR_INTERRUPT;
63016  pIn1 = &aMem[pOp->p1];
63017  if( (pIn1->flags & MEM_RowSet)==0
63018   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
63019  ){
63020    /* The boolean index is empty */
63021    sqlite3VdbeMemSetNull(pIn1);
63022    pc = pOp->p2 - 1;
63023  }else{
63024    /* A value was pulled from the index */
63025    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
63026  }
63027  break;
63028}
63029
63030/* Opcode: RowSetTest P1 P2 P3 P4
63031**
63032** Register P3 is assumed to hold a 64-bit integer value. If register P1
63033** contains a RowSet object and that RowSet object contains
63034** the value held in P3, jump to register P2. Otherwise, insert the
63035** integer in P3 into the RowSet and continue on to the
63036** next opcode.
63037**
63038** The RowSet object is optimized for the case where successive sets
63039** of integers, where each set contains no duplicates. Each set
63040** of values is identified by a unique P4 value. The first set
63041** must have P4==0, the final set P4=-1.  P4 must be either -1 or
63042** non-negative.  For non-negative values of P4 only the lower 4
63043** bits are significant.
63044**
63045** This allows optimizations: (a) when P4==0 there is no need to test
63046** the rowset object for P3, as it is guaranteed not to contain it,
63047** (b) when P4==-1 there is no need to insert the value, as it will
63048** never be tested for, and (c) when a value that is part of set X is
63049** inserted, there is no need to search to see if the same value was
63050** previously inserted as part of set X (only if it was previously
63051** inserted as part of some other set).
63052*/
63053case OP_RowSetTest: {                     /* jump, in1, in3 */
63054#if 0  /* local variables moved into u.bx */
63055  int iSet;
63056  int exists;
63057#endif /* local variables moved into u.bx */
63058
63059  pIn1 = &aMem[pOp->p1];
63060  pIn3 = &aMem[pOp->p3];
63061  u.bx.iSet = pOp->p4.i;
63062  assert( pIn3->flags&MEM_Int );
63063
63064  /* If there is anything other than a rowset object in memory cell P1,
63065  ** delete it now and initialize P1 with an empty rowset
63066  */
63067  if( (pIn1->flags & MEM_RowSet)==0 ){
63068    sqlite3VdbeMemSetRowSet(pIn1);
63069    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63070  }
63071
63072  assert( pOp->p4type==P4_INT32 );
63073  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
63074  if( u.bx.iSet ){
63075    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
63076                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
63077                               pIn3->u.i);
63078    if( u.bx.exists ){
63079      pc = pOp->p2 - 1;
63080      break;
63081    }
63082  }
63083  if( u.bx.iSet>=0 ){
63084    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
63085  }
63086  break;
63087}
63088
63089
63090#ifndef SQLITE_OMIT_TRIGGER
63091
63092/* Opcode: Program P1 P2 P3 P4 *
63093**
63094** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
63095**
63096** P1 contains the address of the memory cell that contains the first memory
63097** cell in an array of values used as arguments to the sub-program. P2
63098** contains the address to jump to if the sub-program throws an IGNORE
63099** exception using the RAISE() function. Register P3 contains the address
63100** of a memory cell in this (the parent) VM that is used to allocate the
63101** memory required by the sub-vdbe at runtime.
63102**
63103** P4 is a pointer to the VM containing the trigger program.
63104*/
63105case OP_Program: {        /* jump */
63106#if 0  /* local variables moved into u.by */
63107  int nMem;               /* Number of memory registers for sub-program */
63108  int nByte;              /* Bytes of runtime space required for sub-program */
63109  Mem *pRt;               /* Register to allocate runtime space */
63110  Mem *pMem;              /* Used to iterate through memory cells */
63111  Mem *pEnd;              /* Last memory cell in new array */
63112  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
63113  SubProgram *pProgram;   /* Sub-program to execute */
63114  void *t;                /* Token identifying trigger */
63115#endif /* local variables moved into u.by */
63116
63117  u.by.pProgram = pOp->p4.pProgram;
63118  u.by.pRt = &aMem[pOp->p3];
63119  assert( u.by.pProgram->nOp>0 );
63120
63121  /* If the p5 flag is clear, then recursive invocation of triggers is
63122  ** disabled for backwards compatibility (p5 is set if this sub-program
63123  ** is really a trigger, not a foreign key action, and the flag set
63124  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
63125  **
63126  ** It is recursive invocation of triggers, at the SQL level, that is
63127  ** disabled. In some cases a single trigger may generate more than one
63128  ** SubProgram (if the trigger may be executed with more than one different
63129  ** ON CONFLICT algorithm). SubProgram structures associated with a
63130  ** single trigger all have the same value for the SubProgram.token
63131  ** variable.  */
63132  if( pOp->p5 ){
63133    u.by.t = u.by.pProgram->token;
63134    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
63135    if( u.by.pFrame ) break;
63136  }
63137
63138  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
63139    rc = SQLITE_ERROR;
63140    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
63141    break;
63142  }
63143
63144  /* Register u.by.pRt is used to store the memory required to save the state
63145  ** of the current program, and the memory required at runtime to execute
63146  ** the trigger program. If this trigger has been fired before, then u.by.pRt
63147  ** is already allocated. Otherwise, it must be initialized.  */
63148  if( (u.by.pRt->flags&MEM_Frame)==0 ){
63149    /* SubProgram.nMem is set to the number of memory cells used by the
63150    ** program stored in SubProgram.aOp. As well as these, one memory
63151    ** cell is required for each cursor used by the program. Set local
63152    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
63153    */
63154    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
63155    u.by.nByte = ROUND8(sizeof(VdbeFrame))
63156              + u.by.nMem * sizeof(Mem)
63157              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
63158    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
63159    if( !u.by.pFrame ){
63160      goto no_mem;
63161    }
63162    sqlite3VdbeMemRelease(u.by.pRt);
63163    u.by.pRt->flags = MEM_Frame;
63164    u.by.pRt->u.pFrame = u.by.pFrame;
63165
63166    u.by.pFrame->v = p;
63167    u.by.pFrame->nChildMem = u.by.nMem;
63168    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
63169    u.by.pFrame->pc = pc;
63170    u.by.pFrame->aMem = p->aMem;
63171    u.by.pFrame->nMem = p->nMem;
63172    u.by.pFrame->apCsr = p->apCsr;
63173    u.by.pFrame->nCursor = p->nCursor;
63174    u.by.pFrame->aOp = p->aOp;
63175    u.by.pFrame->nOp = p->nOp;
63176    u.by.pFrame->token = u.by.pProgram->token;
63177
63178    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
63179    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
63180      u.by.pMem->flags = MEM_Null;
63181      u.by.pMem->db = db;
63182    }
63183  }else{
63184    u.by.pFrame = u.by.pRt->u.pFrame;
63185    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
63186    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
63187    assert( pc==u.by.pFrame->pc );
63188  }
63189
63190  p->nFrame++;
63191  u.by.pFrame->pParent = p->pFrame;
63192  u.by.pFrame->lastRowid = db->lastRowid;
63193  u.by.pFrame->nChange = p->nChange;
63194  p->nChange = 0;
63195  p->pFrame = u.by.pFrame;
63196  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
63197  p->nMem = u.by.pFrame->nChildMem;
63198  p->nCursor = (u16)u.by.pFrame->nChildCsr;
63199  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
63200  p->aOp = aOp = u.by.pProgram->aOp;
63201  p->nOp = u.by.pProgram->nOp;
63202  pc = -1;
63203
63204  break;
63205}
63206
63207/* Opcode: Param P1 P2 * * *
63208**
63209** This opcode is only ever present in sub-programs called via the
63210** OP_Program instruction. Copy a value currently stored in a memory
63211** cell of the calling (parent) frame to cell P2 in the current frames
63212** address space. This is used by trigger programs to access the new.*
63213** and old.* values.
63214**
63215** The address of the cell in the parent frame is determined by adding
63216** the value of the P1 argument to the value of the P1 argument to the
63217** calling OP_Program instruction.
63218*/
63219case OP_Param: {           /* out2-prerelease */
63220#if 0  /* local variables moved into u.bz */
63221  VdbeFrame *pFrame;
63222  Mem *pIn;
63223#endif /* local variables moved into u.bz */
63224  u.bz.pFrame = p->pFrame;
63225  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
63226  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
63227  break;
63228}
63229
63230#endif /* #ifndef SQLITE_OMIT_TRIGGER */
63231
63232#ifndef SQLITE_OMIT_FOREIGN_KEY
63233/* Opcode: FkCounter P1 P2 * * *
63234**
63235** Increment a "constraint counter" by P2 (P2 may be negative or positive).
63236** If P1 is non-zero, the database constraint counter is incremented
63237** (deferred foreign key constraints). Otherwise, if P1 is zero, the
63238** statement counter is incremented (immediate foreign key constraints).
63239*/
63240case OP_FkCounter: {
63241  if( pOp->p1 ){
63242    db->nDeferredCons += pOp->p2;
63243  }else{
63244    p->nFkConstraint += pOp->p2;
63245  }
63246  break;
63247}
63248
63249/* Opcode: FkIfZero P1 P2 * * *
63250**
63251** This opcode tests if a foreign key constraint-counter is currently zero.
63252** If so, jump to instruction P2. Otherwise, fall through to the next
63253** instruction.
63254**
63255** If P1 is non-zero, then the jump is taken if the database constraint-counter
63256** is zero (the one that counts deferred constraint violations). If P1 is
63257** zero, the jump is taken if the statement constraint-counter is zero
63258** (immediate foreign key constraint violations).
63259*/
63260case OP_FkIfZero: {         /* jump */
63261  if( pOp->p1 ){
63262    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
63263  }else{
63264    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
63265  }
63266  break;
63267}
63268#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
63269
63270#ifndef SQLITE_OMIT_AUTOINCREMENT
63271/* Opcode: MemMax P1 P2 * * *
63272**
63273** P1 is a register in the root frame of this VM (the root frame is
63274** different from the current frame if this instruction is being executed
63275** within a sub-program). Set the value of register P1 to the maximum of
63276** its current value and the value in register P2.
63277**
63278** This instruction throws an error if the memory cell is not initially
63279** an integer.
63280*/
63281case OP_MemMax: {        /* in2 */
63282#if 0  /* local variables moved into u.ca */
63283  Mem *pIn1;
63284  VdbeFrame *pFrame;
63285#endif /* local variables moved into u.ca */
63286  if( p->pFrame ){
63287    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
63288    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
63289  }else{
63290    u.ca.pIn1 = &aMem[pOp->p1];
63291  }
63292  sqlite3VdbeMemIntegerify(u.ca.pIn1);
63293  pIn2 = &aMem[pOp->p2];
63294  sqlite3VdbeMemIntegerify(pIn2);
63295  if( u.ca.pIn1->u.i<pIn2->u.i){
63296    u.ca.pIn1->u.i = pIn2->u.i;
63297  }
63298  break;
63299}
63300#endif /* SQLITE_OMIT_AUTOINCREMENT */
63301
63302/* Opcode: IfPos P1 P2 * * *
63303**
63304** If the value of register P1 is 1 or greater, jump to P2.
63305**
63306** It is illegal to use this instruction on a register that does
63307** not contain an integer.  An assertion fault will result if you try.
63308*/
63309case OP_IfPos: {        /* jump, in1 */
63310  pIn1 = &aMem[pOp->p1];
63311  assert( pIn1->flags&MEM_Int );
63312  if( pIn1->u.i>0 ){
63313     pc = pOp->p2 - 1;
63314  }
63315  break;
63316}
63317
63318/* Opcode: IfNeg P1 P2 * * *
63319**
63320** If the value of register P1 is less than zero, jump to P2.
63321**
63322** It is illegal to use this instruction on a register that does
63323** not contain an integer.  An assertion fault will result if you try.
63324*/
63325case OP_IfNeg: {        /* jump, in1 */
63326  pIn1 = &aMem[pOp->p1];
63327  assert( pIn1->flags&MEM_Int );
63328  if( pIn1->u.i<0 ){
63329     pc = pOp->p2 - 1;
63330  }
63331  break;
63332}
63333
63334/* Opcode: IfZero P1 P2 P3 * *
63335**
63336** The register P1 must contain an integer.  Add literal P3 to the
63337** value in register P1.  If the result is exactly 0, jump to P2.
63338**
63339** It is illegal to use this instruction on a register that does
63340** not contain an integer.  An assertion fault will result if you try.
63341*/
63342case OP_IfZero: {        /* jump, in1 */
63343  pIn1 = &aMem[pOp->p1];
63344  assert( pIn1->flags&MEM_Int );
63345  pIn1->u.i += pOp->p3;
63346  if( pIn1->u.i==0 ){
63347     pc = pOp->p2 - 1;
63348  }
63349  break;
63350}
63351
63352/* Opcode: AggStep * P2 P3 P4 P5
63353**
63354** Execute the step function for an aggregate.  The
63355** function has P5 arguments.   P4 is a pointer to the FuncDef
63356** structure that specifies the function.  Use register
63357** P3 as the accumulator.
63358**
63359** The P5 arguments are taken from register P2 and its
63360** successors.
63361*/
63362case OP_AggStep: {
63363#if 0  /* local variables moved into u.cb */
63364  int n;
63365  int i;
63366  Mem *pMem;
63367  Mem *pRec;
63368  sqlite3_context ctx;
63369  sqlite3_value **apVal;
63370#endif /* local variables moved into u.cb */
63371
63372  u.cb.n = pOp->p5;
63373  assert( u.cb.n>=0 );
63374  u.cb.pRec = &aMem[pOp->p2];
63375  u.cb.apVal = p->apArg;
63376  assert( u.cb.apVal || u.cb.n==0 );
63377  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
63378    u.cb.apVal[u.cb.i] = u.cb.pRec;
63379    sqlite3VdbeMemStoreType(u.cb.pRec);
63380  }
63381  u.cb.ctx.pFunc = pOp->p4.pFunc;
63382  assert( pOp->p3>0 && pOp->p3<=p->nMem );
63383  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
63384  u.cb.pMem->n++;
63385  u.cb.ctx.s.flags = MEM_Null;
63386  u.cb.ctx.s.z = 0;
63387  u.cb.ctx.s.zMalloc = 0;
63388  u.cb.ctx.s.xDel = 0;
63389  u.cb.ctx.s.db = db;
63390  u.cb.ctx.isError = 0;
63391  u.cb.ctx.pColl = 0;
63392  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63393    assert( pOp>p->aOp );
63394    assert( pOp[-1].p4type==P4_COLLSEQ );
63395    assert( pOp[-1].opcode==OP_CollSeq );
63396    u.cb.ctx.pColl = pOp[-1].p4.pColl;
63397  }
63398  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
63399  if( u.cb.ctx.isError ){
63400    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
63401    rc = u.cb.ctx.isError;
63402  }
63403  sqlite3VdbeMemRelease(&u.cb.ctx.s);
63404  break;
63405}
63406
63407/* Opcode: AggFinal P1 P2 * P4 *
63408**
63409** Execute the finalizer function for an aggregate.  P1 is
63410** the memory location that is the accumulator for the aggregate.
63411**
63412** P2 is the number of arguments that the step function takes and
63413** P4 is a pointer to the FuncDef for this function.  The P2
63414** argument is not used by this opcode.  It is only there to disambiguate
63415** functions that can take varying numbers of arguments.  The
63416** P4 argument is only needed for the degenerate case where
63417** the step function was not previously called.
63418*/
63419case OP_AggFinal: {
63420#if 0  /* local variables moved into u.cc */
63421  Mem *pMem;
63422#endif /* local variables moved into u.cc */
63423  assert( pOp->p1>0 && pOp->p1<=p->nMem );
63424  u.cc.pMem = &aMem[pOp->p1];
63425  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
63426  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
63427  if( rc ){
63428    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
63429  }
63430  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
63431  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
63432  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
63433    goto too_big;
63434  }
63435  break;
63436}
63437
63438#ifndef SQLITE_OMIT_WAL
63439/* Opcode: Checkpoint P1 * * * *
63440**
63441** Checkpoint database P1. This is a no-op if P1 is not currently in
63442** WAL mode.
63443*/
63444case OP_Checkpoint: {
63445  rc = sqlite3Checkpoint(db, pOp->p1);
63446  break;
63447};
63448#endif
63449
63450/* Opcode: JournalMode P1 P2 P3 * P5
63451**
63452** Change the journal mode of database P1 to P3. P3 must be one of the
63453** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
63454** modes (delete, truncate, persist, off and memory), this is a simple
63455** operation. No IO is required.
63456**
63457** If changing into or out of WAL mode the procedure is more complicated.
63458**
63459** Write a string containing the final journal-mode to register P2.
63460**
63461** If an attempt to change in to or out of WAL mode fails because another
63462** connection also has the same database open, then an SQLITE_BUSY error
63463** is raised if P5==0, or of P5!=0 the journal mode changed is skipped
63464** without signaling the error.
63465*/
63466case OP_JournalMode: {    /* out2-prerelease */
63467#if 0  /* local variables moved into u.cd */
63468  Btree *pBt;                     /* Btree to change journal mode of */
63469  Pager *pPager;                  /* Pager associated with pBt */
63470  int eNew;                       /* New journal mode */
63471  int eOld;                       /* The old journal mode */
63472  const char *zFilename;          /* Name of database file for pPager */
63473#endif /* local variables moved into u.cd */
63474
63475  u.cd.eNew = pOp->p3;
63476  assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
63477       || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
63478       || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
63479       || u.cd.eNew==PAGER_JOURNALMODE_OFF
63480       || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
63481       || u.cd.eNew==PAGER_JOURNALMODE_WAL
63482       || u.cd.eNew==PAGER_JOURNALMODE_QUERY
63483  );
63484  assert( pOp->p1>=0 && pOp->p1<db->nDb );
63485
63486  /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
63487  ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
63488  ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
63489  ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
63490  ** is not called when the statement is prepared because it requires the
63491  ** iDb index of the database as a parameter, and the database has not
63492  ** yet been attached so that index is unavailable.  We have to wait
63493  ** until runtime (now) to get the mutex on the newly attached database.
63494  ** No other mutexes are required by the ATTACH command so this is safe
63495  ** to do.
63496  */
63497  assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
63498  if( p->aMutex.nMutex==0 ){
63499    /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
63500    ** database. */
63501    sqlite3VdbeUsesBtree(p, pOp->p1);
63502    sqlite3VdbeMutexArrayEnter(p);
63503  }
63504
63505  u.cd.pBt = db->aDb[pOp->p1].pBt;
63506  u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
63507  u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
63508  if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
63509  if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
63510
63511#ifndef SQLITE_OMIT_WAL
63512  u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
63513
63514  /* Do not allow a transition to journal_mode=WAL for a database
63515  ** in temporary storage or if the VFS does not support xShmOpen.
63516  */
63517  if( u.cd.eNew==PAGER_JOURNALMODE_WAL
63518   && (u.cd.zFilename[0]==0                         /* Temp file */
63519       || !sqlite3PagerWalSupported(u.cd.pPager))   /* No xShmOpen support */
63520  ){
63521    u.cd.eNew = u.cd.eOld;
63522  }
63523
63524  if( (u.cd.eNew!=u.cd.eOld)
63525   && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
63526  ){
63527    if( !db->autoCommit || db->activeVdbeCnt>1 ){
63528      rc = SQLITE_ERROR;
63529      sqlite3SetString(&p->zErrMsg, db,
63530          "cannot change %s wal mode from within a transaction",
63531          (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
63532      );
63533      break;
63534    }else{
63535
63536      if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
63537        /* If leaving WAL mode, close the log file. If successful, the call
63538        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
63539        ** file. An EXCLUSIVE lock may still be held on the database file
63540        ** after a successful return.
63541        */
63542        rc = sqlite3PagerCloseWal(u.cd.pPager);
63543        if( rc==SQLITE_OK ){
63544          sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63545        }
63546      }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
63547        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
63548        ** as an intermediate */
63549        sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
63550      }
63551
63552      /* Open a transaction on the database file. Regardless of the journal
63553      ** mode, this transaction always uses a rollback journal.
63554      */
63555      assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
63556      if( rc==SQLITE_OK ){
63557        rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
63558      }
63559    }
63560  }
63561#endif /* ifndef SQLITE_OMIT_WAL */
63562
63563  if( rc ){
63564    if( rc==SQLITE_BUSY && pOp->p5!=0 ) rc = SQLITE_OK;
63565    u.cd.eNew = u.cd.eOld;
63566  }
63567  u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63568
63569  pOut = &aMem[pOp->p2];
63570  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63571  pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
63572  pOut->n = sqlite3Strlen30(pOut->z);
63573  pOut->enc = SQLITE_UTF8;
63574  sqlite3VdbeChangeEncoding(pOut, encoding);
63575  break;
63576};
63577
63578#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
63579/* Opcode: Vacuum * * * * *
63580**
63581** Vacuum the entire database.  This opcode will cause other virtual
63582** machines to be created and run.  It may not be called from within
63583** a transaction.
63584*/
63585case OP_Vacuum: {
63586  rc = sqlite3RunVacuum(&p->zErrMsg, db);
63587  break;
63588}
63589#endif
63590
63591#if !defined(SQLITE_OMIT_AUTOVACUUM)
63592/* Opcode: IncrVacuum P1 P2 * * *
63593**
63594** Perform a single step of the incremental vacuum procedure on
63595** the P1 database. If the vacuum has finished, jump to instruction
63596** P2. Otherwise, fall through to the next instruction.
63597*/
63598case OP_IncrVacuum: {        /* jump */
63599#if 0  /* local variables moved into u.ce */
63600  Btree *pBt;
63601#endif /* local variables moved into u.ce */
63602
63603  assert( pOp->p1>=0 && pOp->p1<db->nDb );
63604  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63605  u.ce.pBt = db->aDb[pOp->p1].pBt;
63606  rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
63607  if( rc==SQLITE_DONE ){
63608    pc = pOp->p2 - 1;
63609    rc = SQLITE_OK;
63610  }
63611  break;
63612}
63613#endif
63614
63615/* Opcode: Expire P1 * * * *
63616**
63617** Cause precompiled statements to become expired. An expired statement
63618** fails with an error code of SQLITE_SCHEMA if it is ever executed
63619** (via sqlite3_step()).
63620**
63621** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
63622** then only the currently executing statement is affected.
63623*/
63624case OP_Expire: {
63625  if( !pOp->p1 ){
63626    sqlite3ExpirePreparedStatements(db);
63627  }else{
63628    p->expired = 1;
63629  }
63630  break;
63631}
63632
63633#ifndef SQLITE_OMIT_SHARED_CACHE
63634/* Opcode: TableLock P1 P2 P3 P4 *
63635**
63636** Obtain a lock on a particular table. This instruction is only used when
63637** the shared-cache feature is enabled.
63638**
63639** P1 is the index of the database in sqlite3.aDb[] of the database
63640** on which the lock is acquired.  A readlock is obtained if P3==0 or
63641** a write lock if P3==1.
63642**
63643** P2 contains the root-page of the table to lock.
63644**
63645** P4 contains a pointer to the name of the table being locked. This is only
63646** used to generate an error message if the lock cannot be obtained.
63647*/
63648case OP_TableLock: {
63649  u8 isWriteLock = (u8)pOp->p3;
63650  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
63651    int p1 = pOp->p1;
63652    assert( p1>=0 && p1<db->nDb );
63653    assert( (p->btreeMask & (1<<p1))!=0 );
63654    assert( isWriteLock==0 || isWriteLock==1 );
63655    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
63656    if( (rc&0xFF)==SQLITE_LOCKED ){
63657      const char *z = pOp->p4.z;
63658      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
63659    }
63660  }
63661  break;
63662}
63663#endif /* SQLITE_OMIT_SHARED_CACHE */
63664
63665#ifndef SQLITE_OMIT_VIRTUALTABLE
63666/* Opcode: VBegin * * * P4 *
63667**
63668** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
63669** xBegin method for that table.
63670**
63671** Also, whether or not P4 is set, check that this is not being called from
63672** within a callback to a virtual table xSync() method. If it is, the error
63673** code will be set to SQLITE_LOCKED.
63674*/
63675case OP_VBegin: {
63676#if 0  /* local variables moved into u.cf */
63677  VTable *pVTab;
63678#endif /* local variables moved into u.cf */
63679  u.cf.pVTab = pOp->p4.pVtab;
63680  rc = sqlite3VtabBegin(db, u.cf.pVTab);
63681  if( u.cf.pVTab ){
63682    sqlite3DbFree(db, p->zErrMsg);
63683    p->zErrMsg = u.cf.pVTab->pVtab->zErrMsg;
63684    u.cf.pVTab->pVtab->zErrMsg = 0;
63685  }
63686  break;
63687}
63688#endif /* SQLITE_OMIT_VIRTUALTABLE */
63689
63690#ifndef SQLITE_OMIT_VIRTUALTABLE
63691/* Opcode: VCreate P1 * * P4 *
63692**
63693** P4 is the name of a virtual table in database P1. Call the xCreate method
63694** for that table.
63695*/
63696case OP_VCreate: {
63697  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
63698  break;
63699}
63700#endif /* SQLITE_OMIT_VIRTUALTABLE */
63701
63702#ifndef SQLITE_OMIT_VIRTUALTABLE
63703/* Opcode: VDestroy P1 * * P4 *
63704**
63705** P4 is the name of a virtual table in database P1.  Call the xDestroy method
63706** of that table.
63707*/
63708case OP_VDestroy: {
63709  p->inVtabMethod = 2;
63710  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
63711  p->inVtabMethod = 0;
63712  break;
63713}
63714#endif /* SQLITE_OMIT_VIRTUALTABLE */
63715
63716#ifndef SQLITE_OMIT_VIRTUALTABLE
63717/* Opcode: VOpen P1 * * P4 *
63718**
63719** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
63720** P1 is a cursor number.  This opcode opens a cursor to the virtual
63721** table and stores that cursor in P1.
63722*/
63723case OP_VOpen: {
63724#if 0  /* local variables moved into u.cg */
63725  VdbeCursor *pCur;
63726  sqlite3_vtab_cursor *pVtabCursor;
63727  sqlite3_vtab *pVtab;
63728  sqlite3_module *pModule;
63729#endif /* local variables moved into u.cg */
63730
63731  u.cg.pCur = 0;
63732  u.cg.pVtabCursor = 0;
63733  u.cg.pVtab = pOp->p4.pVtab->pVtab;
63734  u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
63735  assert(u.cg.pVtab && u.cg.pModule);
63736  rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
63737  sqlite3DbFree(db, p->zErrMsg);
63738  p->zErrMsg = u.cg.pVtab->zErrMsg;
63739  u.cg.pVtab->zErrMsg = 0;
63740  if( SQLITE_OK==rc ){
63741    /* Initialize sqlite3_vtab_cursor base class */
63742    u.cg.pVtabCursor->pVtab = u.cg.pVtab;
63743
63744    /* Initialise vdbe cursor object */
63745    u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
63746    if( u.cg.pCur ){
63747      u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
63748      u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
63749    }else{
63750      db->mallocFailed = 1;
63751      u.cg.pModule->xClose(u.cg.pVtabCursor);
63752    }
63753  }
63754  break;
63755}
63756#endif /* SQLITE_OMIT_VIRTUALTABLE */
63757
63758#ifndef SQLITE_OMIT_VIRTUALTABLE
63759/* Opcode: VFilter P1 P2 P3 P4 *
63760**
63761** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
63762** the filtered result set is empty.
63763**
63764** P4 is either NULL or a string that was generated by the xBestIndex
63765** method of the module.  The interpretation of the P4 string is left
63766** to the module implementation.
63767**
63768** This opcode invokes the xFilter method on the virtual table specified
63769** by P1.  The integer query plan parameter to xFilter is stored in register
63770** P3. Register P3+1 stores the argc parameter to be passed to the
63771** xFilter method. Registers P3+2..P3+1+argc are the argc
63772** additional parameters which are passed to
63773** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
63774**
63775** A jump is made to P2 if the result set after filtering would be empty.
63776*/
63777case OP_VFilter: {   /* jump */
63778#if 0  /* local variables moved into u.ch */
63779  int nArg;
63780  int iQuery;
63781  const sqlite3_module *pModule;
63782  Mem *pQuery;
63783  Mem *pArgc;
63784  sqlite3_vtab_cursor *pVtabCursor;
63785  sqlite3_vtab *pVtab;
63786  VdbeCursor *pCur;
63787  int res;
63788  int i;
63789  Mem **apArg;
63790#endif /* local variables moved into u.ch */
63791
63792  u.ch.pQuery = &aMem[pOp->p3];
63793  u.ch.pArgc = &u.ch.pQuery[1];
63794  u.ch.pCur = p->apCsr[pOp->p1];
63795  REGISTER_TRACE(pOp->p3, u.ch.pQuery);
63796  assert( u.ch.pCur->pVtabCursor );
63797  u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
63798  u.ch.pVtab = u.ch.pVtabCursor->pVtab;
63799  u.ch.pModule = u.ch.pVtab->pModule;
63800
63801  /* Grab the index number and argc parameters */
63802  assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
63803  u.ch.nArg = (int)u.ch.pArgc->u.i;
63804  u.ch.iQuery = (int)u.ch.pQuery->u.i;
63805
63806  /* Invoke the xFilter method */
63807  {
63808    u.ch.res = 0;
63809    u.ch.apArg = p->apArg;
63810    for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
63811      u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
63812      sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
63813    }
63814
63815    p->inVtabMethod = 1;
63816    rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
63817    p->inVtabMethod = 0;
63818    sqlite3DbFree(db, p->zErrMsg);
63819    p->zErrMsg = u.ch.pVtab->zErrMsg;
63820    u.ch.pVtab->zErrMsg = 0;
63821    if( rc==SQLITE_OK ){
63822      u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
63823    }
63824
63825    if( u.ch.res ){
63826      pc = pOp->p2 - 1;
63827    }
63828  }
63829  u.ch.pCur->nullRow = 0;
63830
63831  break;
63832}
63833#endif /* SQLITE_OMIT_VIRTUALTABLE */
63834
63835#ifndef SQLITE_OMIT_VIRTUALTABLE
63836/* Opcode: VColumn P1 P2 P3 * *
63837**
63838** Store the value of the P2-th column of
63839** the row of the virtual-table that the
63840** P1 cursor is pointing to into register P3.
63841*/
63842case OP_VColumn: {
63843#if 0  /* local variables moved into u.ci */
63844  sqlite3_vtab *pVtab;
63845  const sqlite3_module *pModule;
63846  Mem *pDest;
63847  sqlite3_context sContext;
63848#endif /* local variables moved into u.ci */
63849
63850  VdbeCursor *pCur = p->apCsr[pOp->p1];
63851  assert( pCur->pVtabCursor );
63852  assert( pOp->p3>0 && pOp->p3<=p->nMem );
63853  u.ci.pDest = &aMem[pOp->p3];
63854  if( pCur->nullRow ){
63855    sqlite3VdbeMemSetNull(u.ci.pDest);
63856    break;
63857  }
63858  u.ci.pVtab = pCur->pVtabCursor->pVtab;
63859  u.ci.pModule = u.ci.pVtab->pModule;
63860  assert( u.ci.pModule->xColumn );
63861  memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
63862
63863  /* The output cell may already have a buffer allocated. Move
63864  ** the current contents to u.ci.sContext.s so in case the user-function
63865  ** can use the already allocated buffer instead of allocating a
63866  ** new one.
63867  */
63868  sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
63869  MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
63870
63871  rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
63872  sqlite3DbFree(db, p->zErrMsg);
63873  p->zErrMsg = u.ci.pVtab->zErrMsg;
63874  u.ci.pVtab->zErrMsg = 0;
63875  if( u.ci.sContext.isError ){
63876    rc = u.ci.sContext.isError;
63877  }
63878
63879  /* Copy the result of the function to the P3 register. We
63880  ** do this regardless of whether or not an error occurred to ensure any
63881  ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
63882  */
63883  sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
63884  sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
63885  REGISTER_TRACE(pOp->p3, u.ci.pDest);
63886  UPDATE_MAX_BLOBSIZE(u.ci.pDest);
63887
63888  if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
63889    goto too_big;
63890  }
63891  break;
63892}
63893#endif /* SQLITE_OMIT_VIRTUALTABLE */
63894
63895#ifndef SQLITE_OMIT_VIRTUALTABLE
63896/* Opcode: VNext P1 P2 * * *
63897**
63898** Advance virtual table P1 to the next row in its result set and
63899** jump to instruction P2.  Or, if the virtual table has reached
63900** the end of its result set, then fall through to the next instruction.
63901*/
63902case OP_VNext: {   /* jump */
63903#if 0  /* local variables moved into u.cj */
63904  sqlite3_vtab *pVtab;
63905  const sqlite3_module *pModule;
63906  int res;
63907  VdbeCursor *pCur;
63908#endif /* local variables moved into u.cj */
63909
63910  u.cj.res = 0;
63911  u.cj.pCur = p->apCsr[pOp->p1];
63912  assert( u.cj.pCur->pVtabCursor );
63913  if( u.cj.pCur->nullRow ){
63914    break;
63915  }
63916  u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
63917  u.cj.pModule = u.cj.pVtab->pModule;
63918  assert( u.cj.pModule->xNext );
63919
63920  /* Invoke the xNext() method of the module. There is no way for the
63921  ** underlying implementation to return an error if one occurs during
63922  ** xNext(). Instead, if an error occurs, true is returned (indicating that
63923  ** data is available) and the error code returned when xColumn or
63924  ** some other method is next invoked on the save virtual table cursor.
63925  */
63926  p->inVtabMethod = 1;
63927  rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
63928  p->inVtabMethod = 0;
63929  sqlite3DbFree(db, p->zErrMsg);
63930  p->zErrMsg = u.cj.pVtab->zErrMsg;
63931  u.cj.pVtab->zErrMsg = 0;
63932  if( rc==SQLITE_OK ){
63933    u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
63934  }
63935
63936  if( !u.cj.res ){
63937    /* If there is data, jump to P2 */
63938    pc = pOp->p2 - 1;
63939  }
63940  break;
63941}
63942#endif /* SQLITE_OMIT_VIRTUALTABLE */
63943
63944#ifndef SQLITE_OMIT_VIRTUALTABLE
63945/* Opcode: VRename P1 * * P4 *
63946**
63947** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
63948** This opcode invokes the corresponding xRename method. The value
63949** in register P1 is passed as the zName argument to the xRename method.
63950*/
63951case OP_VRename: {
63952#if 0  /* local variables moved into u.ck */
63953  sqlite3_vtab *pVtab;
63954  Mem *pName;
63955#endif /* local variables moved into u.ck */
63956
63957  u.ck.pVtab = pOp->p4.pVtab->pVtab;
63958  u.ck.pName = &aMem[pOp->p1];
63959  assert( u.ck.pVtab->pModule->xRename );
63960  REGISTER_TRACE(pOp->p1, u.ck.pName);
63961  assert( u.ck.pName->flags & MEM_Str );
63962  rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
63963  sqlite3DbFree(db, p->zErrMsg);
63964  p->zErrMsg = u.ck.pVtab->zErrMsg;
63965  u.ck.pVtab->zErrMsg = 0;
63966
63967  break;
63968}
63969#endif
63970
63971#ifndef SQLITE_OMIT_VIRTUALTABLE
63972/* Opcode: VUpdate P1 P2 P3 P4 *
63973**
63974** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
63975** This opcode invokes the corresponding xUpdate method. P2 values
63976** are contiguous memory cells starting at P3 to pass to the xUpdate
63977** invocation. The value in register (P3+P2-1) corresponds to the
63978** p2th element of the argv array passed to xUpdate.
63979**
63980** The xUpdate method will do a DELETE or an INSERT or both.
63981** The argv[0] element (which corresponds to memory cell P3)
63982** is the rowid of a row to delete.  If argv[0] is NULL then no
63983** deletion occurs.  The argv[1] element is the rowid of the new
63984** row.  This can be NULL to have the virtual table select the new
63985** rowid for itself.  The subsequent elements in the array are
63986** the values of columns in the new row.
63987**
63988** If P2==1 then no insert is performed.  argv[0] is the rowid of
63989** a row to delete.
63990**
63991** P1 is a boolean flag. If it is set to true and the xUpdate call
63992** is successful, then the value returned by sqlite3_last_insert_rowid()
63993** is set to the value of the rowid for the row just inserted.
63994*/
63995case OP_VUpdate: {
63996#if 0  /* local variables moved into u.cl */
63997  sqlite3_vtab *pVtab;
63998  sqlite3_module *pModule;
63999  int nArg;
64000  int i;
64001  sqlite_int64 rowid;
64002  Mem **apArg;
64003  Mem *pX;
64004#endif /* local variables moved into u.cl */
64005
64006  u.cl.pVtab = pOp->p4.pVtab->pVtab;
64007  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
64008  u.cl.nArg = pOp->p2;
64009  assert( pOp->p4type==P4_VTAB );
64010  if( ALWAYS(u.cl.pModule->xUpdate) ){
64011    u.cl.apArg = p->apArg;
64012    u.cl.pX = &aMem[pOp->p3];
64013    for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
64014      sqlite3VdbeMemStoreType(u.cl.pX);
64015      u.cl.apArg[u.cl.i] = u.cl.pX;
64016      u.cl.pX++;
64017    }
64018    rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
64019    sqlite3DbFree(db, p->zErrMsg);
64020    p->zErrMsg = u.cl.pVtab->zErrMsg;
64021    u.cl.pVtab->zErrMsg = 0;
64022    if( rc==SQLITE_OK && pOp->p1 ){
64023      assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
64024      db->lastRowid = u.cl.rowid;
64025    }
64026    p->nChange++;
64027  }
64028  break;
64029}
64030#endif /* SQLITE_OMIT_VIRTUALTABLE */
64031
64032#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
64033/* Opcode: Pagecount P1 P2 * * *
64034**
64035** Write the current number of pages in database P1 to memory cell P2.
64036*/
64037case OP_Pagecount: {            /* out2-prerelease */
64038  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
64039  break;
64040}
64041#endif
64042
64043#ifndef SQLITE_OMIT_TRACE
64044/* Opcode: Trace * * * P4 *
64045**
64046** If tracing is enabled (by the sqlite3_trace()) interface, then
64047** the UTF-8 string contained in P4 is emitted on the trace callback.
64048*/
64049case OP_Trace: {
64050#if 0  /* local variables moved into u.cm */
64051  char *zTrace;
64052#endif /* local variables moved into u.cm */
64053
64054  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
64055  if( u.cm.zTrace ){
64056    if( db->xTrace ){
64057      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
64058      db->xTrace(db->pTraceArg, z);
64059      sqlite3DbFree(db, z);
64060    }
64061#ifdef SQLITE_DEBUG
64062    if( (db->flags & SQLITE_SqlTrace)!=0 ){
64063      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
64064    }
64065#endif /* SQLITE_DEBUG */
64066  }
64067  break;
64068}
64069#endif
64070
64071
64072/* Opcode: Noop * * * * *
64073**
64074** Do nothing.  This instruction is often useful as a jump
64075** destination.
64076*/
64077/*
64078** The magic Explain opcode are only inserted when explain==2 (which
64079** is to say when the EXPLAIN QUERY PLAN syntax is used.)
64080** This opcode records information from the optimizer.  It is the
64081** the same as a no-op.  This opcodesnever appears in a real VM program.
64082*/
64083default: {          /* This is really OP_Noop and OP_Explain */
64084  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
64085  break;
64086}
64087
64088/*****************************************************************************
64089** The cases of the switch statement above this line should all be indented
64090** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
64091** readability.  From this point on down, the normal indentation rules are
64092** restored.
64093*****************************************************************************/
64094    }
64095
64096#ifdef VDBE_PROFILE
64097    {
64098      u64 elapsed = sqlite3Hwtime() - start;
64099      pOp->cycles += elapsed;
64100      pOp->cnt++;
64101#if 0
64102        fprintf(stdout, "%10llu ", elapsed);
64103        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
64104#endif
64105    }
64106#endif
64107
64108    /* The following code adds nothing to the actual functionality
64109    ** of the program.  It is only here for testing and debugging.
64110    ** On the other hand, it does burn CPU cycles every time through
64111    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
64112    */
64113#ifndef NDEBUG
64114    assert( pc>=-1 && pc<p->nOp );
64115
64116#ifdef SQLITE_DEBUG
64117    if( p->trace ){
64118      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
64119      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
64120        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
64121      }
64122      if( pOp->opflags & OPFLG_OUT3 ){
64123        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
64124      }
64125    }
64126#endif  /* SQLITE_DEBUG */
64127#endif  /* NDEBUG */
64128  }  /* The end of the for(;;) loop the loops through opcodes */
64129
64130  /* If we reach this point, it means that execution is finished with
64131  ** an error of some kind.
64132  */
64133vdbe_error_halt:
64134  assert( rc );
64135  p->rc = rc;
64136  testcase( sqlite3GlobalConfig.xLog!=0 );
64137  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
64138                   pc, p->zSql, p->zErrMsg);
64139  sqlite3VdbeHalt(p);
64140  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
64141  rc = SQLITE_ERROR;
64142  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
64143
64144  /* This is the only way out of this procedure.  We have to
64145  ** release the mutexes on btrees that were acquired at the
64146  ** top. */
64147vdbe_return:
64148  sqlite3BtreeMutexArrayLeave(&p->aMutex);
64149  return rc;
64150
64151  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
64152  ** is encountered.
64153  */
64154too_big:
64155  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
64156  rc = SQLITE_TOOBIG;
64157  goto vdbe_error_halt;
64158
64159  /* Jump to here if a malloc() fails.
64160  */
64161no_mem:
64162  db->mallocFailed = 1;
64163  sqlite3SetString(&p->zErrMsg, db, "out of memory");
64164  rc = SQLITE_NOMEM;
64165  goto vdbe_error_halt;
64166
64167  /* Jump to here for any other kind of fatal error.  The "rc" variable
64168  ** should hold the error number.
64169  */
64170abort_due_to_error:
64171  assert( p->zErrMsg==0 );
64172  if( db->mallocFailed ) rc = SQLITE_NOMEM;
64173  if( rc!=SQLITE_IOERR_NOMEM ){
64174    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64175  }
64176  goto vdbe_error_halt;
64177
64178  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
64179  ** flag.
64180  */
64181abort_due_to_interrupt:
64182  assert( db->u1.isInterrupted );
64183  rc = SQLITE_INTERRUPT;
64184  p->rc = rc;
64185  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64186  goto vdbe_error_halt;
64187}
64188
64189/************** End of vdbe.c ************************************************/
64190/************** Begin file vdbeblob.c ****************************************/
64191/*
64192** 2007 May 1
64193**
64194** The author disclaims copyright to this source code.  In place of
64195** a legal notice, here is a blessing:
64196**
64197**    May you do good and not evil.
64198**    May you find forgiveness for yourself and forgive others.
64199**    May you share freely, never taking more than you give.
64200**
64201*************************************************************************
64202**
64203** This file contains code used to implement incremental BLOB I/O.
64204*/
64205
64206
64207#ifndef SQLITE_OMIT_INCRBLOB
64208
64209/*
64210** Valid sqlite3_blob* handles point to Incrblob structures.
64211*/
64212typedef struct Incrblob Incrblob;
64213struct Incrblob {
64214  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
64215  int nByte;              /* Size of open blob, in bytes */
64216  int iOffset;            /* Byte offset of blob in cursor data */
64217  BtCursor *pCsr;         /* Cursor pointing at blob row */
64218  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
64219  sqlite3 *db;            /* The associated database */
64220};
64221
64222/*
64223** Open a blob handle.
64224*/
64225SQLITE_API int sqlite3_blob_open(
64226  sqlite3* db,            /* The database connection */
64227  const char *zDb,        /* The attached database containing the blob */
64228  const char *zTable,     /* The table containing the blob */
64229  const char *zColumn,    /* The column containing the blob */
64230  sqlite_int64 iRow,      /* The row containing the glob */
64231  int flags,              /* True -> read/write access, false -> read-only */
64232  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
64233){
64234  int nAttempt = 0;
64235  int iCol;               /* Index of zColumn in row-record */
64236
64237  /* This VDBE program seeks a btree cursor to the identified
64238  ** db/table/row entry. The reason for using a vdbe program instead
64239  ** of writing code to use the b-tree layer directly is that the
64240  ** vdbe program will take advantage of the various transaction,
64241  ** locking and error handling infrastructure built into the vdbe.
64242  **
64243  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
64244  ** Code external to the Vdbe then "borrows" the b-tree cursor and
64245  ** uses it to implement the blob_read(), blob_write() and
64246  ** blob_bytes() functions.
64247  **
64248  ** The sqlite3_blob_close() function finalizes the vdbe program,
64249  ** which closes the b-tree cursor and (possibly) commits the
64250  ** transaction.
64251  */
64252  static const VdbeOpList openBlob[] = {
64253    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
64254    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
64255    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
64256
64257    /* One of the following two instructions is replaced by an OP_Noop. */
64258    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
64259    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
64260
64261    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
64262    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
64263    {OP_Column, 0, 0, 1},          /* 7  */
64264    {OP_ResultRow, 1, 0, 0},       /* 8  */
64265    {OP_Close, 0, 0, 0},           /* 9  */
64266    {OP_Halt, 0, 0, 0},            /* 10 */
64267  };
64268
64269  Vdbe *v = 0;
64270  int rc = SQLITE_OK;
64271  char *zErr = 0;
64272  Table *pTab;
64273  Parse *pParse;
64274
64275  *ppBlob = 0;
64276  sqlite3_mutex_enter(db->mutex);
64277  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
64278  if( pParse==0 ){
64279    rc = SQLITE_NOMEM;
64280    goto blob_open_out;
64281  }
64282  do {
64283    memset(pParse, 0, sizeof(Parse));
64284    pParse->db = db;
64285
64286    sqlite3BtreeEnterAll(db);
64287    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
64288    if( pTab && IsVirtual(pTab) ){
64289      pTab = 0;
64290      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
64291    }
64292#ifndef SQLITE_OMIT_VIEW
64293    if( pTab && pTab->pSelect ){
64294      pTab = 0;
64295      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
64296    }
64297#endif
64298    if( !pTab ){
64299      if( pParse->zErrMsg ){
64300        sqlite3DbFree(db, zErr);
64301        zErr = pParse->zErrMsg;
64302        pParse->zErrMsg = 0;
64303      }
64304      rc = SQLITE_ERROR;
64305      sqlite3BtreeLeaveAll(db);
64306      goto blob_open_out;
64307    }
64308
64309    /* Now search pTab for the exact column. */
64310    for(iCol=0; iCol < pTab->nCol; iCol++) {
64311      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
64312        break;
64313      }
64314    }
64315    if( iCol==pTab->nCol ){
64316      sqlite3DbFree(db, zErr);
64317      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
64318      rc = SQLITE_ERROR;
64319      sqlite3BtreeLeaveAll(db);
64320      goto blob_open_out;
64321    }
64322
64323    /* If the value is being opened for writing, check that the
64324    ** column is not indexed, and that it is not part of a foreign key.
64325    ** It is against the rules to open a column to which either of these
64326    ** descriptions applies for writing.  */
64327    if( flags ){
64328      const char *zFault = 0;
64329      Index *pIdx;
64330#ifndef SQLITE_OMIT_FOREIGN_KEY
64331      if( db->flags&SQLITE_ForeignKeys ){
64332        /* Check that the column is not part of an FK child key definition. It
64333        ** is not necessary to check if it is part of a parent key, as parent
64334        ** key columns must be indexed. The check below will pick up this
64335        ** case.  */
64336        FKey *pFKey;
64337        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
64338          int j;
64339          for(j=0; j<pFKey->nCol; j++){
64340            if( pFKey->aCol[j].iFrom==iCol ){
64341              zFault = "foreign key";
64342            }
64343          }
64344        }
64345      }
64346#endif
64347      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64348        int j;
64349        for(j=0; j<pIdx->nColumn; j++){
64350          if( pIdx->aiColumn[j]==iCol ){
64351            zFault = "indexed";
64352          }
64353        }
64354      }
64355      if( zFault ){
64356        sqlite3DbFree(db, zErr);
64357        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
64358        rc = SQLITE_ERROR;
64359        sqlite3BtreeLeaveAll(db);
64360        goto blob_open_out;
64361      }
64362    }
64363
64364    v = sqlite3VdbeCreate(db);
64365    if( v ){
64366      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64367      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
64368      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
64369
64370      /* Configure the OP_Transaction */
64371      sqlite3VdbeChangeP1(v, 0, iDb);
64372      sqlite3VdbeChangeP2(v, 0, flags);
64373
64374      /* Configure the OP_VerifyCookie */
64375      sqlite3VdbeChangeP1(v, 1, iDb);
64376      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
64377
64378      /* Make sure a mutex is held on the table to be accessed */
64379      sqlite3VdbeUsesBtree(v, iDb);
64380
64381      /* Configure the OP_TableLock instruction */
64382#ifdef SQLITE_OMIT_SHARED_CACHE
64383      sqlite3VdbeChangeToNoop(v, 2, 1);
64384#else
64385      sqlite3VdbeChangeP1(v, 2, iDb);
64386      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
64387      sqlite3VdbeChangeP3(v, 2, flags);
64388      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
64389#endif
64390
64391      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
64392      ** parameter of the other to pTab->tnum.  */
64393      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
64394      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
64395      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
64396
64397      /* Configure the number of columns. Configure the cursor to
64398      ** think that the table has one more column than it really
64399      ** does. An OP_Column to retrieve this imaginary column will
64400      ** always return an SQL NULL. This is useful because it means
64401      ** we can invoke OP_Column to fill in the vdbe cursors type
64402      ** and offset cache without causing any IO.
64403      */
64404      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
64405      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
64406      if( !db->mallocFailed ){
64407        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
64408      }
64409    }
64410
64411    sqlite3BtreeLeaveAll(db);
64412    if( db->mallocFailed ){
64413      goto blob_open_out;
64414    }
64415
64416    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
64417    rc = sqlite3_step((sqlite3_stmt *)v);
64418    if( rc!=SQLITE_ROW ){
64419      nAttempt++;
64420      rc = sqlite3_finalize((sqlite3_stmt *)v);
64421      sqlite3DbFree(db, zErr);
64422      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
64423      v = 0;
64424    }
64425  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
64426
64427  if( rc==SQLITE_ROW ){
64428    /* The row-record has been opened successfully. Check that the
64429    ** column in question contains text or a blob. If it contains
64430    ** text, it is up to the caller to get the encoding right.
64431    */
64432    Incrblob *pBlob;
64433    u32 type = v->apCsr[0]->aType[iCol];
64434
64435    if( type<12 ){
64436      sqlite3DbFree(db, zErr);
64437      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
64438          type==0?"null": type==7?"real": "integer"
64439      );
64440      rc = SQLITE_ERROR;
64441      goto blob_open_out;
64442    }
64443    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
64444    if( db->mallocFailed ){
64445      sqlite3DbFree(db, pBlob);
64446      goto blob_open_out;
64447    }
64448    pBlob->flags = flags;
64449    pBlob->pCsr =  v->apCsr[0]->pCursor;
64450    sqlite3BtreeEnterCursor(pBlob->pCsr);
64451    sqlite3BtreeCacheOverflow(pBlob->pCsr);
64452    sqlite3BtreeLeaveCursor(pBlob->pCsr);
64453    pBlob->pStmt = (sqlite3_stmt *)v;
64454    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
64455    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
64456    pBlob->db = db;
64457    *ppBlob = (sqlite3_blob *)pBlob;
64458    rc = SQLITE_OK;
64459  }else if( rc==SQLITE_OK ){
64460    sqlite3DbFree(db, zErr);
64461    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
64462    rc = SQLITE_ERROR;
64463  }
64464
64465blob_open_out:
64466  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
64467    sqlite3VdbeFinalize(v);
64468  }
64469  sqlite3Error(db, rc, zErr);
64470  sqlite3DbFree(db, zErr);
64471  sqlite3StackFree(db, pParse);
64472  rc = sqlite3ApiExit(db, rc);
64473  sqlite3_mutex_leave(db->mutex);
64474  return rc;
64475}
64476
64477/*
64478** Close a blob handle that was previously created using
64479** sqlite3_blob_open().
64480*/
64481SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
64482  Incrblob *p = (Incrblob *)pBlob;
64483  int rc;
64484  sqlite3 *db;
64485
64486  if( p ){
64487    db = p->db;
64488    sqlite3_mutex_enter(db->mutex);
64489    rc = sqlite3_finalize(p->pStmt);
64490    sqlite3DbFree(db, p);
64491    sqlite3_mutex_leave(db->mutex);
64492  }else{
64493    rc = SQLITE_OK;
64494  }
64495  return rc;
64496}
64497
64498/*
64499** Perform a read or write operation on a blob
64500*/
64501static int blobReadWrite(
64502  sqlite3_blob *pBlob,
64503  void *z,
64504  int n,
64505  int iOffset,
64506  int (*xCall)(BtCursor*, u32, u32, void*)
64507){
64508  int rc;
64509  Incrblob *p = (Incrblob *)pBlob;
64510  Vdbe *v;
64511  sqlite3 *db;
64512
64513  if( p==0 ) return SQLITE_MISUSE_BKPT;
64514  db = p->db;
64515  sqlite3_mutex_enter(db->mutex);
64516  v = (Vdbe*)p->pStmt;
64517
64518  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
64519    /* Request is out of range. Return a transient error. */
64520    rc = SQLITE_ERROR;
64521    sqlite3Error(db, SQLITE_ERROR, 0);
64522  } else if( v==0 ){
64523    /* If there is no statement handle, then the blob-handle has
64524    ** already been invalidated. Return SQLITE_ABORT in this case.
64525    */
64526    rc = SQLITE_ABORT;
64527  }else{
64528    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
64529    ** returned, clean-up the statement handle.
64530    */
64531    assert( db == v->db );
64532    sqlite3BtreeEnterCursor(p->pCsr);
64533    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
64534    sqlite3BtreeLeaveCursor(p->pCsr);
64535    if( rc==SQLITE_ABORT ){
64536      sqlite3VdbeFinalize(v);
64537      p->pStmt = 0;
64538    }else{
64539      db->errCode = rc;
64540      v->rc = rc;
64541    }
64542  }
64543  rc = sqlite3ApiExit(db, rc);
64544  sqlite3_mutex_leave(db->mutex);
64545  return rc;
64546}
64547
64548/*
64549** Read data from a blob handle.
64550*/
64551SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
64552  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
64553}
64554
64555/*
64556** Write data to a blob handle.
64557*/
64558SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
64559  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
64560}
64561
64562/*
64563** Query a blob handle for the size of the data.
64564**
64565** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
64566** so no mutex is required for access.
64567*/
64568SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
64569  Incrblob *p = (Incrblob *)pBlob;
64570  return p ? p->nByte : 0;
64571}
64572
64573#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
64574
64575/************** End of vdbeblob.c ********************************************/
64576/************** Begin file journal.c *****************************************/
64577/*
64578** 2007 August 22
64579**
64580** The author disclaims copyright to this source code.  In place of
64581** a legal notice, here is a blessing:
64582**
64583**    May you do good and not evil.
64584**    May you find forgiveness for yourself and forgive others.
64585**    May you share freely, never taking more than you give.
64586**
64587*************************************************************************
64588**
64589** This file implements a special kind of sqlite3_file object used
64590** by SQLite to create journal files if the atomic-write optimization
64591** is enabled.
64592**
64593** The distinctive characteristic of this sqlite3_file is that the
64594** actual on disk file is created lazily. When the file is created,
64595** the caller specifies a buffer size for an in-memory buffer to
64596** be used to service read() and write() requests. The actual file
64597** on disk is not created or populated until either:
64598**
64599**   1) The in-memory representation grows too large for the allocated
64600**      buffer, or
64601**   2) The sqlite3JournalCreate() function is called.
64602*/
64603#ifdef SQLITE_ENABLE_ATOMIC_WRITE
64604
64605
64606/*
64607** A JournalFile object is a subclass of sqlite3_file used by
64608** as an open file handle for journal files.
64609*/
64610struct JournalFile {
64611  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
64612  int nBuf;                       /* Size of zBuf[] in bytes */
64613  char *zBuf;                     /* Space to buffer journal writes */
64614  int iSize;                      /* Amount of zBuf[] currently used */
64615  int flags;                      /* xOpen flags */
64616  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
64617  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
64618  const char *zJournal;           /* Name of the journal file */
64619};
64620typedef struct JournalFile JournalFile;
64621
64622/*
64623** If it does not already exists, create and populate the on-disk file
64624** for JournalFile p.
64625*/
64626static int createFile(JournalFile *p){
64627  int rc = SQLITE_OK;
64628  if( !p->pReal ){
64629    sqlite3_file *pReal = (sqlite3_file *)&p[1];
64630    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
64631    if( rc==SQLITE_OK ){
64632      p->pReal = pReal;
64633      if( p->iSize>0 ){
64634        assert(p->iSize<=p->nBuf);
64635        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
64636      }
64637    }
64638  }
64639  return rc;
64640}
64641
64642/*
64643** Close the file.
64644*/
64645static int jrnlClose(sqlite3_file *pJfd){
64646  JournalFile *p = (JournalFile *)pJfd;
64647  if( p->pReal ){
64648    sqlite3OsClose(p->pReal);
64649  }
64650  sqlite3_free(p->zBuf);
64651  return SQLITE_OK;
64652}
64653
64654/*
64655** Read data from the file.
64656*/
64657static int jrnlRead(
64658  sqlite3_file *pJfd,    /* The journal file from which to read */
64659  void *zBuf,            /* Put the results here */
64660  int iAmt,              /* Number of bytes to read */
64661  sqlite_int64 iOfst     /* Begin reading at this offset */
64662){
64663  int rc = SQLITE_OK;
64664  JournalFile *p = (JournalFile *)pJfd;
64665  if( p->pReal ){
64666    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
64667  }else if( (iAmt+iOfst)>p->iSize ){
64668    rc = SQLITE_IOERR_SHORT_READ;
64669  }else{
64670    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
64671  }
64672  return rc;
64673}
64674
64675/*
64676** Write data to the file.
64677*/
64678static int jrnlWrite(
64679  sqlite3_file *pJfd,    /* The journal file into which to write */
64680  const void *zBuf,      /* Take data to be written from here */
64681  int iAmt,              /* Number of bytes to write */
64682  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
64683){
64684  int rc = SQLITE_OK;
64685  JournalFile *p = (JournalFile *)pJfd;
64686  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
64687    rc = createFile(p);
64688  }
64689  if( rc==SQLITE_OK ){
64690    if( p->pReal ){
64691      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
64692    }else{
64693      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
64694      if( p->iSize<(iOfst+iAmt) ){
64695        p->iSize = (iOfst+iAmt);
64696      }
64697    }
64698  }
64699  return rc;
64700}
64701
64702/*
64703** Truncate the file.
64704*/
64705static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
64706  int rc = SQLITE_OK;
64707  JournalFile *p = (JournalFile *)pJfd;
64708  if( p->pReal ){
64709    rc = sqlite3OsTruncate(p->pReal, size);
64710  }else if( size<p->iSize ){
64711    p->iSize = size;
64712  }
64713  return rc;
64714}
64715
64716/*
64717** Sync the file.
64718*/
64719static int jrnlSync(sqlite3_file *pJfd, int flags){
64720  int rc;
64721  JournalFile *p = (JournalFile *)pJfd;
64722  if( p->pReal ){
64723    rc = sqlite3OsSync(p->pReal, flags);
64724  }else{
64725    rc = SQLITE_OK;
64726  }
64727  return rc;
64728}
64729
64730/*
64731** Query the size of the file in bytes.
64732*/
64733static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
64734  int rc = SQLITE_OK;
64735  JournalFile *p = (JournalFile *)pJfd;
64736  if( p->pReal ){
64737    rc = sqlite3OsFileSize(p->pReal, pSize);
64738  }else{
64739    *pSize = (sqlite_int64) p->iSize;
64740  }
64741  return rc;
64742}
64743
64744/*
64745** Table of methods for JournalFile sqlite3_file object.
64746*/
64747static struct sqlite3_io_methods JournalFileMethods = {
64748  1,             /* iVersion */
64749  jrnlClose,     /* xClose */
64750  jrnlRead,      /* xRead */
64751  jrnlWrite,     /* xWrite */
64752  jrnlTruncate,  /* xTruncate */
64753  jrnlSync,      /* xSync */
64754  jrnlFileSize,  /* xFileSize */
64755  0,             /* xLock */
64756  0,             /* xUnlock */
64757  0,             /* xCheckReservedLock */
64758  0,             /* xFileControl */
64759  0,             /* xSectorSize */
64760  0              /* xDeviceCharacteristics */
64761};
64762
64763/*
64764** Open a journal file.
64765*/
64766SQLITE_PRIVATE int sqlite3JournalOpen(
64767  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
64768  const char *zName,         /* Name of the journal file */
64769  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
64770  int flags,                 /* Opening flags */
64771  int nBuf                   /* Bytes buffered before opening the file */
64772){
64773  JournalFile *p = (JournalFile *)pJfd;
64774  memset(p, 0, sqlite3JournalSize(pVfs));
64775  if( nBuf>0 ){
64776    p->zBuf = sqlite3MallocZero(nBuf);
64777    if( !p->zBuf ){
64778      return SQLITE_NOMEM;
64779    }
64780  }else{
64781    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
64782  }
64783  p->pMethod = &JournalFileMethods;
64784  p->nBuf = nBuf;
64785  p->flags = flags;
64786  p->zJournal = zName;
64787  p->pVfs = pVfs;
64788  return SQLITE_OK;
64789}
64790
64791/*
64792** If the argument p points to a JournalFile structure, and the underlying
64793** file has not yet been created, create it now.
64794*/
64795SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
64796  if( p->pMethods!=&JournalFileMethods ){
64797    return SQLITE_OK;
64798  }
64799  return createFile((JournalFile *)p);
64800}
64801
64802/*
64803** Return the number of bytes required to store a JournalFile that uses vfs
64804** pVfs to create the underlying on-disk files.
64805*/
64806SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
64807  return (pVfs->szOsFile+sizeof(JournalFile));
64808}
64809#endif
64810
64811/************** End of journal.c *********************************************/
64812/************** Begin file memjournal.c **************************************/
64813/*
64814** 2008 October 7
64815**
64816** The author disclaims copyright to this source code.  In place of
64817** a legal notice, here is a blessing:
64818**
64819**    May you do good and not evil.
64820**    May you find forgiveness for yourself and forgive others.
64821**    May you share freely, never taking more than you give.
64822**
64823*************************************************************************
64824**
64825** This file contains code use to implement an in-memory rollback journal.
64826** The in-memory rollback journal is used to journal transactions for
64827** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
64828*/
64829
64830/* Forward references to internal structures */
64831typedef struct MemJournal MemJournal;
64832typedef struct FilePoint FilePoint;
64833typedef struct FileChunk FileChunk;
64834
64835/* Space to hold the rollback journal is allocated in increments of
64836** this many bytes.
64837**
64838** The size chosen is a little less than a power of two.  That way,
64839** the FileChunk object will have a size that almost exactly fills
64840** a power-of-two allocation.  This mimimizes wasted space in power-of-two
64841** memory allocators.
64842*/
64843#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
64844
64845/* Macro to find the minimum of two numeric values.
64846*/
64847#ifndef MIN
64848# define MIN(x,y) ((x)<(y)?(x):(y))
64849#endif
64850
64851/*
64852** The rollback journal is composed of a linked list of these structures.
64853*/
64854struct FileChunk {
64855  FileChunk *pNext;               /* Next chunk in the journal */
64856  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
64857};
64858
64859/*
64860** An instance of this object serves as a cursor into the rollback journal.
64861** The cursor can be either for reading or writing.
64862*/
64863struct FilePoint {
64864  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
64865  FileChunk *pChunk;              /* Specific chunk into which cursor points */
64866};
64867
64868/*
64869** This subclass is a subclass of sqlite3_file.  Each open memory-journal
64870** is an instance of this class.
64871*/
64872struct MemJournal {
64873  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
64874  FileChunk *pFirst;              /* Head of in-memory chunk-list */
64875  FilePoint endpoint;             /* Pointer to the end of the file */
64876  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
64877};
64878
64879/*
64880** Read data from the in-memory journal file.  This is the implementation
64881** of the sqlite3_vfs.xRead method.
64882*/
64883static int memjrnlRead(
64884  sqlite3_file *pJfd,    /* The journal file from which to read */
64885  void *zBuf,            /* Put the results here */
64886  int iAmt,              /* Number of bytes to read */
64887  sqlite_int64 iOfst     /* Begin reading at this offset */
64888){
64889  MemJournal *p = (MemJournal *)pJfd;
64890  u8 *zOut = zBuf;
64891  int nRead = iAmt;
64892  int iChunkOffset;
64893  FileChunk *pChunk;
64894
64895  /* SQLite never tries to read past the end of a rollback journal file */
64896  assert( iOfst+iAmt<=p->endpoint.iOffset );
64897
64898  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
64899    sqlite3_int64 iOff = 0;
64900    for(pChunk=p->pFirst;
64901        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
64902        pChunk=pChunk->pNext
64903    ){
64904      iOff += JOURNAL_CHUNKSIZE;
64905    }
64906  }else{
64907    pChunk = p->readpoint.pChunk;
64908  }
64909
64910  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
64911  do {
64912    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
64913    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
64914    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
64915    zOut += nCopy;
64916    nRead -= iSpace;
64917    iChunkOffset = 0;
64918  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
64919  p->readpoint.iOffset = iOfst+iAmt;
64920  p->readpoint.pChunk = pChunk;
64921
64922  return SQLITE_OK;
64923}
64924
64925/*
64926** Write data to the file.
64927*/
64928static int memjrnlWrite(
64929  sqlite3_file *pJfd,    /* The journal file into which to write */
64930  const void *zBuf,      /* Take data to be written from here */
64931  int iAmt,              /* Number of bytes to write */
64932  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
64933){
64934  MemJournal *p = (MemJournal *)pJfd;
64935  int nWrite = iAmt;
64936  u8 *zWrite = (u8 *)zBuf;
64937
64938  /* An in-memory journal file should only ever be appended to. Random
64939  ** access writes are not required by sqlite.
64940  */
64941  assert( iOfst==p->endpoint.iOffset );
64942  UNUSED_PARAMETER(iOfst);
64943
64944  while( nWrite>0 ){
64945    FileChunk *pChunk = p->endpoint.pChunk;
64946    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
64947    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
64948
64949    if( iChunkOffset==0 ){
64950      /* New chunk is required to extend the file. */
64951      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
64952      if( !pNew ){
64953        return SQLITE_IOERR_NOMEM;
64954      }
64955      pNew->pNext = 0;
64956      if( pChunk ){
64957        assert( p->pFirst );
64958        pChunk->pNext = pNew;
64959      }else{
64960        assert( !p->pFirst );
64961        p->pFirst = pNew;
64962      }
64963      p->endpoint.pChunk = pNew;
64964    }
64965
64966    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
64967    zWrite += iSpace;
64968    nWrite -= iSpace;
64969    p->endpoint.iOffset += iSpace;
64970  }
64971
64972  return SQLITE_OK;
64973}
64974
64975/*
64976** Truncate the file.
64977*/
64978static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
64979  MemJournal *p = (MemJournal *)pJfd;
64980  FileChunk *pChunk;
64981  assert(size==0);
64982  UNUSED_PARAMETER(size);
64983  pChunk = p->pFirst;
64984  while( pChunk ){
64985    FileChunk *pTmp = pChunk;
64986    pChunk = pChunk->pNext;
64987    sqlite3_free(pTmp);
64988  }
64989  sqlite3MemJournalOpen(pJfd);
64990  return SQLITE_OK;
64991}
64992
64993/*
64994** Close the file.
64995*/
64996static int memjrnlClose(sqlite3_file *pJfd){
64997  memjrnlTruncate(pJfd, 0);
64998  return SQLITE_OK;
64999}
65000
65001
65002/*
65003** Sync the file.
65004**
65005** Syncing an in-memory journal is a no-op.  And, in fact, this routine
65006** is never called in a working implementation.  This implementation
65007** exists purely as a contingency, in case some malfunction in some other
65008** part of SQLite causes Sync to be called by mistake.
65009*/
65010static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
65011  UNUSED_PARAMETER2(NotUsed, NotUsed2);
65012  return SQLITE_OK;
65013}
65014
65015/*
65016** Query the size of the file in bytes.
65017*/
65018static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
65019  MemJournal *p = (MemJournal *)pJfd;
65020  *pSize = (sqlite_int64) p->endpoint.iOffset;
65021  return SQLITE_OK;
65022}
65023
65024/*
65025** Table of methods for MemJournal sqlite3_file object.
65026*/
65027static const struct sqlite3_io_methods MemJournalMethods = {
65028  1,                /* iVersion */
65029  memjrnlClose,     /* xClose */
65030  memjrnlRead,      /* xRead */
65031  memjrnlWrite,     /* xWrite */
65032  memjrnlTruncate,  /* xTruncate */
65033  memjrnlSync,      /* xSync */
65034  memjrnlFileSize,  /* xFileSize */
65035  0,                /* xLock */
65036  0,                /* xUnlock */
65037  0,                /* xCheckReservedLock */
65038  0,                /* xFileControl */
65039  0,                /* xSectorSize */
65040  0,                /* xDeviceCharacteristics */
65041  0,                /* xShmOpen */
65042  0,                /* xShmLock */
65043  0,                /* xShmMap */
65044  0,                /* xShmBarrier */
65045  0                 /* xShmClose */
65046};
65047
65048/*
65049** Open a journal file.
65050*/
65051SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
65052  MemJournal *p = (MemJournal *)pJfd;
65053  assert( EIGHT_BYTE_ALIGNMENT(p) );
65054  memset(p, 0, sqlite3MemJournalSize());
65055  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
65056}
65057
65058/*
65059** Return true if the file-handle passed as an argument is
65060** an in-memory journal
65061*/
65062SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
65063  return pJfd->pMethods==&MemJournalMethods;
65064}
65065
65066/*
65067** Return the number of bytes required to store a MemJournal that uses vfs
65068** pVfs to create the underlying on-disk files.
65069*/
65070SQLITE_PRIVATE int sqlite3MemJournalSize(void){
65071  return sizeof(MemJournal);
65072}
65073
65074/************** End of memjournal.c ******************************************/
65075/************** Begin file walker.c ******************************************/
65076/*
65077** 2008 August 16
65078**
65079** The author disclaims copyright to this source code.  In place of
65080** a legal notice, here is a blessing:
65081**
65082**    May you do good and not evil.
65083**    May you find forgiveness for yourself and forgive others.
65084**    May you share freely, never taking more than you give.
65085**
65086*************************************************************************
65087** This file contains routines used for walking the parser tree for
65088** an SQL statement.
65089*/
65090
65091
65092/*
65093** Walk an expression tree.  Invoke the callback once for each node
65094** of the expression, while decending.  (In other words, the callback
65095** is invoked before visiting children.)
65096**
65097** The return value from the callback should be one of the WRC_*
65098** constants to specify how to proceed with the walk.
65099**
65100**    WRC_Continue      Continue descending down the tree.
65101**
65102**    WRC_Prune         Do not descend into child nodes.  But allow
65103**                      the walk to continue with sibling nodes.
65104**
65105**    WRC_Abort         Do no more callbacks.  Unwind the stack and
65106**                      return the top-level walk call.
65107**
65108** The return value from this routine is WRC_Abort to abandon the tree walk
65109** and WRC_Continue to continue.
65110*/
65111SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
65112  int rc;
65113  if( pExpr==0 ) return WRC_Continue;
65114  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
65115  testcase( ExprHasProperty(pExpr, EP_Reduced) );
65116  rc = pWalker->xExprCallback(pWalker, pExpr);
65117  if( rc==WRC_Continue
65118              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
65119    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
65120    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
65121    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65122      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
65123    }else{
65124      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
65125    }
65126  }
65127  return rc & WRC_Abort;
65128}
65129
65130/*
65131** Call sqlite3WalkExpr() for every expression in list p or until
65132** an abort request is seen.
65133*/
65134SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
65135  int i;
65136  struct ExprList_item *pItem;
65137  if( p ){
65138    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
65139      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
65140    }
65141  }
65142  return WRC_Continue;
65143}
65144
65145/*
65146** Walk all expressions associated with SELECT statement p.  Do
65147** not invoke the SELECT callback on p, but do (of course) invoke
65148** any expr callbacks and SELECT callbacks that come from subqueries.
65149** Return WRC_Abort or WRC_Continue.
65150*/
65151SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
65152  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
65153  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
65154  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
65155  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
65156  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
65157  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
65158  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
65159  return WRC_Continue;
65160}
65161
65162/*
65163** Walk the parse trees associated with all subqueries in the
65164** FROM clause of SELECT statement p.  Do not invoke the select
65165** callback on p, but do invoke it on each FROM clause subquery
65166** and on any subqueries further down in the tree.  Return
65167** WRC_Abort or WRC_Continue;
65168*/
65169SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
65170  SrcList *pSrc;
65171  int i;
65172  struct SrcList_item *pItem;
65173
65174  pSrc = p->pSrc;
65175  if( ALWAYS(pSrc) ){
65176    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
65177      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
65178        return WRC_Abort;
65179      }
65180    }
65181  }
65182  return WRC_Continue;
65183}
65184
65185/*
65186** Call sqlite3WalkExpr() for every expression in Select statement p.
65187** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
65188** on the compound select chain, p->pPrior.
65189**
65190** Return WRC_Continue under normal conditions.  Return WRC_Abort if
65191** there is an abort request.
65192**
65193** If the Walker does not have an xSelectCallback() then this routine
65194** is a no-op returning WRC_Continue.
65195*/
65196SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
65197  int rc;
65198  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
65199  rc = WRC_Continue;
65200  while( p  ){
65201    rc = pWalker->xSelectCallback(pWalker, p);
65202    if( rc ) break;
65203    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
65204    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
65205    p = p->pPrior;
65206  }
65207  return rc & WRC_Abort;
65208}
65209
65210/************** End of walker.c **********************************************/
65211/************** Begin file resolve.c *****************************************/
65212/*
65213** 2008 August 18
65214**
65215** The author disclaims copyright to this source code.  In place of
65216** a legal notice, here is a blessing:
65217**
65218**    May you do good and not evil.
65219**    May you find forgiveness for yourself and forgive others.
65220**    May you share freely, never taking more than you give.
65221**
65222*************************************************************************
65223**
65224** This file contains routines used for walking the parser tree and
65225** resolve all identifiers by associating them with a particular
65226** table and column.
65227*/
65228
65229/*
65230** Turn the pExpr expression into an alias for the iCol-th column of the
65231** result set in pEList.
65232**
65233** If the result set column is a simple column reference, then this routine
65234** makes an exact copy.  But for any other kind of expression, this
65235** routine make a copy of the result set column as the argument to the
65236** TK_AS operator.  The TK_AS operator causes the expression to be
65237** evaluated just once and then reused for each alias.
65238**
65239** The reason for suppressing the TK_AS term when the expression is a simple
65240** column reference is so that the column reference will be recognized as
65241** usable by indices within the WHERE clause processing logic.
65242**
65243** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
65244** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
65245**
65246**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
65247**
65248** Is equivalent to:
65249**
65250**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
65251**
65252** The result of random()%5 in the GROUP BY clause is probably different
65253** from the result in the result-set.  We might fix this someday.  Or
65254** then again, we might not...
65255*/
65256static void resolveAlias(
65257  Parse *pParse,         /* Parsing context */
65258  ExprList *pEList,      /* A result set */
65259  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
65260  Expr *pExpr,           /* Transform this into an alias to the result set */
65261  const char *zType      /* "GROUP" or "ORDER" or "" */
65262){
65263  Expr *pOrig;           /* The iCol-th column of the result set */
65264  Expr *pDup;            /* Copy of pOrig */
65265  sqlite3 *db;           /* The database connection */
65266
65267  assert( iCol>=0 && iCol<pEList->nExpr );
65268  pOrig = pEList->a[iCol].pExpr;
65269  assert( pOrig!=0 );
65270  assert( pOrig->flags & EP_Resolved );
65271  db = pParse->db;
65272  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
65273    pDup = sqlite3ExprDup(db, pOrig, 0);
65274    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
65275    if( pDup==0 ) return;
65276    if( pEList->a[iCol].iAlias==0 ){
65277      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
65278    }
65279    pDup->iTable = pEList->a[iCol].iAlias;
65280  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
65281    pDup = sqlite3ExprDup(db, pOrig, 0);
65282    if( pDup==0 ) return;
65283  }else{
65284    char *zToken = pOrig->u.zToken;
65285    assert( zToken!=0 );
65286    pOrig->u.zToken = 0;
65287    pDup = sqlite3ExprDup(db, pOrig, 0);
65288    pOrig->u.zToken = zToken;
65289    if( pDup==0 ) return;
65290    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
65291    pDup->flags2 |= EP2_MallocedToken;
65292    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
65293  }
65294  if( pExpr->flags & EP_ExpCollate ){
65295    pDup->pColl = pExpr->pColl;
65296    pDup->flags |= EP_ExpCollate;
65297  }
65298
65299  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
65300  ** prevents ExprDelete() from deleting the Expr structure itself,
65301  ** allowing it to be repopulated by the memcpy() on the following line.
65302  */
65303  ExprSetProperty(pExpr, EP_Static);
65304  sqlite3ExprDelete(db, pExpr);
65305  memcpy(pExpr, pDup, sizeof(*pExpr));
65306  sqlite3DbFree(db, pDup);
65307}
65308
65309/*
65310** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
65311** that name in the set of source tables in pSrcList and make the pExpr
65312** expression node refer back to that source column.  The following changes
65313** are made to pExpr:
65314**
65315**    pExpr->iDb           Set the index in db->aDb[] of the database X
65316**                         (even if X is implied).
65317**    pExpr->iTable        Set to the cursor number for the table obtained
65318**                         from pSrcList.
65319**    pExpr->pTab          Points to the Table structure of X.Y (even if
65320**                         X and/or Y are implied.)
65321**    pExpr->iColumn       Set to the column number within the table.
65322**    pExpr->op            Set to TK_COLUMN.
65323**    pExpr->pLeft         Any expression this points to is deleted
65324**    pExpr->pRight        Any expression this points to is deleted.
65325**
65326** The zDb variable is the name of the database (the "X").  This value may be
65327** NULL meaning that name is of the form Y.Z or Z.  Any available database
65328** can be used.  The zTable variable is the name of the table (the "Y").  This
65329** value can be NULL if zDb is also NULL.  If zTable is NULL it
65330** means that the form of the name is Z and that columns from any table
65331** can be used.
65332**
65333** If the name cannot be resolved unambiguously, leave an error message
65334** in pParse and return WRC_Abort.  Return WRC_Prune on success.
65335*/
65336static int lookupName(
65337  Parse *pParse,       /* The parsing context */
65338  const char *zDb,     /* Name of the database containing table, or NULL */
65339  const char *zTab,    /* Name of table containing column, or NULL */
65340  const char *zCol,    /* Name of the column. */
65341  NameContext *pNC,    /* The name context used to resolve the name */
65342  Expr *pExpr          /* Make this EXPR node point to the selected column */
65343){
65344  int i, j;            /* Loop counters */
65345  int cnt = 0;                      /* Number of matching column names */
65346  int cntTab = 0;                   /* Number of matching table names */
65347  sqlite3 *db = pParse->db;         /* The database connection */
65348  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
65349  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
65350  NameContext *pTopNC = pNC;        /* First namecontext in the list */
65351  Schema *pSchema = 0;              /* Schema of the expression */
65352  int isTrigger = 0;
65353
65354  assert( pNC );     /* the name context cannot be NULL. */
65355  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
65356  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
65357
65358  /* Initialize the node to no-match */
65359  pExpr->iTable = -1;
65360  pExpr->pTab = 0;
65361  ExprSetIrreducible(pExpr);
65362
65363  /* Start at the inner-most context and move outward until a match is found */
65364  while( pNC && cnt==0 ){
65365    ExprList *pEList;
65366    SrcList *pSrcList = pNC->pSrcList;
65367
65368    if( pSrcList ){
65369      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
65370        Table *pTab;
65371        int iDb;
65372        Column *pCol;
65373
65374        pTab = pItem->pTab;
65375        assert( pTab!=0 && pTab->zName!=0 );
65376        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65377        assert( pTab->nCol>0 );
65378        if( zTab ){
65379          if( pItem->zAlias ){
65380            char *zTabName = pItem->zAlias;
65381            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
65382          }else{
65383            char *zTabName = pTab->zName;
65384            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
65385              continue;
65386            }
65387            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
65388              continue;
65389            }
65390          }
65391        }
65392        if( 0==(cntTab++) ){
65393          pExpr->iTable = pItem->iCursor;
65394          pExpr->pTab = pTab;
65395          pSchema = pTab->pSchema;
65396          pMatch = pItem;
65397        }
65398        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
65399          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65400            IdList *pUsing;
65401            cnt++;
65402            pExpr->iTable = pItem->iCursor;
65403            pExpr->pTab = pTab;
65404            pMatch = pItem;
65405            pSchema = pTab->pSchema;
65406            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
65407            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
65408            if( i<pSrcList->nSrc-1 ){
65409              if( pItem[1].jointype & JT_NATURAL ){
65410                /* If this match occurred in the left table of a natural join,
65411                ** then skip the right table to avoid a duplicate match */
65412                pItem++;
65413                i++;
65414              }else if( (pUsing = pItem[1].pUsing)!=0 ){
65415                /* If this match occurs on a column that is in the USING clause
65416                ** of a join, skip the search of the right table of the join
65417                ** to avoid a duplicate match there. */
65418                int k;
65419                for(k=0; k<pUsing->nId; k++){
65420                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
65421                    pItem++;
65422                    i++;
65423                    break;
65424                  }
65425                }
65426              }
65427            }
65428            break;
65429          }
65430        }
65431      }
65432    }
65433
65434#ifndef SQLITE_OMIT_TRIGGER
65435    /* If we have not already resolved the name, then maybe
65436    ** it is a new.* or old.* trigger argument reference
65437    */
65438    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
65439      int op = pParse->eTriggerOp;
65440      Table *pTab = 0;
65441      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
65442      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
65443        pExpr->iTable = 1;
65444        pTab = pParse->pTriggerTab;
65445      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
65446        pExpr->iTable = 0;
65447        pTab = pParse->pTriggerTab;
65448      }
65449
65450      if( pTab ){
65451        int iCol;
65452        pSchema = pTab->pSchema;
65453        cntTab++;
65454        for(iCol=0; iCol<pTab->nCol; iCol++){
65455          Column *pCol = &pTab->aCol[iCol];
65456          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65457            if( iCol==pTab->iPKey ){
65458              iCol = -1;
65459            }
65460            break;
65461          }
65462        }
65463        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
65464          iCol = -1;        /* IMP: R-44911-55124 */
65465        }
65466        if( iCol<pTab->nCol ){
65467          cnt++;
65468          if( iCol<0 ){
65469            pExpr->affinity = SQLITE_AFF_INTEGER;
65470          }else if( pExpr->iTable==0 ){
65471            testcase( iCol==31 );
65472            testcase( iCol==32 );
65473            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65474          }else{
65475            testcase( iCol==31 );
65476            testcase( iCol==32 );
65477            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65478          }
65479          pExpr->iColumn = (i16)iCol;
65480          pExpr->pTab = pTab;
65481          isTrigger = 1;
65482        }
65483      }
65484    }
65485#endif /* !defined(SQLITE_OMIT_TRIGGER) */
65486
65487    /*
65488    ** Perhaps the name is a reference to the ROWID
65489    */
65490    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
65491      cnt = 1;
65492      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
65493      pExpr->affinity = SQLITE_AFF_INTEGER;
65494    }
65495
65496    /*
65497    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
65498    ** might refer to an result-set alias.  This happens, for example, when
65499    ** we are resolving names in the WHERE clause of the following command:
65500    **
65501    **     SELECT a+b AS x FROM table WHERE x<10;
65502    **
65503    ** In cases like this, replace pExpr with a copy of the expression that
65504    ** forms the result set entry ("a+b" in the example) and return immediately.
65505    ** Note that the expression in the result set should have already been
65506    ** resolved by the time the WHERE clause is resolved.
65507    */
65508    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
65509      for(j=0; j<pEList->nExpr; j++){
65510        char *zAs = pEList->a[j].zName;
65511        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
65512          Expr *pOrig;
65513          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
65514          assert( pExpr->x.pList==0 );
65515          assert( pExpr->x.pSelect==0 );
65516          pOrig = pEList->a[j].pExpr;
65517          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
65518            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
65519            return WRC_Abort;
65520          }
65521          resolveAlias(pParse, pEList, j, pExpr, "");
65522          cnt = 1;
65523          pMatch = 0;
65524          assert( zTab==0 && zDb==0 );
65525          goto lookupname_end;
65526        }
65527      }
65528    }
65529
65530    /* Advance to the next name context.  The loop will exit when either
65531    ** we have a match (cnt>0) or when we run out of name contexts.
65532    */
65533    if( cnt==0 ){
65534      pNC = pNC->pNext;
65535    }
65536  }
65537
65538  /*
65539  ** If X and Y are NULL (in other words if only the column name Z is
65540  ** supplied) and the value of Z is enclosed in double-quotes, then
65541  ** Z is a string literal if it doesn't match any column names.  In that
65542  ** case, we need to return right away and not make any changes to
65543  ** pExpr.
65544  **
65545  ** Because no reference was made to outer contexts, the pNC->nRef
65546  ** fields are not changed in any context.
65547  */
65548  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
65549    pExpr->op = TK_STRING;
65550    pExpr->pTab = 0;
65551    return WRC_Prune;
65552  }
65553
65554  /*
65555  ** cnt==0 means there was not match.  cnt>1 means there were two or
65556  ** more matches.  Either way, we have an error.
65557  */
65558  if( cnt!=1 ){
65559    const char *zErr;
65560    zErr = cnt==0 ? "no such column" : "ambiguous column name";
65561    if( zDb ){
65562      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
65563    }else if( zTab ){
65564      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
65565    }else{
65566      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
65567    }
65568    pParse->checkSchema = 1;
65569    pTopNC->nErr++;
65570  }
65571
65572  /* If a column from a table in pSrcList is referenced, then record
65573  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
65574  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
65575  ** column number is greater than the number of bits in the bitmask
65576  ** then set the high-order bit of the bitmask.
65577  */
65578  if( pExpr->iColumn>=0 && pMatch!=0 ){
65579    int n = pExpr->iColumn;
65580    testcase( n==BMS-1 );
65581    if( n>=BMS ){
65582      n = BMS-1;
65583    }
65584    assert( pMatch->iCursor==pExpr->iTable );
65585    pMatch->colUsed |= ((Bitmask)1)<<n;
65586  }
65587
65588  /* Clean up and return
65589  */
65590  sqlite3ExprDelete(db, pExpr->pLeft);
65591  pExpr->pLeft = 0;
65592  sqlite3ExprDelete(db, pExpr->pRight);
65593  pExpr->pRight = 0;
65594  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
65595lookupname_end:
65596  if( cnt==1 ){
65597    assert( pNC!=0 );
65598    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
65599    /* Increment the nRef value on all name contexts from TopNC up to
65600    ** the point where the name matched. */
65601    for(;;){
65602      assert( pTopNC!=0 );
65603      pTopNC->nRef++;
65604      if( pTopNC==pNC ) break;
65605      pTopNC = pTopNC->pNext;
65606    }
65607    return WRC_Prune;
65608  } else {
65609    return WRC_Abort;
65610  }
65611}
65612
65613/*
65614** Allocate and return a pointer to an expression to load the column iCol
65615** from datasource iSrc in SrcList pSrc.
65616*/
65617SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
65618  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
65619  if( p ){
65620    struct SrcList_item *pItem = &pSrc->a[iSrc];
65621    p->pTab = pItem->pTab;
65622    p->iTable = pItem->iCursor;
65623    if( p->pTab->iPKey==iCol ){
65624      p->iColumn = -1;
65625    }else{
65626      p->iColumn = (ynVar)iCol;
65627      testcase( iCol==BMS );
65628      testcase( iCol==BMS-1 );
65629      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
65630    }
65631    ExprSetProperty(p, EP_Resolved);
65632  }
65633  return p;
65634}
65635
65636/*
65637** This routine is callback for sqlite3WalkExpr().
65638**
65639** Resolve symbolic names into TK_COLUMN operators for the current
65640** node in the expression tree.  Return 0 to continue the search down
65641** the tree or 2 to abort the tree walk.
65642**
65643** This routine also does error checking and name resolution for
65644** function names.  The operator for aggregate functions is changed
65645** to TK_AGG_FUNCTION.
65646*/
65647static int resolveExprStep(Walker *pWalker, Expr *pExpr){
65648  NameContext *pNC;
65649  Parse *pParse;
65650
65651  pNC = pWalker->u.pNC;
65652  assert( pNC!=0 );
65653  pParse = pNC->pParse;
65654  assert( pParse==pWalker->pParse );
65655
65656  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
65657  ExprSetProperty(pExpr, EP_Resolved);
65658#ifndef NDEBUG
65659  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
65660    SrcList *pSrcList = pNC->pSrcList;
65661    int i;
65662    for(i=0; i<pNC->pSrcList->nSrc; i++){
65663      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
65664    }
65665  }
65666#endif
65667  switch( pExpr->op ){
65668
65669#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
65670    /* The special operator TK_ROW means use the rowid for the first
65671    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
65672    ** clause processing on UPDATE and DELETE statements.
65673    */
65674    case TK_ROW: {
65675      SrcList *pSrcList = pNC->pSrcList;
65676      struct SrcList_item *pItem;
65677      assert( pSrcList && pSrcList->nSrc==1 );
65678      pItem = pSrcList->a;
65679      pExpr->op = TK_COLUMN;
65680      pExpr->pTab = pItem->pTab;
65681      pExpr->iTable = pItem->iCursor;
65682      pExpr->iColumn = -1;
65683      pExpr->affinity = SQLITE_AFF_INTEGER;
65684      break;
65685    }
65686#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
65687
65688    /* A lone identifier is the name of a column.
65689    */
65690    case TK_ID: {
65691      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
65692    }
65693
65694    /* A table name and column name:     ID.ID
65695    ** Or a database, table and column:  ID.ID.ID
65696    */
65697    case TK_DOT: {
65698      const char *zColumn;
65699      const char *zTable;
65700      const char *zDb;
65701      Expr *pRight;
65702
65703      /* if( pSrcList==0 ) break; */
65704      pRight = pExpr->pRight;
65705      if( pRight->op==TK_ID ){
65706        zDb = 0;
65707        zTable = pExpr->pLeft->u.zToken;
65708        zColumn = pRight->u.zToken;
65709      }else{
65710        assert( pRight->op==TK_DOT );
65711        zDb = pExpr->pLeft->u.zToken;
65712        zTable = pRight->pLeft->u.zToken;
65713        zColumn = pRight->pRight->u.zToken;
65714      }
65715      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
65716    }
65717
65718    /* Resolve function names
65719    */
65720    case TK_CONST_FUNC:
65721    case TK_FUNCTION: {
65722      ExprList *pList = pExpr->x.pList;    /* The argument list */
65723      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
65724      int no_such_func = 0;       /* True if no such function exists */
65725      int wrong_num_args = 0;     /* True if wrong number of arguments */
65726      int is_agg = 0;             /* True if is an aggregate function */
65727      int auth;                   /* Authorization to use the function */
65728      int nId;                    /* Number of characters in function name */
65729      const char *zId;            /* The function name. */
65730      FuncDef *pDef;              /* Information about the function */
65731      u8 enc = ENC(pParse->db);   /* The database encoding */
65732
65733      testcase( pExpr->op==TK_CONST_FUNC );
65734      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
65735      zId = pExpr->u.zToken;
65736      nId = sqlite3Strlen30(zId);
65737      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
65738      if( pDef==0 ){
65739        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
65740        if( pDef==0 ){
65741          no_such_func = 1;
65742        }else{
65743          wrong_num_args = 1;
65744        }
65745      }else{
65746        is_agg = pDef->xFunc==0;
65747      }
65748#ifndef SQLITE_OMIT_AUTHORIZATION
65749      if( pDef ){
65750        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
65751        if( auth!=SQLITE_OK ){
65752          if( auth==SQLITE_DENY ){
65753            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
65754                                    pDef->zName);
65755            pNC->nErr++;
65756          }
65757          pExpr->op = TK_NULL;
65758          return WRC_Prune;
65759        }
65760      }
65761#endif
65762      if( is_agg && !pNC->allowAgg ){
65763        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
65764        pNC->nErr++;
65765        is_agg = 0;
65766      }else if( no_such_func ){
65767        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
65768        pNC->nErr++;
65769      }else if( wrong_num_args ){
65770        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
65771             nId, zId);
65772        pNC->nErr++;
65773      }
65774      if( is_agg ){
65775        pExpr->op = TK_AGG_FUNCTION;
65776        pNC->hasAgg = 1;
65777      }
65778      if( is_agg ) pNC->allowAgg = 0;
65779      sqlite3WalkExprList(pWalker, pList);
65780      if( is_agg ) pNC->allowAgg = 1;
65781      /* FIX ME:  Compute pExpr->affinity based on the expected return
65782      ** type of the function
65783      */
65784      return WRC_Prune;
65785    }
65786#ifndef SQLITE_OMIT_SUBQUERY
65787    case TK_SELECT:
65788    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
65789#endif
65790    case TK_IN: {
65791      testcase( pExpr->op==TK_IN );
65792      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65793        int nRef = pNC->nRef;
65794#ifndef SQLITE_OMIT_CHECK
65795        if( pNC->isCheck ){
65796          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
65797        }
65798#endif
65799        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
65800        assert( pNC->nRef>=nRef );
65801        if( nRef!=pNC->nRef ){
65802          ExprSetProperty(pExpr, EP_VarSelect);
65803        }
65804      }
65805      break;
65806    }
65807#ifndef SQLITE_OMIT_CHECK
65808    case TK_VARIABLE: {
65809      if( pNC->isCheck ){
65810        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
65811      }
65812      break;
65813    }
65814#endif
65815  }
65816  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
65817}
65818
65819/*
65820** pEList is a list of expressions which are really the result set of the
65821** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
65822** This routine checks to see if pE is a simple identifier which corresponds
65823** to the AS-name of one of the terms of the expression list.  If it is,
65824** this routine return an integer between 1 and N where N is the number of
65825** elements in pEList, corresponding to the matching entry.  If there is
65826** no match, or if pE is not a simple identifier, then this routine
65827** return 0.
65828**
65829** pEList has been resolved.  pE has not.
65830*/
65831static int resolveAsName(
65832  Parse *pParse,     /* Parsing context for error messages */
65833  ExprList *pEList,  /* List of expressions to scan */
65834  Expr *pE           /* Expression we are trying to match */
65835){
65836  int i;             /* Loop counter */
65837
65838  UNUSED_PARAMETER(pParse);
65839
65840  if( pE->op==TK_ID ){
65841    char *zCol = pE->u.zToken;
65842    for(i=0; i<pEList->nExpr; i++){
65843      char *zAs = pEList->a[i].zName;
65844      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
65845        return i+1;
65846      }
65847    }
65848  }
65849  return 0;
65850}
65851
65852/*
65853** pE is a pointer to an expression which is a single term in the
65854** ORDER BY of a compound SELECT.  The expression has not been
65855** name resolved.
65856**
65857** At the point this routine is called, we already know that the
65858** ORDER BY term is not an integer index into the result set.  That
65859** case is handled by the calling routine.
65860**
65861** Attempt to match pE against result set columns in the left-most
65862** SELECT statement.  Return the index i of the matching column,
65863** as an indication to the caller that it should sort by the i-th column.
65864** The left-most column is 1.  In other words, the value returned is the
65865** same integer value that would be used in the SQL statement to indicate
65866** the column.
65867**
65868** If there is no match, return 0.  Return -1 if an error occurs.
65869*/
65870static int resolveOrderByTermToExprList(
65871  Parse *pParse,     /* Parsing context for error messages */
65872  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
65873  Expr *pE           /* The specific ORDER BY term */
65874){
65875  int i;             /* Loop counter */
65876  ExprList *pEList;  /* The columns of the result set */
65877  NameContext nc;    /* Name context for resolving pE */
65878  sqlite3 *db;       /* Database connection */
65879  int rc;            /* Return code from subprocedures */
65880  u8 savedSuppErr;   /* Saved value of db->suppressErr */
65881
65882  assert( sqlite3ExprIsInteger(pE, &i)==0 );
65883  pEList = pSelect->pEList;
65884
65885  /* Resolve all names in the ORDER BY term expression
65886  */
65887  memset(&nc, 0, sizeof(nc));
65888  nc.pParse = pParse;
65889  nc.pSrcList = pSelect->pSrc;
65890  nc.pEList = pEList;
65891  nc.allowAgg = 1;
65892  nc.nErr = 0;
65893  db = pParse->db;
65894  savedSuppErr = db->suppressErr;
65895  db->suppressErr = 1;
65896  rc = sqlite3ResolveExprNames(&nc, pE);
65897  db->suppressErr = savedSuppErr;
65898  if( rc ) return 0;
65899
65900  /* Try to match the ORDER BY expression against an expression
65901  ** in the result set.  Return an 1-based index of the matching
65902  ** result-set entry.
65903  */
65904  for(i=0; i<pEList->nExpr; i++){
65905    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
65906      return i+1;
65907    }
65908  }
65909
65910  /* If no match, return 0. */
65911  return 0;
65912}
65913
65914/*
65915** Generate an ORDER BY or GROUP BY term out-of-range error.
65916*/
65917static void resolveOutOfRangeError(
65918  Parse *pParse,         /* The error context into which to write the error */
65919  const char *zType,     /* "ORDER" or "GROUP" */
65920  int i,                 /* The index (1-based) of the term out of range */
65921  int mx                 /* Largest permissible value of i */
65922){
65923  sqlite3ErrorMsg(pParse,
65924    "%r %s BY term out of range - should be "
65925    "between 1 and %d", i, zType, mx);
65926}
65927
65928/*
65929** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
65930** each term of the ORDER BY clause is a constant integer between 1
65931** and N where N is the number of columns in the compound SELECT.
65932**
65933** ORDER BY terms that are already an integer between 1 and N are
65934** unmodified.  ORDER BY terms that are integers outside the range of
65935** 1 through N generate an error.  ORDER BY terms that are expressions
65936** are matched against result set expressions of compound SELECT
65937** beginning with the left-most SELECT and working toward the right.
65938** At the first match, the ORDER BY expression is transformed into
65939** the integer column number.
65940**
65941** Return the number of errors seen.
65942*/
65943static int resolveCompoundOrderBy(
65944  Parse *pParse,        /* Parsing context.  Leave error messages here */
65945  Select *pSelect       /* The SELECT statement containing the ORDER BY */
65946){
65947  int i;
65948  ExprList *pOrderBy;
65949  ExprList *pEList;
65950  sqlite3 *db;
65951  int moreToDo = 1;
65952
65953  pOrderBy = pSelect->pOrderBy;
65954  if( pOrderBy==0 ) return 0;
65955  db = pParse->db;
65956#if SQLITE_MAX_COLUMN
65957  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
65958    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
65959    return 1;
65960  }
65961#endif
65962  for(i=0; i<pOrderBy->nExpr; i++){
65963    pOrderBy->a[i].done = 0;
65964  }
65965  pSelect->pNext = 0;
65966  while( pSelect->pPrior ){
65967    pSelect->pPrior->pNext = pSelect;
65968    pSelect = pSelect->pPrior;
65969  }
65970  while( pSelect && moreToDo ){
65971    struct ExprList_item *pItem;
65972    moreToDo = 0;
65973    pEList = pSelect->pEList;
65974    assert( pEList!=0 );
65975    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
65976      int iCol = -1;
65977      Expr *pE, *pDup;
65978      if( pItem->done ) continue;
65979      pE = pItem->pExpr;
65980      if( sqlite3ExprIsInteger(pE, &iCol) ){
65981        if( iCol<=0 || iCol>pEList->nExpr ){
65982          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
65983          return 1;
65984        }
65985      }else{
65986        iCol = resolveAsName(pParse, pEList, pE);
65987        if( iCol==0 ){
65988          pDup = sqlite3ExprDup(db, pE, 0);
65989          if( !db->mallocFailed ){
65990            assert(pDup);
65991            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
65992          }
65993          sqlite3ExprDelete(db, pDup);
65994        }
65995      }
65996      if( iCol>0 ){
65997        CollSeq *pColl = pE->pColl;
65998        int flags = pE->flags & EP_ExpCollate;
65999        sqlite3ExprDelete(db, pE);
66000        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
66001        if( pE==0 ) return 1;
66002        pE->pColl = pColl;
66003        pE->flags |= EP_IntValue | flags;
66004        pE->u.iValue = iCol;
66005        pItem->iCol = (u16)iCol;
66006        pItem->done = 1;
66007      }else{
66008        moreToDo = 1;
66009      }
66010    }
66011    pSelect = pSelect->pNext;
66012  }
66013  for(i=0; i<pOrderBy->nExpr; i++){
66014    if( pOrderBy->a[i].done==0 ){
66015      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
66016            "column in the result set", i+1);
66017      return 1;
66018    }
66019  }
66020  return 0;
66021}
66022
66023/*
66024** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
66025** the SELECT statement pSelect.  If any term is reference to a
66026** result set expression (as determined by the ExprList.a.iCol field)
66027** then convert that term into a copy of the corresponding result set
66028** column.
66029**
66030** If any errors are detected, add an error message to pParse and
66031** return non-zero.  Return zero if no errors are seen.
66032*/
66033SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
66034  Parse *pParse,        /* Parsing context.  Leave error messages here */
66035  Select *pSelect,      /* The SELECT statement containing the clause */
66036  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
66037  const char *zType     /* "ORDER" or "GROUP" */
66038){
66039  int i;
66040  sqlite3 *db = pParse->db;
66041  ExprList *pEList;
66042  struct ExprList_item *pItem;
66043
66044  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
66045#if SQLITE_MAX_COLUMN
66046  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
66047    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
66048    return 1;
66049  }
66050#endif
66051  pEList = pSelect->pEList;
66052  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
66053  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66054    if( pItem->iCol ){
66055      if( pItem->iCol>pEList->nExpr ){
66056        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
66057        return 1;
66058      }
66059      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
66060    }
66061  }
66062  return 0;
66063}
66064
66065/*
66066** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
66067** The Name context of the SELECT statement is pNC.  zType is either
66068** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
66069**
66070** This routine resolves each term of the clause into an expression.
66071** If the order-by term is an integer I between 1 and N (where N is the
66072** number of columns in the result set of the SELECT) then the expression
66073** in the resolution is a copy of the I-th result-set expression.  If
66074** the order-by term is an identify that corresponds to the AS-name of
66075** a result-set expression, then the term resolves to a copy of the
66076** result-set expression.  Otherwise, the expression is resolved in
66077** the usual way - using sqlite3ResolveExprNames().
66078**
66079** This routine returns the number of errors.  If errors occur, then
66080** an appropriate error message might be left in pParse.  (OOM errors
66081** excepted.)
66082*/
66083static int resolveOrderGroupBy(
66084  NameContext *pNC,     /* The name context of the SELECT statement */
66085  Select *pSelect,      /* The SELECT statement holding pOrderBy */
66086  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
66087  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
66088){
66089  int i;                         /* Loop counter */
66090  int iCol;                      /* Column number */
66091  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
66092  Parse *pParse;                 /* Parsing context */
66093  int nResult;                   /* Number of terms in the result set */
66094
66095  if( pOrderBy==0 ) return 0;
66096  nResult = pSelect->pEList->nExpr;
66097  pParse = pNC->pParse;
66098  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66099    Expr *pE = pItem->pExpr;
66100    iCol = resolveAsName(pParse, pSelect->pEList, pE);
66101    if( iCol>0 ){
66102      /* If an AS-name match is found, mark this ORDER BY column as being
66103      ** a copy of the iCol-th result-set column.  The subsequent call to
66104      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
66105      ** copy of the iCol-th result-set expression. */
66106      pItem->iCol = (u16)iCol;
66107      continue;
66108    }
66109    if( sqlite3ExprIsInteger(pE, &iCol) ){
66110      /* The ORDER BY term is an integer constant.  Again, set the column
66111      ** number so that sqlite3ResolveOrderGroupBy() will convert the
66112      ** order-by term to a copy of the result-set expression */
66113      if( iCol<1 ){
66114        resolveOutOfRangeError(pParse, zType, i+1, nResult);
66115        return 1;
66116      }
66117      pItem->iCol = (u16)iCol;
66118      continue;
66119    }
66120
66121    /* Otherwise, treat the ORDER BY term as an ordinary expression */
66122    pItem->iCol = 0;
66123    if( sqlite3ResolveExprNames(pNC, pE) ){
66124      return 1;
66125    }
66126  }
66127  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
66128}
66129
66130/*
66131** Resolve names in the SELECT statement p and all of its descendents.
66132*/
66133static int resolveSelectStep(Walker *pWalker, Select *p){
66134  NameContext *pOuterNC;  /* Context that contains this SELECT */
66135  NameContext sNC;        /* Name context of this SELECT */
66136  int isCompound;         /* True if p is a compound select */
66137  int nCompound;          /* Number of compound terms processed so far */
66138  Parse *pParse;          /* Parsing context */
66139  ExprList *pEList;       /* Result set expression list */
66140  int i;                  /* Loop counter */
66141  ExprList *pGroupBy;     /* The GROUP BY clause */
66142  Select *pLeftmost;      /* Left-most of SELECT of a compound */
66143  sqlite3 *db;            /* Database connection */
66144
66145
66146  assert( p!=0 );
66147  if( p->selFlags & SF_Resolved ){
66148    return WRC_Prune;
66149  }
66150  pOuterNC = pWalker->u.pNC;
66151  pParse = pWalker->pParse;
66152  db = pParse->db;
66153
66154  /* Normally sqlite3SelectExpand() will be called first and will have
66155  ** already expanded this SELECT.  However, if this is a subquery within
66156  ** an expression, sqlite3ResolveExprNames() will be called without a
66157  ** prior call to sqlite3SelectExpand().  When that happens, let
66158  ** sqlite3SelectPrep() do all of the processing for this SELECT.
66159  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
66160  ** this routine in the correct order.
66161  */
66162  if( (p->selFlags & SF_Expanded)==0 ){
66163    sqlite3SelectPrep(pParse, p, pOuterNC);
66164    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
66165  }
66166
66167  isCompound = p->pPrior!=0;
66168  nCompound = 0;
66169  pLeftmost = p;
66170  while( p ){
66171    assert( (p->selFlags & SF_Expanded)!=0 );
66172    assert( (p->selFlags & SF_Resolved)==0 );
66173    p->selFlags |= SF_Resolved;
66174
66175    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
66176    ** are not allowed to refer to any names, so pass an empty NameContext.
66177    */
66178    memset(&sNC, 0, sizeof(sNC));
66179    sNC.pParse = pParse;
66180    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
66181        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
66182      return WRC_Abort;
66183    }
66184
66185    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
66186    ** resolve the result-set expression list.
66187    */
66188    sNC.allowAgg = 1;
66189    sNC.pSrcList = p->pSrc;
66190    sNC.pNext = pOuterNC;
66191
66192    /* Resolve names in the result set. */
66193    pEList = p->pEList;
66194    assert( pEList!=0 );
66195    for(i=0; i<pEList->nExpr; i++){
66196      Expr *pX = pEList->a[i].pExpr;
66197      if( sqlite3ResolveExprNames(&sNC, pX) ){
66198        return WRC_Abort;
66199      }
66200    }
66201
66202    /* Recursively resolve names in all subqueries
66203    */
66204    for(i=0; i<p->pSrc->nSrc; i++){
66205      struct SrcList_item *pItem = &p->pSrc->a[i];
66206      if( pItem->pSelect ){
66207        const char *zSavedContext = pParse->zAuthContext;
66208        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
66209        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
66210        pParse->zAuthContext = zSavedContext;
66211        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
66212      }
66213    }
66214
66215    /* If there are no aggregate functions in the result-set, and no GROUP BY
66216    ** expression, do not allow aggregates in any of the other expressions.
66217    */
66218    assert( (p->selFlags & SF_Aggregate)==0 );
66219    pGroupBy = p->pGroupBy;
66220    if( pGroupBy || sNC.hasAgg ){
66221      p->selFlags |= SF_Aggregate;
66222    }else{
66223      sNC.allowAgg = 0;
66224    }
66225
66226    /* If a HAVING clause is present, then there must be a GROUP BY clause.
66227    */
66228    if( p->pHaving && !pGroupBy ){
66229      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
66230      return WRC_Abort;
66231    }
66232
66233    /* Add the expression list to the name-context before parsing the
66234    ** other expressions in the SELECT statement. This is so that
66235    ** expressions in the WHERE clause (etc.) can refer to expressions by
66236    ** aliases in the result set.
66237    **
66238    ** Minor point: If this is the case, then the expression will be
66239    ** re-evaluated for each reference to it.
66240    */
66241    sNC.pEList = p->pEList;
66242    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
66243       sqlite3ResolveExprNames(&sNC, p->pHaving)
66244    ){
66245      return WRC_Abort;
66246    }
66247
66248    /* The ORDER BY and GROUP BY clauses may not refer to terms in
66249    ** outer queries
66250    */
66251    sNC.pNext = 0;
66252    sNC.allowAgg = 1;
66253
66254    /* Process the ORDER BY clause for singleton SELECT statements.
66255    ** The ORDER BY clause for compounds SELECT statements is handled
66256    ** below, after all of the result-sets for all of the elements of
66257    ** the compound have been resolved.
66258    */
66259    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
66260      return WRC_Abort;
66261    }
66262    if( db->mallocFailed ){
66263      return WRC_Abort;
66264    }
66265
66266    /* Resolve the GROUP BY clause.  At the same time, make sure
66267    ** the GROUP BY clause does not contain aggregate functions.
66268    */
66269    if( pGroupBy ){
66270      struct ExprList_item *pItem;
66271
66272      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
66273        return WRC_Abort;
66274      }
66275      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
66276        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
66277          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
66278              "the GROUP BY clause");
66279          return WRC_Abort;
66280        }
66281      }
66282    }
66283
66284    /* Advance to the next term of the compound
66285    */
66286    p = p->pPrior;
66287    nCompound++;
66288  }
66289
66290  /* Resolve the ORDER BY on a compound SELECT after all terms of
66291  ** the compound have been resolved.
66292  */
66293  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
66294    return WRC_Abort;
66295  }
66296
66297  return WRC_Prune;
66298}
66299
66300/*
66301** This routine walks an expression tree and resolves references to
66302** table columns and result-set columns.  At the same time, do error
66303** checking on function usage and set a flag if any aggregate functions
66304** are seen.
66305**
66306** To resolve table columns references we look for nodes (or subtrees) of the
66307** form X.Y.Z or Y.Z or just Z where
66308**
66309**      X:   The name of a database.  Ex:  "main" or "temp" or
66310**           the symbolic name assigned to an ATTACH-ed database.
66311**
66312**      Y:   The name of a table in a FROM clause.  Or in a trigger
66313**           one of the special names "old" or "new".
66314**
66315**      Z:   The name of a column in table Y.
66316**
66317** The node at the root of the subtree is modified as follows:
66318**
66319**    Expr.op        Changed to TK_COLUMN
66320**    Expr.pTab      Points to the Table object for X.Y
66321**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
66322**    Expr.iTable    The VDBE cursor number for X.Y
66323**
66324**
66325** To resolve result-set references, look for expression nodes of the
66326** form Z (with no X and Y prefix) where the Z matches the right-hand
66327** size of an AS clause in the result-set of a SELECT.  The Z expression
66328** is replaced by a copy of the left-hand side of the result-set expression.
66329** Table-name and function resolution occurs on the substituted expression
66330** tree.  For example, in:
66331**
66332**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
66333**
66334** The "x" term of the order by is replaced by "a+b" to render:
66335**
66336**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
66337**
66338** Function calls are checked to make sure that the function is
66339** defined and that the correct number of arguments are specified.
66340** If the function is an aggregate function, then the pNC->hasAgg is
66341** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
66342** If an expression contains aggregate functions then the EP_Agg
66343** property on the expression is set.
66344**
66345** An error message is left in pParse if anything is amiss.  The number
66346** if errors is returned.
66347*/
66348SQLITE_PRIVATE int sqlite3ResolveExprNames(
66349  NameContext *pNC,       /* Namespace to resolve expressions in. */
66350  Expr *pExpr             /* The expression to be analyzed. */
66351){
66352  int savedHasAgg;
66353  Walker w;
66354
66355  if( pExpr==0 ) return 0;
66356#if SQLITE_MAX_EXPR_DEPTH>0
66357  {
66358    Parse *pParse = pNC->pParse;
66359    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
66360      return 1;
66361    }
66362    pParse->nHeight += pExpr->nHeight;
66363  }
66364#endif
66365  savedHasAgg = pNC->hasAgg;
66366  pNC->hasAgg = 0;
66367  w.xExprCallback = resolveExprStep;
66368  w.xSelectCallback = resolveSelectStep;
66369  w.pParse = pNC->pParse;
66370  w.u.pNC = pNC;
66371  sqlite3WalkExpr(&w, pExpr);
66372#if SQLITE_MAX_EXPR_DEPTH>0
66373  pNC->pParse->nHeight -= pExpr->nHeight;
66374#endif
66375  if( pNC->nErr>0 || w.pParse->nErr>0 ){
66376    ExprSetProperty(pExpr, EP_Error);
66377  }
66378  if( pNC->hasAgg ){
66379    ExprSetProperty(pExpr, EP_Agg);
66380  }else if( savedHasAgg ){
66381    pNC->hasAgg = 1;
66382  }
66383  return ExprHasProperty(pExpr, EP_Error);
66384}
66385
66386
66387/*
66388** Resolve all names in all expressions of a SELECT and in all
66389** decendents of the SELECT, including compounds off of p->pPrior,
66390** subqueries in expressions, and subqueries used as FROM clause
66391** terms.
66392**
66393** See sqlite3ResolveExprNames() for a description of the kinds of
66394** transformations that occur.
66395**
66396** All SELECT statements should have been expanded using
66397** sqlite3SelectExpand() prior to invoking this routine.
66398*/
66399SQLITE_PRIVATE void sqlite3ResolveSelectNames(
66400  Parse *pParse,         /* The parser context */
66401  Select *p,             /* The SELECT statement being coded. */
66402  NameContext *pOuterNC  /* Name context for parent SELECT statement */
66403){
66404  Walker w;
66405
66406  assert( p!=0 );
66407  w.xExprCallback = resolveExprStep;
66408  w.xSelectCallback = resolveSelectStep;
66409  w.pParse = pParse;
66410  w.u.pNC = pOuterNC;
66411  sqlite3WalkSelect(&w, p);
66412}
66413
66414/************** End of resolve.c *********************************************/
66415/************** Begin file expr.c ********************************************/
66416/*
66417** 2001 September 15
66418**
66419** The author disclaims copyright to this source code.  In place of
66420** a legal notice, here is a blessing:
66421**
66422**    May you do good and not evil.
66423**    May you find forgiveness for yourself and forgive others.
66424**    May you share freely, never taking more than you give.
66425**
66426*************************************************************************
66427** This file contains routines used for analyzing expressions and
66428** for generating VDBE code that evaluates expressions in SQLite.
66429*/
66430
66431/*
66432** Return the 'affinity' of the expression pExpr if any.
66433**
66434** If pExpr is a column, a reference to a column via an 'AS' alias,
66435** or a sub-select with a column as the return value, then the
66436** affinity of that column is returned. Otherwise, 0x00 is returned,
66437** indicating no affinity for the expression.
66438**
66439** i.e. the WHERE clause expresssions in the following statements all
66440** have an affinity:
66441**
66442** CREATE TABLE t1(a);
66443** SELECT * FROM t1 WHERE a;
66444** SELECT a AS b FROM t1 WHERE b;
66445** SELECT * FROM t1 WHERE (select a from t1);
66446*/
66447SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
66448  int op = pExpr->op;
66449  if( op==TK_SELECT ){
66450    assert( pExpr->flags&EP_xIsSelect );
66451    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
66452  }
66453#ifndef SQLITE_OMIT_CAST
66454  if( op==TK_CAST ){
66455    assert( !ExprHasProperty(pExpr, EP_IntValue) );
66456    return sqlite3AffinityType(pExpr->u.zToken);
66457  }
66458#endif
66459  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
66460   && pExpr->pTab!=0
66461  ){
66462    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
66463    ** a TK_COLUMN but was previously evaluated and cached in a register */
66464    int j = pExpr->iColumn;
66465    if( j<0 ) return SQLITE_AFF_INTEGER;
66466    assert( pExpr->pTab && j<pExpr->pTab->nCol );
66467    return pExpr->pTab->aCol[j].affinity;
66468  }
66469  return pExpr->affinity;
66470}
66471
66472/*
66473** Set the collating sequence for expression pExpr to be the collating
66474** sequence named by pToken.   Return a pointer to the revised expression.
66475** The collating sequence is marked as "explicit" using the EP_ExpCollate
66476** flag.  An explicit collating sequence will override implicit
66477** collating sequences.
66478*/
66479SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
66480  char *zColl = 0;            /* Dequoted name of collation sequence */
66481  CollSeq *pColl;
66482  sqlite3 *db = pParse->db;
66483  zColl = sqlite3NameFromToken(db, pCollName);
66484  if( pExpr && zColl ){
66485    pColl = sqlite3LocateCollSeq(pParse, zColl);
66486    if( pColl ){
66487      pExpr->pColl = pColl;
66488      pExpr->flags |= EP_ExpCollate;
66489    }
66490  }
66491  sqlite3DbFree(db, zColl);
66492  return pExpr;
66493}
66494
66495/*
66496** Return the default collation sequence for the expression pExpr. If
66497** there is no default collation type, return 0.
66498*/
66499SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
66500  CollSeq *pColl = 0;
66501  Expr *p = pExpr;
66502  while( ALWAYS(p) ){
66503    int op;
66504    pColl = p->pColl;
66505    if( pColl ) break;
66506    op = p->op;
66507    if( p->pTab!=0 && (
66508        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
66509    )){
66510      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
66511      ** a TK_COLUMN but was previously evaluated and cached in a register */
66512      const char *zColl;
66513      int j = p->iColumn;
66514      if( j>=0 ){
66515        sqlite3 *db = pParse->db;
66516        zColl = p->pTab->aCol[j].zColl;
66517        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
66518        pExpr->pColl = pColl;
66519      }
66520      break;
66521    }
66522    if( op!=TK_CAST && op!=TK_UPLUS ){
66523      break;
66524    }
66525    p = p->pLeft;
66526  }
66527  if( sqlite3CheckCollSeq(pParse, pColl) ){
66528    pColl = 0;
66529  }
66530  return pColl;
66531}
66532
66533/*
66534** pExpr is an operand of a comparison operator.  aff2 is the
66535** type affinity of the other operand.  This routine returns the
66536** type affinity that should be used for the comparison operator.
66537*/
66538SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
66539  char aff1 = sqlite3ExprAffinity(pExpr);
66540  if( aff1 && aff2 ){
66541    /* Both sides of the comparison are columns. If one has numeric
66542    ** affinity, use that. Otherwise use no affinity.
66543    */
66544    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
66545      return SQLITE_AFF_NUMERIC;
66546    }else{
66547      return SQLITE_AFF_NONE;
66548    }
66549  }else if( !aff1 && !aff2 ){
66550    /* Neither side of the comparison is a column.  Compare the
66551    ** results directly.
66552    */
66553    return SQLITE_AFF_NONE;
66554  }else{
66555    /* One side is a column, the other is not. Use the columns affinity. */
66556    assert( aff1==0 || aff2==0 );
66557    return (aff1 + aff2);
66558  }
66559}
66560
66561/*
66562** pExpr is a comparison operator.  Return the type affinity that should
66563** be applied to both operands prior to doing the comparison.
66564*/
66565static char comparisonAffinity(Expr *pExpr){
66566  char aff;
66567  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
66568          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
66569          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
66570  assert( pExpr->pLeft );
66571  aff = sqlite3ExprAffinity(pExpr->pLeft);
66572  if( pExpr->pRight ){
66573    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
66574  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66575    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
66576  }else if( !aff ){
66577    aff = SQLITE_AFF_NONE;
66578  }
66579  return aff;
66580}
66581
66582/*
66583** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
66584** idx_affinity is the affinity of an indexed column. Return true
66585** if the index with affinity idx_affinity may be used to implement
66586** the comparison in pExpr.
66587*/
66588SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
66589  char aff = comparisonAffinity(pExpr);
66590  switch( aff ){
66591    case SQLITE_AFF_NONE:
66592      return 1;
66593    case SQLITE_AFF_TEXT:
66594      return idx_affinity==SQLITE_AFF_TEXT;
66595    default:
66596      return sqlite3IsNumericAffinity(idx_affinity);
66597  }
66598}
66599
66600/*
66601** Return the P5 value that should be used for a binary comparison
66602** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
66603*/
66604static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
66605  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
66606  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
66607  return aff;
66608}
66609
66610/*
66611** Return a pointer to the collation sequence that should be used by
66612** a binary comparison operator comparing pLeft and pRight.
66613**
66614** If the left hand expression has a collating sequence type, then it is
66615** used. Otherwise the collation sequence for the right hand expression
66616** is used, or the default (BINARY) if neither expression has a collating
66617** type.
66618**
66619** Argument pRight (but not pLeft) may be a null pointer. In this case,
66620** it is not considered.
66621*/
66622SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
66623  Parse *pParse,
66624  Expr *pLeft,
66625  Expr *pRight
66626){
66627  CollSeq *pColl;
66628  assert( pLeft );
66629  if( pLeft->flags & EP_ExpCollate ){
66630    assert( pLeft->pColl );
66631    pColl = pLeft->pColl;
66632  }else if( pRight && pRight->flags & EP_ExpCollate ){
66633    assert( pRight->pColl );
66634    pColl = pRight->pColl;
66635  }else{
66636    pColl = sqlite3ExprCollSeq(pParse, pLeft);
66637    if( !pColl ){
66638      pColl = sqlite3ExprCollSeq(pParse, pRight);
66639    }
66640  }
66641  return pColl;
66642}
66643
66644/*
66645** Generate code for a comparison operator.
66646*/
66647static int codeCompare(
66648  Parse *pParse,    /* The parsing (and code generating) context */
66649  Expr *pLeft,      /* The left operand */
66650  Expr *pRight,     /* The right operand */
66651  int opcode,       /* The comparison opcode */
66652  int in1, int in2, /* Register holding operands */
66653  int dest,         /* Jump here if true.  */
66654  int jumpIfNull    /* If true, jump if either operand is NULL */
66655){
66656  int p5;
66657  int addr;
66658  CollSeq *p4;
66659
66660  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
66661  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
66662  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
66663                           (void*)p4, P4_COLLSEQ);
66664  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
66665  return addr;
66666}
66667
66668#if SQLITE_MAX_EXPR_DEPTH>0
66669/*
66670** Check that argument nHeight is less than or equal to the maximum
66671** expression depth allowed. If it is not, leave an error message in
66672** pParse.
66673*/
66674SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
66675  int rc = SQLITE_OK;
66676  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
66677  if( nHeight>mxHeight ){
66678    sqlite3ErrorMsg(pParse,
66679       "Expression tree is too large (maximum depth %d)", mxHeight
66680    );
66681    rc = SQLITE_ERROR;
66682  }
66683  return rc;
66684}
66685
66686/* The following three functions, heightOfExpr(), heightOfExprList()
66687** and heightOfSelect(), are used to determine the maximum height
66688** of any expression tree referenced by the structure passed as the
66689** first argument.
66690**
66691** If this maximum height is greater than the current value pointed
66692** to by pnHeight, the second parameter, then set *pnHeight to that
66693** value.
66694*/
66695static void heightOfExpr(Expr *p, int *pnHeight){
66696  if( p ){
66697    if( p->nHeight>*pnHeight ){
66698      *pnHeight = p->nHeight;
66699    }
66700  }
66701}
66702static void heightOfExprList(ExprList *p, int *pnHeight){
66703  if( p ){
66704    int i;
66705    for(i=0; i<p->nExpr; i++){
66706      heightOfExpr(p->a[i].pExpr, pnHeight);
66707    }
66708  }
66709}
66710static void heightOfSelect(Select *p, int *pnHeight){
66711  if( p ){
66712    heightOfExpr(p->pWhere, pnHeight);
66713    heightOfExpr(p->pHaving, pnHeight);
66714    heightOfExpr(p->pLimit, pnHeight);
66715    heightOfExpr(p->pOffset, pnHeight);
66716    heightOfExprList(p->pEList, pnHeight);
66717    heightOfExprList(p->pGroupBy, pnHeight);
66718    heightOfExprList(p->pOrderBy, pnHeight);
66719    heightOfSelect(p->pPrior, pnHeight);
66720  }
66721}
66722
66723/*
66724** Set the Expr.nHeight variable in the structure passed as an
66725** argument. An expression with no children, Expr.pList or
66726** Expr.pSelect member has a height of 1. Any other expression
66727** has a height equal to the maximum height of any other
66728** referenced Expr plus one.
66729*/
66730static void exprSetHeight(Expr *p){
66731  int nHeight = 0;
66732  heightOfExpr(p->pLeft, &nHeight);
66733  heightOfExpr(p->pRight, &nHeight);
66734  if( ExprHasProperty(p, EP_xIsSelect) ){
66735    heightOfSelect(p->x.pSelect, &nHeight);
66736  }else{
66737    heightOfExprList(p->x.pList, &nHeight);
66738  }
66739  p->nHeight = nHeight + 1;
66740}
66741
66742/*
66743** Set the Expr.nHeight variable using the exprSetHeight() function. If
66744** the height is greater than the maximum allowed expression depth,
66745** leave an error in pParse.
66746*/
66747SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
66748  exprSetHeight(p);
66749  sqlite3ExprCheckHeight(pParse, p->nHeight);
66750}
66751
66752/*
66753** Return the maximum height of any expression tree referenced
66754** by the select statement passed as an argument.
66755*/
66756SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
66757  int nHeight = 0;
66758  heightOfSelect(p, &nHeight);
66759  return nHeight;
66760}
66761#else
66762  #define exprSetHeight(y)
66763#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
66764
66765/*
66766** This routine is the core allocator for Expr nodes.
66767**
66768** Construct a new expression node and return a pointer to it.  Memory
66769** for this node and for the pToken argument is a single allocation
66770** obtained from sqlite3DbMalloc().  The calling function
66771** is responsible for making sure the node eventually gets freed.
66772**
66773** If dequote is true, then the token (if it exists) is dequoted.
66774** If dequote is false, no dequoting is performance.  The deQuote
66775** parameter is ignored if pToken is NULL or if the token does not
66776** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
66777** then the EP_DblQuoted flag is set on the expression node.
66778**
66779** Special case:  If op==TK_INTEGER and pToken points to a string that
66780** can be translated into a 32-bit integer, then the token is not
66781** stored in u.zToken.  Instead, the integer values is written
66782** into u.iValue and the EP_IntValue flag is set.  No extra storage
66783** is allocated to hold the integer text and the dequote flag is ignored.
66784*/
66785SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
66786  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
66787  int op,                 /* Expression opcode */
66788  const Token *pToken,    /* Token argument.  Might be NULL */
66789  int dequote             /* True to dequote */
66790){
66791  Expr *pNew;
66792  int nExtra = 0;
66793  int iValue = 0;
66794
66795  if( pToken ){
66796    if( op!=TK_INTEGER || pToken->z==0
66797          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
66798      nExtra = pToken->n+1;
66799    }
66800  }
66801  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
66802  if( pNew ){
66803    pNew->op = (u8)op;
66804    pNew->iAgg = -1;
66805    if( pToken ){
66806      if( nExtra==0 ){
66807        pNew->flags |= EP_IntValue;
66808        pNew->u.iValue = iValue;
66809      }else{
66810        int c;
66811        pNew->u.zToken = (char*)&pNew[1];
66812        memcpy(pNew->u.zToken, pToken->z, pToken->n);
66813        pNew->u.zToken[pToken->n] = 0;
66814        if( dequote && nExtra>=3
66815             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
66816          sqlite3Dequote(pNew->u.zToken);
66817          if( c=='"' ) pNew->flags |= EP_DblQuoted;
66818        }
66819      }
66820    }
66821#if SQLITE_MAX_EXPR_DEPTH>0
66822    pNew->nHeight = 1;
66823#endif
66824  }
66825  return pNew;
66826}
66827
66828/*
66829** Allocate a new expression node from a zero-terminated token that has
66830** already been dequoted.
66831*/
66832SQLITE_PRIVATE Expr *sqlite3Expr(
66833  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
66834  int op,                 /* Expression opcode */
66835  const char *zToken      /* Token argument.  Might be NULL */
66836){
66837  Token x;
66838  x.z = zToken;
66839  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
66840  return sqlite3ExprAlloc(db, op, &x, 0);
66841}
66842
66843/*
66844** Attach subtrees pLeft and pRight to the Expr node pRoot.
66845**
66846** If pRoot==NULL that means that a memory allocation error has occurred.
66847** In that case, delete the subtrees pLeft and pRight.
66848*/
66849SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
66850  sqlite3 *db,
66851  Expr *pRoot,
66852  Expr *pLeft,
66853  Expr *pRight
66854){
66855  if( pRoot==0 ){
66856    assert( db->mallocFailed );
66857    sqlite3ExprDelete(db, pLeft);
66858    sqlite3ExprDelete(db, pRight);
66859  }else{
66860    if( pRight ){
66861      pRoot->pRight = pRight;
66862      if( pRight->flags & EP_ExpCollate ){
66863        pRoot->flags |= EP_ExpCollate;
66864        pRoot->pColl = pRight->pColl;
66865      }
66866    }
66867    if( pLeft ){
66868      pRoot->pLeft = pLeft;
66869      if( pLeft->flags & EP_ExpCollate ){
66870        pRoot->flags |= EP_ExpCollate;
66871        pRoot->pColl = pLeft->pColl;
66872      }
66873    }
66874    exprSetHeight(pRoot);
66875  }
66876}
66877
66878/*
66879** Allocate a Expr node which joins as many as two subtrees.
66880**
66881** One or both of the subtrees can be NULL.  Return a pointer to the new
66882** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
66883** free the subtrees and return NULL.
66884*/
66885SQLITE_PRIVATE Expr *sqlite3PExpr(
66886  Parse *pParse,          /* Parsing context */
66887  int op,                 /* Expression opcode */
66888  Expr *pLeft,            /* Left operand */
66889  Expr *pRight,           /* Right operand */
66890  const Token *pToken     /* Argument token */
66891){
66892  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
66893  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
66894  return p;
66895}
66896
66897/*
66898** Join two expressions using an AND operator.  If either expression is
66899** NULL, then just return the other expression.
66900*/
66901SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
66902  if( pLeft==0 ){
66903    return pRight;
66904  }else if( pRight==0 ){
66905    return pLeft;
66906  }else{
66907    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
66908    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
66909    return pNew;
66910  }
66911}
66912
66913/*
66914** Construct a new expression node for a function with multiple
66915** arguments.
66916*/
66917SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
66918  Expr *pNew;
66919  sqlite3 *db = pParse->db;
66920  assert( pToken );
66921  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
66922  if( pNew==0 ){
66923    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
66924    return 0;
66925  }
66926  pNew->x.pList = pList;
66927  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
66928  sqlite3ExprSetHeight(pParse, pNew);
66929  return pNew;
66930}
66931
66932/*
66933** Assign a variable number to an expression that encodes a wildcard
66934** in the original SQL statement.
66935**
66936** Wildcards consisting of a single "?" are assigned the next sequential
66937** variable number.
66938**
66939** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
66940** sure "nnn" is not too be to avoid a denial of service attack when
66941** the SQL statement comes from an external source.
66942**
66943** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
66944** as the previous instance of the same wildcard.  Or if this is the first
66945** instance of the wildcard, the next sequenial variable number is
66946** assigned.
66947*/
66948SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
66949  sqlite3 *db = pParse->db;
66950  const char *z;
66951
66952  if( pExpr==0 ) return;
66953  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
66954  z = pExpr->u.zToken;
66955  assert( z!=0 );
66956  assert( z[0]!=0 );
66957  if( z[1]==0 ){
66958    /* Wildcard of the form "?".  Assign the next variable number */
66959    assert( z[0]=='?' );
66960    pExpr->iColumn = (ynVar)(++pParse->nVar);
66961  }else if( z[0]=='?' ){
66962    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
66963    ** use it as the variable number */
66964    int i = atoi((char*)&z[1]);
66965    pExpr->iColumn = (ynVar)i;
66966    testcase( i==0 );
66967    testcase( i==1 );
66968    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
66969    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
66970    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
66971      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
66972          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
66973    }
66974    if( i>pParse->nVar ){
66975      pParse->nVar = i;
66976    }
66977  }else{
66978    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
66979    ** number as the prior appearance of the same name, or if the name
66980    ** has never appeared before, reuse the same variable number
66981    */
66982    int i;
66983    u32 n;
66984    n = sqlite3Strlen30(z);
66985    for(i=0; i<pParse->nVarExpr; i++){
66986      Expr *pE = pParse->apVarExpr[i];
66987      assert( pE!=0 );
66988      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
66989        pExpr->iColumn = pE->iColumn;
66990        break;
66991      }
66992    }
66993    if( i>=pParse->nVarExpr ){
66994      pExpr->iColumn = (ynVar)(++pParse->nVar);
66995      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
66996        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
66997        pParse->apVarExpr =
66998            sqlite3DbReallocOrFree(
66999              db,
67000              pParse->apVarExpr,
67001              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
67002            );
67003      }
67004      if( !db->mallocFailed ){
67005        assert( pParse->apVarExpr!=0 );
67006        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
67007      }
67008    }
67009  }
67010  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
67011    sqlite3ErrorMsg(pParse, "too many SQL variables");
67012  }
67013}
67014
67015/*
67016** Recursively delete an expression tree.
67017*/
67018SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
67019  if( p==0 ) return;
67020  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67021    sqlite3ExprDelete(db, p->pLeft);
67022    sqlite3ExprDelete(db, p->pRight);
67023    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
67024      sqlite3DbFree(db, p->u.zToken);
67025    }
67026    if( ExprHasProperty(p, EP_xIsSelect) ){
67027      sqlite3SelectDelete(db, p->x.pSelect);
67028    }else{
67029      sqlite3ExprListDelete(db, p->x.pList);
67030    }
67031  }
67032  if( !ExprHasProperty(p, EP_Static) ){
67033    sqlite3DbFree(db, p);
67034  }
67035}
67036
67037/*
67038** Return the number of bytes allocated for the expression structure
67039** passed as the first argument. This is always one of EXPR_FULLSIZE,
67040** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
67041*/
67042static int exprStructSize(Expr *p){
67043  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
67044  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
67045  return EXPR_FULLSIZE;
67046}
67047
67048/*
67049** The dupedExpr*Size() routines each return the number of bytes required
67050** to store a copy of an expression or expression tree.  They differ in
67051** how much of the tree is measured.
67052**
67053**     dupedExprStructSize()     Size of only the Expr structure
67054**     dupedExprNodeSize()       Size of Expr + space for token
67055**     dupedExprSize()           Expr + token + subtree components
67056**
67057***************************************************************************
67058**
67059** The dupedExprStructSize() function returns two values OR-ed together:
67060** (1) the space required for a copy of the Expr structure only and
67061** (2) the EP_xxx flags that indicate what the structure size should be.
67062** The return values is always one of:
67063**
67064**      EXPR_FULLSIZE
67065**      EXPR_REDUCEDSIZE   | EP_Reduced
67066**      EXPR_TOKENONLYSIZE | EP_TokenOnly
67067**
67068** The size of the structure can be found by masking the return value
67069** of this routine with 0xfff.  The flags can be found by masking the
67070** return value with EP_Reduced|EP_TokenOnly.
67071**
67072** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
67073** (unreduced) Expr objects as they or originally constructed by the parser.
67074** During expression analysis, extra information is computed and moved into
67075** later parts of teh Expr object and that extra information might get chopped
67076** off if the expression is reduced.  Note also that it does not work to
67077** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
67078** to reduce a pristine expression tree from the parser.  The implementation
67079** of dupedExprStructSize() contain multiple assert() statements that attempt
67080** to enforce this constraint.
67081*/
67082static int dupedExprStructSize(Expr *p, int flags){
67083  int nSize;
67084  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
67085  if( 0==(flags&EXPRDUP_REDUCE) ){
67086    nSize = EXPR_FULLSIZE;
67087  }else{
67088    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
67089    assert( !ExprHasProperty(p, EP_FromJoin) );
67090    assert( (p->flags2 & EP2_MallocedToken)==0 );
67091    assert( (p->flags2 & EP2_Irreducible)==0 );
67092    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
67093      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
67094    }else{
67095      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
67096    }
67097  }
67098  return nSize;
67099}
67100
67101/*
67102** This function returns the space in bytes required to store the copy
67103** of the Expr structure and a copy of the Expr.u.zToken string (if that
67104** string is defined.)
67105*/
67106static int dupedExprNodeSize(Expr *p, int flags){
67107  int nByte = dupedExprStructSize(p, flags) & 0xfff;
67108  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67109    nByte += sqlite3Strlen30(p->u.zToken)+1;
67110  }
67111  return ROUND8(nByte);
67112}
67113
67114/*
67115** Return the number of bytes required to create a duplicate of the
67116** expression passed as the first argument. The second argument is a
67117** mask containing EXPRDUP_XXX flags.
67118**
67119** The value returned includes space to create a copy of the Expr struct
67120** itself and the buffer referred to by Expr.u.zToken, if any.
67121**
67122** If the EXPRDUP_REDUCE flag is set, then the return value includes
67123** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
67124** and Expr.pRight variables (but not for any structures pointed to or
67125** descended from the Expr.x.pList or Expr.x.pSelect variables).
67126*/
67127static int dupedExprSize(Expr *p, int flags){
67128  int nByte = 0;
67129  if( p ){
67130    nByte = dupedExprNodeSize(p, flags);
67131    if( flags&EXPRDUP_REDUCE ){
67132      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
67133    }
67134  }
67135  return nByte;
67136}
67137
67138/*
67139** This function is similar to sqlite3ExprDup(), except that if pzBuffer
67140** is not NULL then *pzBuffer is assumed to point to a buffer large enough
67141** to store the copy of expression p, the copies of p->u.zToken
67142** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
67143** if any. Before returning, *pzBuffer is set to the first byte passed the
67144** portion of the buffer copied into by this function.
67145*/
67146static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
67147  Expr *pNew = 0;                      /* Value to return */
67148  if( p ){
67149    const int isReduced = (flags&EXPRDUP_REDUCE);
67150    u8 *zAlloc;
67151    u32 staticFlag = 0;
67152
67153    assert( pzBuffer==0 || isReduced );
67154
67155    /* Figure out where to write the new Expr structure. */
67156    if( pzBuffer ){
67157      zAlloc = *pzBuffer;
67158      staticFlag = EP_Static;
67159    }else{
67160      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
67161    }
67162    pNew = (Expr *)zAlloc;
67163
67164    if( pNew ){
67165      /* Set nNewSize to the size allocated for the structure pointed to
67166      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
67167      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
67168      ** by the copy of the p->u.zToken string (if any).
67169      */
67170      const unsigned nStructSize = dupedExprStructSize(p, flags);
67171      const int nNewSize = nStructSize & 0xfff;
67172      int nToken;
67173      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67174        nToken = sqlite3Strlen30(p->u.zToken) + 1;
67175      }else{
67176        nToken = 0;
67177      }
67178      if( isReduced ){
67179        assert( ExprHasProperty(p, EP_Reduced)==0 );
67180        memcpy(zAlloc, p, nNewSize);
67181      }else{
67182        int nSize = exprStructSize(p);
67183        memcpy(zAlloc, p, nSize);
67184        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
67185      }
67186
67187      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
67188      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
67189      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
67190      pNew->flags |= staticFlag;
67191
67192      /* Copy the p->u.zToken string, if any. */
67193      if( nToken ){
67194        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
67195        memcpy(zToken, p->u.zToken, nToken);
67196      }
67197
67198      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
67199        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
67200        if( ExprHasProperty(p, EP_xIsSelect) ){
67201          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
67202        }else{
67203          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
67204        }
67205      }
67206
67207      /* Fill in pNew->pLeft and pNew->pRight. */
67208      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
67209        zAlloc += dupedExprNodeSize(p, flags);
67210        if( ExprHasProperty(pNew, EP_Reduced) ){
67211          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
67212          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
67213        }
67214        if( pzBuffer ){
67215          *pzBuffer = zAlloc;
67216        }
67217      }else{
67218        pNew->flags2 = 0;
67219        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67220          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
67221          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
67222        }
67223      }
67224
67225    }
67226  }
67227  return pNew;
67228}
67229
67230/*
67231** The following group of routines make deep copies of expressions,
67232** expression lists, ID lists, and select statements.  The copies can
67233** be deleted (by being passed to their respective ...Delete() routines)
67234** without effecting the originals.
67235**
67236** The expression list, ID, and source lists return by sqlite3ExprListDup(),
67237** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
67238** by subsequent calls to sqlite*ListAppend() routines.
67239**
67240** Any tables that the SrcList might point to are not duplicated.
67241**
67242** The flags parameter contains a combination of the EXPRDUP_XXX flags.
67243** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
67244** truncated version of the usual Expr structure that will be stored as
67245** part of the in-memory representation of the database schema.
67246*/
67247SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
67248  return exprDup(db, p, flags, 0);
67249}
67250SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
67251  ExprList *pNew;
67252  struct ExprList_item *pItem, *pOldItem;
67253  int i;
67254  if( p==0 ) return 0;
67255  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67256  if( pNew==0 ) return 0;
67257  pNew->iECursor = 0;
67258  pNew->nExpr = pNew->nAlloc = p->nExpr;
67259  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
67260  if( pItem==0 ){
67261    sqlite3DbFree(db, pNew);
67262    return 0;
67263  }
67264  pOldItem = p->a;
67265  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
67266    Expr *pOldExpr = pOldItem->pExpr;
67267    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
67268    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67269    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
67270    pItem->sortOrder = pOldItem->sortOrder;
67271    pItem->done = 0;
67272    pItem->iCol = pOldItem->iCol;
67273    pItem->iAlias = pOldItem->iAlias;
67274  }
67275  return pNew;
67276}
67277
67278/*
67279** If cursors, triggers, views and subqueries are all omitted from
67280** the build, then none of the following routines, except for
67281** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
67282** called with a NULL argument.
67283*/
67284#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
67285 || !defined(SQLITE_OMIT_SUBQUERY)
67286SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
67287  SrcList *pNew;
67288  int i;
67289  int nByte;
67290  if( p==0 ) return 0;
67291  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
67292  pNew = sqlite3DbMallocRaw(db, nByte );
67293  if( pNew==0 ) return 0;
67294  pNew->nSrc = pNew->nAlloc = p->nSrc;
67295  for(i=0; i<p->nSrc; i++){
67296    struct SrcList_item *pNewItem = &pNew->a[i];
67297    struct SrcList_item *pOldItem = &p->a[i];
67298    Table *pTab;
67299    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
67300    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67301    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
67302    pNewItem->jointype = pOldItem->jointype;
67303    pNewItem->iCursor = pOldItem->iCursor;
67304    pNewItem->isPopulated = pOldItem->isPopulated;
67305    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
67306    pNewItem->notIndexed = pOldItem->notIndexed;
67307    pNewItem->pIndex = pOldItem->pIndex;
67308    pTab = pNewItem->pTab = pOldItem->pTab;
67309    if( pTab ){
67310      pTab->nRef++;
67311    }
67312    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
67313    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
67314    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
67315    pNewItem->colUsed = pOldItem->colUsed;
67316  }
67317  return pNew;
67318}
67319SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
67320  IdList *pNew;
67321  int i;
67322  if( p==0 ) return 0;
67323  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67324  if( pNew==0 ) return 0;
67325  pNew->nId = pNew->nAlloc = p->nId;
67326  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
67327  if( pNew->a==0 ){
67328    sqlite3DbFree(db, pNew);
67329    return 0;
67330  }
67331  for(i=0; i<p->nId; i++){
67332    struct IdList_item *pNewItem = &pNew->a[i];
67333    struct IdList_item *pOldItem = &p->a[i];
67334    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67335    pNewItem->idx = pOldItem->idx;
67336  }
67337  return pNew;
67338}
67339SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67340  Select *pNew;
67341  if( p==0 ) return 0;
67342  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
67343  if( pNew==0 ) return 0;
67344  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
67345  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
67346  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
67347  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
67348  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
67349  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
67350  pNew->op = p->op;
67351  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
67352  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
67353  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
67354  pNew->iLimit = 0;
67355  pNew->iOffset = 0;
67356  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
67357  pNew->pRightmost = 0;
67358  pNew->addrOpenEphm[0] = -1;
67359  pNew->addrOpenEphm[1] = -1;
67360  pNew->addrOpenEphm[2] = -1;
67361  return pNew;
67362}
67363#else
67364SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67365  assert( p==0 );
67366  return 0;
67367}
67368#endif
67369
67370
67371/*
67372** Add a new element to the end of an expression list.  If pList is
67373** initially NULL, then create a new expression list.
67374**
67375** If a memory allocation error occurs, the entire list is freed and
67376** NULL is returned.  If non-NULL is returned, then it is guaranteed
67377** that the new entry was successfully appended.
67378*/
67379SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
67380  Parse *pParse,          /* Parsing context */
67381  ExprList *pList,        /* List to which to append. Might be NULL */
67382  Expr *pExpr             /* Expression to be appended. Might be NULL */
67383){
67384  sqlite3 *db = pParse->db;
67385  if( pList==0 ){
67386    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
67387    if( pList==0 ){
67388      goto no_mem;
67389    }
67390    assert( pList->nAlloc==0 );
67391  }
67392  if( pList->nAlloc<=pList->nExpr ){
67393    struct ExprList_item *a;
67394    int n = pList->nAlloc*2 + 4;
67395    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
67396    if( a==0 ){
67397      goto no_mem;
67398    }
67399    pList->a = a;
67400    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
67401  }
67402  assert( pList->a!=0 );
67403  if( 1 ){
67404    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
67405    memset(pItem, 0, sizeof(*pItem));
67406    pItem->pExpr = pExpr;
67407  }
67408  return pList;
67409
67410no_mem:
67411  /* Avoid leaking memory if malloc has failed. */
67412  sqlite3ExprDelete(db, pExpr);
67413  sqlite3ExprListDelete(db, pList);
67414  return 0;
67415}
67416
67417/*
67418** Set the ExprList.a[].zName element of the most recently added item
67419** on the expression list.
67420**
67421** pList might be NULL following an OOM error.  But pName should never be
67422** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67423** is set.
67424*/
67425SQLITE_PRIVATE void sqlite3ExprListSetName(
67426  Parse *pParse,          /* Parsing context */
67427  ExprList *pList,        /* List to which to add the span. */
67428  Token *pName,           /* Name to be added */
67429  int dequote             /* True to cause the name to be dequoted */
67430){
67431  assert( pList!=0 || pParse->db->mallocFailed!=0 );
67432  if( pList ){
67433    struct ExprList_item *pItem;
67434    assert( pList->nExpr>0 );
67435    pItem = &pList->a[pList->nExpr-1];
67436    assert( pItem->zName==0 );
67437    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
67438    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
67439  }
67440}
67441
67442/*
67443** Set the ExprList.a[].zSpan element of the most recently added item
67444** on the expression list.
67445**
67446** pList might be NULL following an OOM error.  But pSpan should never be
67447** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67448** is set.
67449*/
67450SQLITE_PRIVATE void sqlite3ExprListSetSpan(
67451  Parse *pParse,          /* Parsing context */
67452  ExprList *pList,        /* List to which to add the span. */
67453  ExprSpan *pSpan         /* The span to be added */
67454){
67455  sqlite3 *db = pParse->db;
67456  assert( pList!=0 || db->mallocFailed!=0 );
67457  if( pList ){
67458    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
67459    assert( pList->nExpr>0 );
67460    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
67461    sqlite3DbFree(db, pItem->zSpan);
67462    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67463                                    (int)(pSpan->zEnd - pSpan->zStart));
67464  }
67465}
67466
67467/*
67468** If the expression list pEList contains more than iLimit elements,
67469** leave an error message in pParse.
67470*/
67471SQLITE_PRIVATE void sqlite3ExprListCheckLength(
67472  Parse *pParse,
67473  ExprList *pEList,
67474  const char *zObject
67475){
67476  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
67477  testcase( pEList && pEList->nExpr==mx );
67478  testcase( pEList && pEList->nExpr==mx+1 );
67479  if( pEList && pEList->nExpr>mx ){
67480    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
67481  }
67482}
67483
67484/*
67485** Delete an entire expression list.
67486*/
67487SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
67488  int i;
67489  struct ExprList_item *pItem;
67490  if( pList==0 ) return;
67491  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
67492  assert( pList->nExpr<=pList->nAlloc );
67493  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
67494    sqlite3ExprDelete(db, pItem->pExpr);
67495    sqlite3DbFree(db, pItem->zName);
67496    sqlite3DbFree(db, pItem->zSpan);
67497  }
67498  sqlite3DbFree(db, pList->a);
67499  sqlite3DbFree(db, pList);
67500}
67501
67502/*
67503** These routines are Walker callbacks.  Walker.u.pi is a pointer
67504** to an integer.  These routines are checking an expression to see
67505** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
67506** not constant.
67507**
67508** These callback routines are used to implement the following:
67509**
67510**     sqlite3ExprIsConstant()
67511**     sqlite3ExprIsConstantNotJoin()
67512**     sqlite3ExprIsConstantOrFunction()
67513**
67514*/
67515static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
67516
67517  /* If pWalker->u.i is 3 then any term of the expression that comes from
67518  ** the ON or USING clauses of a join disqualifies the expression
67519  ** from being considered constant. */
67520  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
67521    pWalker->u.i = 0;
67522    return WRC_Abort;
67523  }
67524
67525  switch( pExpr->op ){
67526    /* Consider functions to be constant if all their arguments are constant
67527    ** and pWalker->u.i==2 */
67528    case TK_FUNCTION:
67529      if( pWalker->u.i==2 ) return 0;
67530      /* Fall through */
67531    case TK_ID:
67532    case TK_COLUMN:
67533    case TK_AGG_FUNCTION:
67534    case TK_AGG_COLUMN:
67535      testcase( pExpr->op==TK_ID );
67536      testcase( pExpr->op==TK_COLUMN );
67537      testcase( pExpr->op==TK_AGG_FUNCTION );
67538      testcase( pExpr->op==TK_AGG_COLUMN );
67539      pWalker->u.i = 0;
67540      return WRC_Abort;
67541    default:
67542      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
67543      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
67544      return WRC_Continue;
67545  }
67546}
67547static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
67548  UNUSED_PARAMETER(NotUsed);
67549  pWalker->u.i = 0;
67550  return WRC_Abort;
67551}
67552static int exprIsConst(Expr *p, int initFlag){
67553  Walker w;
67554  w.u.i = initFlag;
67555  w.xExprCallback = exprNodeIsConstant;
67556  w.xSelectCallback = selectNodeIsConstant;
67557  sqlite3WalkExpr(&w, p);
67558  return w.u.i;
67559}
67560
67561/*
67562** Walk an expression tree.  Return 1 if the expression is constant
67563** and 0 if it involves variables or function calls.
67564**
67565** For the purposes of this function, a double-quoted string (ex: "abc")
67566** is considered a variable but a single-quoted string (ex: 'abc') is
67567** a constant.
67568*/
67569SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
67570  return exprIsConst(p, 1);
67571}
67572
67573/*
67574** Walk an expression tree.  Return 1 if the expression is constant
67575** that does no originate from the ON or USING clauses of a join.
67576** Return 0 if it involves variables or function calls or terms from
67577** an ON or USING clause.
67578*/
67579SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
67580  return exprIsConst(p, 3);
67581}
67582
67583/*
67584** Walk an expression tree.  Return 1 if the expression is constant
67585** or a function call with constant arguments.  Return and 0 if there
67586** are any variables.
67587**
67588** For the purposes of this function, a double-quoted string (ex: "abc")
67589** is considered a variable but a single-quoted string (ex: 'abc') is
67590** a constant.
67591*/
67592SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
67593  return exprIsConst(p, 2);
67594}
67595
67596/*
67597** If the expression p codes a constant integer that is small enough
67598** to fit in a 32-bit integer, return 1 and put the value of the integer
67599** in *pValue.  If the expression is not an integer or if it is too big
67600** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
67601*/
67602SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
67603  int rc = 0;
67604  if( p->flags & EP_IntValue ){
67605    *pValue = p->u.iValue;
67606    return 1;
67607  }
67608  switch( p->op ){
67609    case TK_INTEGER: {
67610      rc = sqlite3GetInt32(p->u.zToken, pValue);
67611      assert( rc==0 );
67612      break;
67613    }
67614    case TK_UPLUS: {
67615      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
67616      break;
67617    }
67618    case TK_UMINUS: {
67619      int v;
67620      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
67621        *pValue = -v;
67622        rc = 1;
67623      }
67624      break;
67625    }
67626    default: break;
67627  }
67628  if( rc ){
67629    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
67630               || (p->flags2 & EP2_MallocedToken)==0 );
67631    p->op = TK_INTEGER;
67632    p->flags |= EP_IntValue;
67633    p->u.iValue = *pValue;
67634  }
67635  return rc;
67636}
67637
67638/*
67639** Return FALSE if there is no chance that the expression can be NULL.
67640**
67641** If the expression might be NULL or if the expression is too complex
67642** to tell return TRUE.
67643**
67644** This routine is used as an optimization, to skip OP_IsNull opcodes
67645** when we know that a value cannot be NULL.  Hence, a false positive
67646** (returning TRUE when in fact the expression can never be NULL) might
67647** be a small performance hit but is otherwise harmless.  On the other
67648** hand, a false negative (returning FALSE when the result could be NULL)
67649** will likely result in an incorrect answer.  So when in doubt, return
67650** TRUE.
67651*/
67652SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
67653  u8 op;
67654  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
67655  op = p->op;
67656  if( op==TK_REGISTER ) op = p->op2;
67657  switch( op ){
67658    case TK_INTEGER:
67659    case TK_STRING:
67660    case TK_FLOAT:
67661    case TK_BLOB:
67662      return 0;
67663    default:
67664      return 1;
67665  }
67666}
67667
67668/*
67669** Generate an OP_IsNull instruction that tests register iReg and jumps
67670** to location iDest if the value in iReg is NULL.  The value in iReg
67671** was computed by pExpr.  If we can look at pExpr at compile-time and
67672** determine that it can never generate a NULL, then the OP_IsNull operation
67673** can be omitted.
67674*/
67675SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
67676  Vdbe *v,            /* The VDBE under construction */
67677  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
67678  int iReg,           /* Test the value in this register for NULL */
67679  int iDest           /* Jump here if the value is null */
67680){
67681  if( sqlite3ExprCanBeNull(pExpr) ){
67682    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
67683  }
67684}
67685
67686/*
67687** Return TRUE if the given expression is a constant which would be
67688** unchanged by OP_Affinity with the affinity given in the second
67689** argument.
67690**
67691** This routine is used to determine if the OP_Affinity operation
67692** can be omitted.  When in doubt return FALSE.  A false negative
67693** is harmless.  A false positive, however, can result in the wrong
67694** answer.
67695*/
67696SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
67697  u8 op;
67698  if( aff==SQLITE_AFF_NONE ) return 1;
67699  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
67700  op = p->op;
67701  if( op==TK_REGISTER ) op = p->op2;
67702  switch( op ){
67703    case TK_INTEGER: {
67704      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
67705    }
67706    case TK_FLOAT: {
67707      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
67708    }
67709    case TK_STRING: {
67710      return aff==SQLITE_AFF_TEXT;
67711    }
67712    case TK_BLOB: {
67713      return 1;
67714    }
67715    case TK_COLUMN: {
67716      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
67717      return p->iColumn<0
67718          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
67719    }
67720    default: {
67721      return 0;
67722    }
67723  }
67724}
67725
67726/*
67727** Return TRUE if the given string is a row-id column name.
67728*/
67729SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
67730  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
67731  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
67732  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
67733  return 0;
67734}
67735
67736/*
67737** Return true if we are able to the IN operator optimization on a
67738** query of the form
67739**
67740**       x IN (SELECT ...)
67741**
67742** Where the SELECT... clause is as specified by the parameter to this
67743** routine.
67744**
67745** The Select object passed in has already been preprocessed and no
67746** errors have been found.
67747*/
67748#ifndef SQLITE_OMIT_SUBQUERY
67749static int isCandidateForInOpt(Select *p){
67750  SrcList *pSrc;
67751  ExprList *pEList;
67752  Table *pTab;
67753  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
67754  if( p->pPrior ) return 0;              /* Not a compound SELECT */
67755  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
67756    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
67757    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
67758    return 0; /* No DISTINCT keyword and no aggregate functions */
67759  }
67760  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
67761  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
67762  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
67763  if( p->pWhere ) return 0;              /* Has no WHERE clause */
67764  pSrc = p->pSrc;
67765  assert( pSrc!=0 );
67766  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
67767  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
67768  pTab = pSrc->a[0].pTab;
67769  if( NEVER(pTab==0) ) return 0;
67770  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
67771  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
67772  pEList = p->pEList;
67773  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
67774  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
67775  return 1;
67776}
67777#endif /* SQLITE_OMIT_SUBQUERY */
67778
67779/*
67780** This function is used by the implementation of the IN (...) operator.
67781** It's job is to find or create a b-tree structure that may be used
67782** either to test for membership of the (...) set or to iterate through
67783** its members, skipping duplicates.
67784**
67785** The index of the cursor opened on the b-tree (database table, database index
67786** or ephermal table) is stored in pX->iTable before this function returns.
67787** The returned value of this function indicates the b-tree type, as follows:
67788**
67789**   IN_INDEX_ROWID - The cursor was opened on a database table.
67790**   IN_INDEX_INDEX - The cursor was opened on a database index.
67791**   IN_INDEX_EPH -   The cursor was opened on a specially created and
67792**                    populated epheremal table.
67793**
67794** An existing b-tree may only be used if the SELECT is of the simple
67795** form:
67796**
67797**     SELECT <column> FROM <table>
67798**
67799** If the prNotFound parameter is 0, then the b-tree will be used to iterate
67800** through the set members, skipping any duplicates. In this case an
67801** epheremal table must be used unless the selected <column> is guaranteed
67802** to be unique - either because it is an INTEGER PRIMARY KEY or it
67803** has a UNIQUE constraint or UNIQUE index.
67804**
67805** If the prNotFound parameter is not 0, then the b-tree will be used
67806** for fast set membership tests. In this case an epheremal table must
67807** be used unless <column> is an INTEGER PRIMARY KEY or an index can
67808** be found with <column> as its left-most column.
67809**
67810** When the b-tree is being used for membership tests, the calling function
67811** needs to know whether or not the structure contains an SQL NULL
67812** value in order to correctly evaluate expressions like "X IN (Y, Z)".
67813** If there is any chance that the (...) might contain a NULL value at
67814** runtime, then a register is allocated and the register number written
67815** to *prNotFound. If there is no chance that the (...) contains a
67816** NULL value, then *prNotFound is left unchanged.
67817**
67818** If a register is allocated and its location stored in *prNotFound, then
67819** its initial value is NULL.  If the (...) does not remain constant
67820** for the duration of the query (i.e. the SELECT within the (...)
67821** is a correlated subquery) then the value of the allocated register is
67822** reset to NULL each time the subquery is rerun. This allows the
67823** caller to use vdbe code equivalent to the following:
67824**
67825**   if( register==NULL ){
67826**     has_null = <test if data structure contains null>
67827**     register = 1
67828**   }
67829**
67830** in order to avoid running the <test if data structure contains null>
67831** test more often than is necessary.
67832*/
67833#ifndef SQLITE_OMIT_SUBQUERY
67834SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
67835  Select *p;                            /* SELECT to the right of IN operator */
67836  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
67837  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
67838  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
67839
67840  assert( pX->op==TK_IN );
67841
67842  /* Check to see if an existing table or index can be used to
67843  ** satisfy the query.  This is preferable to generating a new
67844  ** ephemeral table.
67845  */
67846  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
67847  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
67848    sqlite3 *db = pParse->db;              /* Database connection */
67849    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
67850    int iCol = pExpr->iColumn;             /* Index of column <column> */
67851    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
67852    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
67853    int iDb;                               /* Database idx for pTab */
67854
67855    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
67856    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67857    sqlite3CodeVerifySchema(pParse, iDb);
67858    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
67859
67860    /* This function is only called from two places. In both cases the vdbe
67861    ** has already been allocated. So assume sqlite3GetVdbe() is always
67862    ** successful here.
67863    */
67864    assert(v);
67865    if( iCol<0 ){
67866      int iMem = ++pParse->nMem;
67867      int iAddr;
67868
67869      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
67870      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
67871
67872      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
67873      eType = IN_INDEX_ROWID;
67874
67875      sqlite3VdbeJumpHere(v, iAddr);
67876    }else{
67877      Index *pIdx;                         /* Iterator variable */
67878
67879      /* The collation sequence used by the comparison. If an index is to
67880      ** be used in place of a temp-table, it must be ordered according
67881      ** to this collation sequence.  */
67882      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
67883
67884      /* Check that the affinity that will be used to perform the
67885      ** comparison is the same as the affinity of the column. If
67886      ** it is not, it is not possible to use any index.
67887      */
67888      char aff = comparisonAffinity(pX);
67889      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
67890
67891      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
67892        if( (pIdx->aiColumn[0]==iCol)
67893         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
67894         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
67895        ){
67896          int iMem = ++pParse->nMem;
67897          int iAddr;
67898          char *pKey;
67899
67900          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
67901          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
67902          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
67903
67904          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
67905                               pKey,P4_KEYINFO_HANDOFF);
67906          VdbeComment((v, "%s", pIdx->zName));
67907          eType = IN_INDEX_INDEX;
67908
67909          sqlite3VdbeJumpHere(v, iAddr);
67910          if( prNotFound && !pTab->aCol[iCol].notNull ){
67911            *prNotFound = ++pParse->nMem;
67912          }
67913        }
67914      }
67915    }
67916  }
67917
67918  if( eType==0 ){
67919    /* Could not found an existing table or index to use as the RHS b-tree.
67920    ** We will have to generate an ephemeral table to do the job.
67921    */
67922    int rMayHaveNull = 0;
67923    eType = IN_INDEX_EPH;
67924    if( prNotFound ){
67925      *prNotFound = rMayHaveNull = ++pParse->nMem;
67926    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
67927      eType = IN_INDEX_ROWID;
67928    }
67929    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
67930  }else{
67931    pX->iTable = iTab;
67932  }
67933  return eType;
67934}
67935#endif
67936
67937/*
67938** Generate code for scalar subqueries used as an expression
67939** and IN operators.  Examples:
67940**
67941**     (SELECT a FROM b)          -- subquery
67942**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
67943**     x IN (4,5,11)              -- IN operator with list on right-hand side
67944**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
67945**
67946** The pExpr parameter describes the expression that contains the IN
67947** operator or subquery.
67948**
67949** If parameter isRowid is non-zero, then expression pExpr is guaranteed
67950** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
67951** to some integer key column of a table B-Tree. In this case, use an
67952** intkey B-Tree to store the set of IN(...) values instead of the usual
67953** (slower) variable length keys B-Tree.
67954**
67955** If rMayHaveNull is non-zero, that means that the operation is an IN
67956** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
67957** Furthermore, the IN is in a WHERE clause and that we really want
67958** to iterate over the RHS of the IN operator in order to quickly locate
67959** all corresponding LHS elements.  All this routine does is initialize
67960** the register given by rMayHaveNull to NULL.  Calling routines will take
67961** care of changing this register value to non-NULL if the RHS is NULL-free.
67962**
67963** If rMayHaveNull is zero, that means that the subquery is being used
67964** for membership testing only.  There is no need to initialize any
67965** registers to indicate the presense or absence of NULLs on the RHS.
67966**
67967** For a SELECT or EXISTS operator, return the register that holds the
67968** result.  For IN operators or if an error occurs, the return value is 0.
67969*/
67970#ifndef SQLITE_OMIT_SUBQUERY
67971SQLITE_PRIVATE int sqlite3CodeSubselect(
67972  Parse *pParse,          /* Parsing context */
67973  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
67974  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
67975  int isRowid             /* If true, LHS of IN operator is a rowid */
67976){
67977  int testAddr = 0;                       /* One-time test address */
67978  int rReg = 0;                           /* Register storing resulting */
67979  Vdbe *v = sqlite3GetVdbe(pParse);
67980  if( NEVER(v==0) ) return 0;
67981  sqlite3ExprCachePush(pParse);
67982
67983  /* This code must be run in its entirety every time it is encountered
67984  ** if any of the following is true:
67985  **
67986  **    *  The right-hand side is a correlated subquery
67987  **    *  The right-hand side is an expression list containing variables
67988  **    *  We are inside a trigger
67989  **
67990  ** If all of the above are false, then we can run this code just once
67991  ** save the results, and reuse the same result on subsequent invocations.
67992  */
67993  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
67994    int mem = ++pParse->nMem;
67995    sqlite3VdbeAddOp1(v, OP_If, mem);
67996    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
67997    assert( testAddr>0 || pParse->db->mallocFailed );
67998  }
67999
68000  switch( pExpr->op ){
68001    case TK_IN: {
68002      char affinity;
68003      KeyInfo keyInfo;
68004      int addr;        /* Address of OP_OpenEphemeral instruction */
68005      Expr *pLeft = pExpr->pLeft;
68006
68007      if( rMayHaveNull ){
68008        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
68009      }
68010
68011      affinity = sqlite3ExprAffinity(pLeft);
68012
68013      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
68014      ** expression it is handled the same way.  An ephemeral table is
68015      ** filled with single-field index keys representing the results
68016      ** from the SELECT or the <exprlist>.
68017      **
68018      ** If the 'x' expression is a column value, or the SELECT...
68019      ** statement returns a column value, then the affinity of that
68020      ** column is used to build the index keys. If both 'x' and the
68021      ** SELECT... statement are columns, then numeric affinity is used
68022      ** if either column has NUMERIC or INTEGER affinity. If neither
68023      ** 'x' nor the SELECT... statement are columns, then numeric affinity
68024      ** is used.
68025      */
68026      pExpr->iTable = pParse->nTab++;
68027      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
68028      memset(&keyInfo, 0, sizeof(keyInfo));
68029      keyInfo.nField = 1;
68030
68031      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68032        /* Case 1:     expr IN (SELECT ...)
68033        **
68034        ** Generate code to write the results of the select into the temporary
68035        ** table allocated and opened above.
68036        */
68037        SelectDest dest;
68038        ExprList *pEList;
68039
68040        assert( !isRowid );
68041        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
68042        dest.affinity = (u8)affinity;
68043        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
68044        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
68045          return 0;
68046        }
68047        pEList = pExpr->x.pSelect->pEList;
68048        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
68049          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
68050              pEList->a[0].pExpr);
68051        }
68052      }else if( pExpr->x.pList!=0 ){
68053        /* Case 2:     expr IN (exprlist)
68054        **
68055        ** For each expression, build an index key from the evaluation and
68056        ** store it in the temporary table. If <expr> is a column, then use
68057        ** that columns affinity when building index keys. If <expr> is not
68058        ** a column, use numeric affinity.
68059        */
68060        int i;
68061        ExprList *pList = pExpr->x.pList;
68062        struct ExprList_item *pItem;
68063        int r1, r2, r3;
68064
68065        if( !affinity ){
68066          affinity = SQLITE_AFF_NONE;
68067        }
68068        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
68069
68070        /* Loop through each expression in <exprlist>. */
68071        r1 = sqlite3GetTempReg(pParse);
68072        r2 = sqlite3GetTempReg(pParse);
68073        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
68074        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
68075          Expr *pE2 = pItem->pExpr;
68076          int iValToIns;
68077
68078          /* If the expression is not constant then we will need to
68079          ** disable the test that was generated above that makes sure
68080          ** this code only executes once.  Because for a non-constant
68081          ** expression we need to rerun this code each time.
68082          */
68083          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
68084            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
68085            testAddr = 0;
68086          }
68087
68088          /* Evaluate the expression and insert it into the temp table */
68089          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
68090            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
68091          }else{
68092            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
68093            if( isRowid ){
68094              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
68095                                sqlite3VdbeCurrentAddr(v)+2);
68096              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
68097            }else{
68098              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
68099              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
68100              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
68101            }
68102          }
68103        }
68104        sqlite3ReleaseTempReg(pParse, r1);
68105        sqlite3ReleaseTempReg(pParse, r2);
68106      }
68107      if( !isRowid ){
68108        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
68109      }
68110      break;
68111    }
68112
68113    case TK_EXISTS:
68114    case TK_SELECT:
68115    default: {
68116      /* If this has to be a scalar SELECT.  Generate code to put the
68117      ** value of this select in a memory cell and record the number
68118      ** of the memory cell in iColumn.  If this is an EXISTS, write
68119      ** an integer 0 (not exists) or 1 (exists) into a memory cell
68120      ** and record that memory cell in iColumn.
68121      */
68122      static const Token one = { "1", 1 };  /* Token for literal value 1 */
68123      Select *pSel;                         /* SELECT statement to encode */
68124      SelectDest dest;                      /* How to deal with SELECt result */
68125
68126      testcase( pExpr->op==TK_EXISTS );
68127      testcase( pExpr->op==TK_SELECT );
68128      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
68129
68130      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
68131      pSel = pExpr->x.pSelect;
68132      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
68133      if( pExpr->op==TK_SELECT ){
68134        dest.eDest = SRT_Mem;
68135        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
68136        VdbeComment((v, "Init subquery result"));
68137      }else{
68138        dest.eDest = SRT_Exists;
68139        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
68140        VdbeComment((v, "Init EXISTS result"));
68141      }
68142      sqlite3ExprDelete(pParse->db, pSel->pLimit);
68143      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
68144      if( sqlite3Select(pParse, pSel, &dest) ){
68145        return 0;
68146      }
68147      rReg = dest.iParm;
68148      ExprSetIrreducible(pExpr);
68149      break;
68150    }
68151  }
68152
68153  if( testAddr ){
68154    sqlite3VdbeJumpHere(v, testAddr-1);
68155  }
68156  sqlite3ExprCachePop(pParse, 1);
68157
68158  return rReg;
68159}
68160#endif /* SQLITE_OMIT_SUBQUERY */
68161
68162#ifndef SQLITE_OMIT_SUBQUERY
68163/*
68164** Generate code for an IN expression.
68165**
68166**      x IN (SELECT ...)
68167**      x IN (value, value, ...)
68168**
68169** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
68170** is an array of zero or more values.  The expression is true if the LHS is
68171** contained within the RHS.  The value of the expression is unknown (NULL)
68172** if the LHS is NULL or if the LHS is not contained within the RHS and the
68173** RHS contains one or more NULL values.
68174**
68175** This routine generates code will jump to destIfFalse if the LHS is not
68176** contained within the RHS.  If due to NULLs we cannot determine if the LHS
68177** is contained in the RHS then jump to destIfNull.  If the LHS is contained
68178** within the RHS then fall through.
68179*/
68180static void sqlite3ExprCodeIN(
68181  Parse *pParse,        /* Parsing and code generating context */
68182  Expr *pExpr,          /* The IN expression */
68183  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
68184  int destIfNull        /* Jump here if the results are unknown due to NULLs */
68185){
68186  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
68187  char affinity;        /* Comparison affinity to use */
68188  int eType;            /* Type of the RHS */
68189  int r1;               /* Temporary use register */
68190  Vdbe *v;              /* Statement under construction */
68191
68192  /* Compute the RHS.   After this step, the table with cursor
68193  ** pExpr->iTable will contains the values that make up the RHS.
68194  */
68195  v = pParse->pVdbe;
68196  assert( v!=0 );       /* OOM detected prior to this routine */
68197  VdbeNoopComment((v, "begin IN expr"));
68198  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
68199
68200  /* Figure out the affinity to use to create a key from the results
68201  ** of the expression. affinityStr stores a static string suitable for
68202  ** P4 of OP_MakeRecord.
68203  */
68204  affinity = comparisonAffinity(pExpr);
68205
68206  /* Code the LHS, the <expr> from "<expr> IN (...)".
68207  */
68208  sqlite3ExprCachePush(pParse);
68209  r1 = sqlite3GetTempReg(pParse);
68210  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
68211  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
68212
68213
68214  if( eType==IN_INDEX_ROWID ){
68215    /* In this case, the RHS is the ROWID of table b-tree
68216    */
68217    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
68218    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
68219  }else{
68220    /* In this case, the RHS is an index b-tree.
68221    */
68222    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
68223
68224    /* If the set membership test fails, then the result of the
68225    ** "x IN (...)" expression must be either 0 or NULL. If the set
68226    ** contains no NULL values, then the result is 0. If the set
68227    ** contains one or more NULL values, then the result of the
68228    ** expression is also NULL.
68229    */
68230    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
68231      /* This branch runs if it is known at compile time that the RHS
68232      ** cannot contain NULL values. This happens as the result
68233      ** of a "NOT NULL" constraint in the database schema.
68234      **
68235      ** Also run this branch if NULL is equivalent to FALSE
68236      ** for this particular IN operator.
68237      */
68238      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
68239
68240    }else{
68241      /* In this branch, the RHS of the IN might contain a NULL and
68242      ** the presence of a NULL on the RHS makes a difference in the
68243      ** outcome.
68244      */
68245      int j1, j2, j3;
68246
68247      /* First check to see if the LHS is contained in the RHS.  If so,
68248      ** then the presence of NULLs in the RHS does not matter, so jump
68249      ** over all of the code that follows.
68250      */
68251      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
68252
68253      /* Here we begin generating code that runs if the LHS is not
68254      ** contained within the RHS.  Generate additional code that
68255      ** tests the RHS for NULLs.  If the RHS contains a NULL then
68256      ** jump to destIfNull.  If there are no NULLs in the RHS then
68257      ** jump to destIfFalse.
68258      */
68259      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
68260      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
68261      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
68262      sqlite3VdbeJumpHere(v, j3);
68263      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
68264      sqlite3VdbeJumpHere(v, j2);
68265
68266      /* Jump to the appropriate target depending on whether or not
68267      ** the RHS contains a NULL
68268      */
68269      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
68270      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
68271
68272      /* The OP_Found at the top of this branch jumps here when true,
68273      ** causing the overall IN expression evaluation to fall through.
68274      */
68275      sqlite3VdbeJumpHere(v, j1);
68276    }
68277  }
68278  sqlite3ReleaseTempReg(pParse, r1);
68279  sqlite3ExprCachePop(pParse, 1);
68280  VdbeComment((v, "end IN expr"));
68281}
68282#endif /* SQLITE_OMIT_SUBQUERY */
68283
68284/*
68285** Duplicate an 8-byte value
68286*/
68287static char *dup8bytes(Vdbe *v, const char *in){
68288  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
68289  if( out ){
68290    memcpy(out, in, 8);
68291  }
68292  return out;
68293}
68294
68295#ifndef SQLITE_OMIT_FLOATING_POINT
68296/*
68297** Generate an instruction that will put the floating point
68298** value described by z[0..n-1] into register iMem.
68299**
68300** The z[] string will probably not be zero-terminated.  But the
68301** z[n] character is guaranteed to be something that does not look
68302** like the continuation of the number.
68303*/
68304static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
68305  if( ALWAYS(z!=0) ){
68306    double value;
68307    char *zV;
68308    sqlite3AtoF(z, &value);
68309    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
68310    if( negateFlag ) value = -value;
68311    zV = dup8bytes(v, (char*)&value);
68312    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
68313  }
68314}
68315#endif
68316
68317
68318/*
68319** Generate an instruction that will put the integer describe by
68320** text z[0..n-1] into register iMem.
68321**
68322** The z[] string will probably not be zero-terminated.  But the
68323** z[n] character is guaranteed to be something that does not look
68324** like the continuation of the number.
68325*/
68326static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
68327  Vdbe *v = pParse->pVdbe;
68328  if( pExpr->flags & EP_IntValue ){
68329    int i = pExpr->u.iValue;
68330    if( negFlag ) i = -i;
68331    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
68332  }else{
68333    const char *z = pExpr->u.zToken;
68334    assert( z!=0 );
68335    if( sqlite3FitsIn64Bits(z, negFlag) ){
68336      i64 value;
68337      char *zV;
68338      sqlite3Atoi64(z, &value);
68339      if( negFlag ) value = -value;
68340      zV = dup8bytes(v, (char*)&value);
68341      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
68342    }else{
68343#ifdef SQLITE_OMIT_FLOATING_POINT
68344      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
68345#else
68346      codeReal(v, z, negFlag, iMem);
68347#endif
68348    }
68349  }
68350}
68351
68352/*
68353** Clear a cache entry.
68354*/
68355static void cacheEntryClear(Parse *pParse, struct yColCache *p){
68356  if( p->tempReg ){
68357    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
68358      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
68359    }
68360    p->tempReg = 0;
68361  }
68362}
68363
68364
68365/*
68366** Record in the column cache that a particular column from a
68367** particular table is stored in a particular register.
68368*/
68369SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
68370  int i;
68371  int minLru;
68372  int idxLru;
68373  struct yColCache *p;
68374
68375  assert( iReg>0 );  /* Register numbers are always positive */
68376  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
68377
68378  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
68379  ** for testing only - to verify that SQLite always gets the same answer
68380  ** with and without the column cache.
68381  */
68382  if( pParse->db->flags & SQLITE_ColumnCache ) return;
68383
68384  /* First replace any existing entry.
68385  **
68386  ** Actually, the way the column cache is currently used, we are guaranteed
68387  ** that the object will never already be in cache.  Verify this guarantee.
68388  */
68389#ifndef NDEBUG
68390  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68391#if 0 /* This code wold remove the entry from the cache if it existed */
68392    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
68393      cacheEntryClear(pParse, p);
68394      p->iLevel = pParse->iCacheLevel;
68395      p->iReg = iReg;
68396      p->lru = pParse->iCacheCnt++;
68397      return;
68398    }
68399#endif
68400    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
68401  }
68402#endif
68403
68404  /* Find an empty slot and replace it */
68405  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68406    if( p->iReg==0 ){
68407      p->iLevel = pParse->iCacheLevel;
68408      p->iTable = iTab;
68409      p->iColumn = iCol;
68410      p->iReg = iReg;
68411      p->tempReg = 0;
68412      p->lru = pParse->iCacheCnt++;
68413      return;
68414    }
68415  }
68416
68417  /* Replace the last recently used */
68418  minLru = 0x7fffffff;
68419  idxLru = -1;
68420  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68421    if( p->lru<minLru ){
68422      idxLru = i;
68423      minLru = p->lru;
68424    }
68425  }
68426  if( ALWAYS(idxLru>=0) ){
68427    p = &pParse->aColCache[idxLru];
68428    p->iLevel = pParse->iCacheLevel;
68429    p->iTable = iTab;
68430    p->iColumn = iCol;
68431    p->iReg = iReg;
68432    p->tempReg = 0;
68433    p->lru = pParse->iCacheCnt++;
68434    return;
68435  }
68436}
68437
68438/*
68439** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
68440** Purge the range of registers from the column cache.
68441*/
68442SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
68443  int i;
68444  int iLast = iReg + nReg - 1;
68445  struct yColCache *p;
68446  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68447    int r = p->iReg;
68448    if( r>=iReg && r<=iLast ){
68449      cacheEntryClear(pParse, p);
68450      p->iReg = 0;
68451    }
68452  }
68453}
68454
68455/*
68456** Remember the current column cache context.  Any new entries added
68457** added to the column cache after this call are removed when the
68458** corresponding pop occurs.
68459*/
68460SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
68461  pParse->iCacheLevel++;
68462}
68463
68464/*
68465** Remove from the column cache any entries that were added since the
68466** the previous N Push operations.  In other words, restore the cache
68467** to the state it was in N Pushes ago.
68468*/
68469SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
68470  int i;
68471  struct yColCache *p;
68472  assert( N>0 );
68473  assert( pParse->iCacheLevel>=N );
68474  pParse->iCacheLevel -= N;
68475  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68476    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
68477      cacheEntryClear(pParse, p);
68478      p->iReg = 0;
68479    }
68480  }
68481}
68482
68483/*
68484** When a cached column is reused, make sure that its register is
68485** no longer available as a temp register.  ticket #3879:  that same
68486** register might be in the cache in multiple places, so be sure to
68487** get them all.
68488*/
68489static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
68490  int i;
68491  struct yColCache *p;
68492  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68493    if( p->iReg==iReg ){
68494      p->tempReg = 0;
68495    }
68496  }
68497}
68498
68499/*
68500** Generate code to extract the value of the iCol-th column of a table.
68501*/
68502SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
68503  Vdbe *v,        /* The VDBE under construction */
68504  Table *pTab,    /* The table containing the value */
68505  int iTabCur,    /* The cursor for this table */
68506  int iCol,       /* Index of the column to extract */
68507  int regOut      /* Extract the valud into this register */
68508){
68509  if( iCol<0 || iCol==pTab->iPKey ){
68510    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
68511  }else{
68512    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
68513    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
68514  }
68515  if( iCol>=0 ){
68516    sqlite3ColumnDefault(v, pTab, iCol, regOut);
68517  }
68518}
68519
68520/*
68521** Generate code that will extract the iColumn-th column from
68522** table pTab and store the column value in a register.  An effort
68523** is made to store the column value in register iReg, but this is
68524** not guaranteed.  The location of the column value is returned.
68525**
68526** There must be an open cursor to pTab in iTable when this routine
68527** is called.  If iColumn<0 then code is generated that extracts the rowid.
68528*/
68529SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
68530  Parse *pParse,   /* Parsing and code generating context */
68531  Table *pTab,     /* Description of the table we are reading from */
68532  int iColumn,     /* Index of the table column */
68533  int iTable,      /* The cursor pointing to the table */
68534  int iReg         /* Store results here */
68535){
68536  Vdbe *v = pParse->pVdbe;
68537  int i;
68538  struct yColCache *p;
68539
68540  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68541    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
68542      p->lru = pParse->iCacheCnt++;
68543      sqlite3ExprCachePinRegister(pParse, p->iReg);
68544      return p->iReg;
68545    }
68546  }
68547  assert( v!=0 );
68548  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
68549  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
68550  return iReg;
68551}
68552
68553/*
68554** Clear all column cache entries.
68555*/
68556SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
68557  int i;
68558  struct yColCache *p;
68559
68560  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68561    if( p->iReg ){
68562      cacheEntryClear(pParse, p);
68563      p->iReg = 0;
68564    }
68565  }
68566}
68567
68568/*
68569** Record the fact that an affinity change has occurred on iCount
68570** registers starting with iStart.
68571*/
68572SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
68573  sqlite3ExprCacheRemove(pParse, iStart, iCount);
68574}
68575
68576/*
68577** Generate code to move content from registers iFrom...iFrom+nReg-1
68578** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
68579*/
68580SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
68581  int i;
68582  struct yColCache *p;
68583  if( NEVER(iFrom==iTo) ) return;
68584  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
68585  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68586    int x = p->iReg;
68587    if( x>=iFrom && x<iFrom+nReg ){
68588      p->iReg += iTo-iFrom;
68589    }
68590  }
68591}
68592
68593/*
68594** Generate code to copy content from registers iFrom...iFrom+nReg-1
68595** over to iTo..iTo+nReg-1.
68596*/
68597SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
68598  int i;
68599  if( NEVER(iFrom==iTo) ) return;
68600  for(i=0; i<nReg; i++){
68601    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
68602  }
68603}
68604
68605#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
68606/*
68607** Return true if any register in the range iFrom..iTo (inclusive)
68608** is used as part of the column cache.
68609**
68610** This routine is used within assert() and testcase() macros only
68611** and does not appear in a normal build.
68612*/
68613static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
68614  int i;
68615  struct yColCache *p;
68616  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68617    int r = p->iReg;
68618    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
68619  }
68620  return 0;
68621}
68622#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
68623
68624/*
68625** If the last instruction coded is an ephemeral copy of any of
68626** the registers in the nReg registers beginning with iReg, then
68627** convert the last instruction from OP_SCopy to OP_Copy.
68628*/
68629SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
68630  VdbeOp *pOp;
68631  Vdbe *v;
68632
68633  assert( pParse->db->mallocFailed==0 );
68634  v = pParse->pVdbe;
68635  assert( v!=0 );
68636  pOp = sqlite3VdbeGetOp(v, -1);
68637  assert( pOp!=0 );
68638  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
68639    pOp->opcode = OP_Copy;
68640  }
68641}
68642
68643/*
68644** Generate code to store the value of the iAlias-th alias in register
68645** target.  The first time this is called, pExpr is evaluated to compute
68646** the value of the alias.  The value is stored in an auxiliary register
68647** and the number of that register is returned.  On subsequent calls,
68648** the register number is returned without generating any code.
68649**
68650** Note that in order for this to work, code must be generated in the
68651** same order that it is executed.
68652**
68653** Aliases are numbered starting with 1.  So iAlias is in the range
68654** of 1 to pParse->nAlias inclusive.
68655**
68656** pParse->aAlias[iAlias-1] records the register number where the value
68657** of the iAlias-th alias is stored.  If zero, that means that the
68658** alias has not yet been computed.
68659*/
68660static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
68661#if 0
68662  sqlite3 *db = pParse->db;
68663  int iReg;
68664  if( pParse->nAliasAlloc<pParse->nAlias ){
68665    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
68666                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
68667    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
68668    if( db->mallocFailed ) return 0;
68669    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
68670           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
68671    pParse->nAliasAlloc = pParse->nAlias;
68672  }
68673  assert( iAlias>0 && iAlias<=pParse->nAlias );
68674  iReg = pParse->aAlias[iAlias-1];
68675  if( iReg==0 ){
68676    if( pParse->iCacheLevel>0 ){
68677      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
68678    }else{
68679      iReg = ++pParse->nMem;
68680      sqlite3ExprCode(pParse, pExpr, iReg);
68681      pParse->aAlias[iAlias-1] = iReg;
68682    }
68683  }
68684  return iReg;
68685#else
68686  UNUSED_PARAMETER(iAlias);
68687  return sqlite3ExprCodeTarget(pParse, pExpr, target);
68688#endif
68689}
68690
68691/*
68692** Generate code into the current Vdbe to evaluate the given
68693** expression.  Attempt to store the results in register "target".
68694** Return the register where results are stored.
68695**
68696** With this routine, there is no guarantee that results will
68697** be stored in target.  The result might be stored in some other
68698** register if it is convenient to do so.  The calling function
68699** must check the return code and move the results to the desired
68700** register.
68701*/
68702SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
68703  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
68704  int op;                   /* The opcode being coded */
68705  int inReg = target;       /* Results stored in register inReg */
68706  int regFree1 = 0;         /* If non-zero free this temporary register */
68707  int regFree2 = 0;         /* If non-zero free this temporary register */
68708  int r1, r2, r3, r4;       /* Various register numbers */
68709  sqlite3 *db = pParse->db; /* The database connection */
68710
68711  assert( target>0 && target<=pParse->nMem );
68712  if( v==0 ){
68713    assert( pParse->db->mallocFailed );
68714    return 0;
68715  }
68716
68717  if( pExpr==0 ){
68718    op = TK_NULL;
68719  }else{
68720    op = pExpr->op;
68721  }
68722  switch( op ){
68723    case TK_AGG_COLUMN: {
68724      AggInfo *pAggInfo = pExpr->pAggInfo;
68725      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
68726      if( !pAggInfo->directMode ){
68727        assert( pCol->iMem>0 );
68728        inReg = pCol->iMem;
68729        break;
68730      }else if( pAggInfo->useSortingIdx ){
68731        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
68732                              pCol->iSorterColumn, target);
68733        break;
68734      }
68735      /* Otherwise, fall thru into the TK_COLUMN case */
68736    }
68737    case TK_COLUMN: {
68738      if( pExpr->iTable<0 ){
68739        /* This only happens when coding check constraints */
68740        assert( pParse->ckBase>0 );
68741        inReg = pExpr->iColumn + pParse->ckBase;
68742      }else{
68743        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
68744                                 pExpr->iColumn, pExpr->iTable, target);
68745      }
68746      break;
68747    }
68748    case TK_INTEGER: {
68749      codeInteger(pParse, pExpr, 0, target);
68750      break;
68751    }
68752#ifndef SQLITE_OMIT_FLOATING_POINT
68753    case TK_FLOAT: {
68754      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68755      codeReal(v, pExpr->u.zToken, 0, target);
68756      break;
68757    }
68758#endif
68759    case TK_STRING: {
68760      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68761      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
68762      break;
68763    }
68764    case TK_NULL: {
68765      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
68766      break;
68767    }
68768#ifndef SQLITE_OMIT_BLOB_LITERAL
68769    case TK_BLOB: {
68770      int n;
68771      const char *z;
68772      char *zBlob;
68773      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68774      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
68775      assert( pExpr->u.zToken[1]=='\'' );
68776      z = &pExpr->u.zToken[2];
68777      n = sqlite3Strlen30(z) - 1;
68778      assert( z[n]=='\'' );
68779      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
68780      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
68781      break;
68782    }
68783#endif
68784    case TK_VARIABLE: {
68785      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68786      assert( pExpr->u.zToken!=0 );
68787      assert( pExpr->u.zToken[0]!=0 );
68788      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
68789      if( pExpr->u.zToken[1]!=0 ){
68790        sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
68791      }
68792      break;
68793    }
68794    case TK_REGISTER: {
68795      inReg = pExpr->iTable;
68796      break;
68797    }
68798    case TK_AS: {
68799      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
68800      break;
68801    }
68802#ifndef SQLITE_OMIT_CAST
68803    case TK_CAST: {
68804      /* Expressions of the form:   CAST(pLeft AS token) */
68805      int aff, to_op;
68806      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
68807      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68808      aff = sqlite3AffinityType(pExpr->u.zToken);
68809      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
68810      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
68811      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
68812      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
68813      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
68814      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
68815      testcase( to_op==OP_ToText );
68816      testcase( to_op==OP_ToBlob );
68817      testcase( to_op==OP_ToNumeric );
68818      testcase( to_op==OP_ToInt );
68819      testcase( to_op==OP_ToReal );
68820      if( inReg!=target ){
68821        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
68822        inReg = target;
68823      }
68824      sqlite3VdbeAddOp1(v, to_op, inReg);
68825      testcase( usedAsColumnCache(pParse, inReg, inReg) );
68826      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
68827      break;
68828    }
68829#endif /* SQLITE_OMIT_CAST */
68830    case TK_LT:
68831    case TK_LE:
68832    case TK_GT:
68833    case TK_GE:
68834    case TK_NE:
68835    case TK_EQ: {
68836      assert( TK_LT==OP_Lt );
68837      assert( TK_LE==OP_Le );
68838      assert( TK_GT==OP_Gt );
68839      assert( TK_GE==OP_Ge );
68840      assert( TK_EQ==OP_Eq );
68841      assert( TK_NE==OP_Ne );
68842      testcase( op==TK_LT );
68843      testcase( op==TK_LE );
68844      testcase( op==TK_GT );
68845      testcase( op==TK_GE );
68846      testcase( op==TK_EQ );
68847      testcase( op==TK_NE );
68848      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
68849      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
68850      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
68851                  r1, r2, inReg, SQLITE_STOREP2);
68852      testcase( regFree1==0 );
68853      testcase( regFree2==0 );
68854      break;
68855    }
68856    case TK_IS:
68857    case TK_ISNOT: {
68858      testcase( op==TK_IS );
68859      testcase( op==TK_ISNOT );
68860      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
68861      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
68862      op = (op==TK_IS) ? TK_EQ : TK_NE;
68863      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
68864                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
68865      testcase( regFree1==0 );
68866      testcase( regFree2==0 );
68867      break;
68868    }
68869    case TK_AND:
68870    case TK_OR:
68871    case TK_PLUS:
68872    case TK_STAR:
68873    case TK_MINUS:
68874    case TK_REM:
68875    case TK_BITAND:
68876    case TK_BITOR:
68877    case TK_SLASH:
68878    case TK_LSHIFT:
68879    case TK_RSHIFT:
68880    case TK_CONCAT: {
68881      assert( TK_AND==OP_And );
68882      assert( TK_OR==OP_Or );
68883      assert( TK_PLUS==OP_Add );
68884      assert( TK_MINUS==OP_Subtract );
68885      assert( TK_REM==OP_Remainder );
68886      assert( TK_BITAND==OP_BitAnd );
68887      assert( TK_BITOR==OP_BitOr );
68888      assert( TK_SLASH==OP_Divide );
68889      assert( TK_LSHIFT==OP_ShiftLeft );
68890      assert( TK_RSHIFT==OP_ShiftRight );
68891      assert( TK_CONCAT==OP_Concat );
68892      testcase( op==TK_AND );
68893      testcase( op==TK_OR );
68894      testcase( op==TK_PLUS );
68895      testcase( op==TK_MINUS );
68896      testcase( op==TK_REM );
68897      testcase( op==TK_BITAND );
68898      testcase( op==TK_BITOR );
68899      testcase( op==TK_SLASH );
68900      testcase( op==TK_LSHIFT );
68901      testcase( op==TK_RSHIFT );
68902      testcase( op==TK_CONCAT );
68903      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
68904      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
68905      sqlite3VdbeAddOp3(v, op, r2, r1, target);
68906      testcase( regFree1==0 );
68907      testcase( regFree2==0 );
68908      break;
68909    }
68910    case TK_UMINUS: {
68911      Expr *pLeft = pExpr->pLeft;
68912      assert( pLeft );
68913      if( pLeft->op==TK_INTEGER ){
68914        codeInteger(pParse, pLeft, 1, target);
68915#ifndef SQLITE_OMIT_FLOATING_POINT
68916      }else if( pLeft->op==TK_FLOAT ){
68917        assert( !ExprHasProperty(pExpr, EP_IntValue) );
68918        codeReal(v, pLeft->u.zToken, 1, target);
68919#endif
68920      }else{
68921        regFree1 = r1 = sqlite3GetTempReg(pParse);
68922        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
68923        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
68924        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
68925        testcase( regFree2==0 );
68926      }
68927      inReg = target;
68928      break;
68929    }
68930    case TK_BITNOT:
68931    case TK_NOT: {
68932      assert( TK_BITNOT==OP_BitNot );
68933      assert( TK_NOT==OP_Not );
68934      testcase( op==TK_BITNOT );
68935      testcase( op==TK_NOT );
68936      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
68937      testcase( regFree1==0 );
68938      inReg = target;
68939      sqlite3VdbeAddOp2(v, op, r1, inReg);
68940      break;
68941    }
68942    case TK_ISNULL:
68943    case TK_NOTNULL: {
68944      int addr;
68945      assert( TK_ISNULL==OP_IsNull );
68946      assert( TK_NOTNULL==OP_NotNull );
68947      testcase( op==TK_ISNULL );
68948      testcase( op==TK_NOTNULL );
68949      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
68950      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
68951      testcase( regFree1==0 );
68952      addr = sqlite3VdbeAddOp1(v, op, r1);
68953      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
68954      sqlite3VdbeJumpHere(v, addr);
68955      break;
68956    }
68957    case TK_AGG_FUNCTION: {
68958      AggInfo *pInfo = pExpr->pAggInfo;
68959      if( pInfo==0 ){
68960        assert( !ExprHasProperty(pExpr, EP_IntValue) );
68961        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
68962      }else{
68963        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
68964      }
68965      break;
68966    }
68967    case TK_CONST_FUNC:
68968    case TK_FUNCTION: {
68969      ExprList *pFarg;       /* List of function arguments */
68970      int nFarg;             /* Number of function arguments */
68971      FuncDef *pDef;         /* The function definition object */
68972      int nId;               /* Length of the function name in bytes */
68973      const char *zId;       /* The function name */
68974      int constMask = 0;     /* Mask of function arguments that are constant */
68975      int i;                 /* Loop counter */
68976      u8 enc = ENC(db);      /* The text encoding used by this database */
68977      CollSeq *pColl = 0;    /* A collating sequence */
68978
68979      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
68980      testcase( op==TK_CONST_FUNC );
68981      testcase( op==TK_FUNCTION );
68982      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
68983        pFarg = 0;
68984      }else{
68985        pFarg = pExpr->x.pList;
68986      }
68987      nFarg = pFarg ? pFarg->nExpr : 0;
68988      assert( !ExprHasProperty(pExpr, EP_IntValue) );
68989      zId = pExpr->u.zToken;
68990      nId = sqlite3Strlen30(zId);
68991      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
68992      if( pDef==0 ){
68993        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
68994        break;
68995      }
68996
68997      /* Attempt a direct implementation of the built-in COALESCE() and
68998      ** IFNULL() functions.  This avoids unnecessary evalation of
68999      ** arguments past the first non-NULL argument.
69000      */
69001      if( pDef->flags & SQLITE_FUNC_COALESCE ){
69002        int endCoalesce = sqlite3VdbeMakeLabel(v);
69003        assert( nFarg>=2 );
69004        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
69005        for(i=1; i<nFarg; i++){
69006          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
69007          sqlite3ExprCacheRemove(pParse, target, 1);
69008          sqlite3ExprCachePush(pParse);
69009          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
69010          sqlite3ExprCachePop(pParse, 1);
69011        }
69012        sqlite3VdbeResolveLabel(v, endCoalesce);
69013        break;
69014      }
69015
69016
69017      if( pFarg ){
69018        r1 = sqlite3GetTempRange(pParse, nFarg);
69019        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
69020        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
69021        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
69022      }else{
69023        r1 = 0;
69024      }
69025#ifndef SQLITE_OMIT_VIRTUALTABLE
69026      /* Possibly overload the function if the first argument is
69027      ** a virtual table column.
69028      **
69029      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
69030      ** second argument, not the first, as the argument to test to
69031      ** see if it is a column in a virtual table.  This is done because
69032      ** the left operand of infix functions (the operand we want to
69033      ** control overloading) ends up as the second argument to the
69034      ** function.  The expression "A glob B" is equivalent to
69035      ** "glob(B,A).  We want to use the A in "A glob B" to test
69036      ** for function overloading.  But we use the B term in "glob(B,A)".
69037      */
69038      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
69039        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
69040      }else if( nFarg>0 ){
69041        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
69042      }
69043#endif
69044      for(i=0; i<nFarg; i++){
69045        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
69046          constMask |= (1<<i);
69047        }
69048        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
69049          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
69050        }
69051      }
69052      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
69053        if( !pColl ) pColl = db->pDfltColl;
69054        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
69055      }
69056      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
69057                        (char*)pDef, P4_FUNCDEF);
69058      sqlite3VdbeChangeP5(v, (u8)nFarg);
69059      if( nFarg ){
69060        sqlite3ReleaseTempRange(pParse, r1, nFarg);
69061      }
69062      break;
69063    }
69064#ifndef SQLITE_OMIT_SUBQUERY
69065    case TK_EXISTS:
69066    case TK_SELECT: {
69067      testcase( op==TK_EXISTS );
69068      testcase( op==TK_SELECT );
69069      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
69070      break;
69071    }
69072    case TK_IN: {
69073      int destIfFalse = sqlite3VdbeMakeLabel(v);
69074      int destIfNull = sqlite3VdbeMakeLabel(v);
69075      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69076      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
69077      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
69078      sqlite3VdbeResolveLabel(v, destIfFalse);
69079      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
69080      sqlite3VdbeResolveLabel(v, destIfNull);
69081      break;
69082    }
69083#endif /* SQLITE_OMIT_SUBQUERY */
69084
69085
69086    /*
69087    **    x BETWEEN y AND z
69088    **
69089    ** This is equivalent to
69090    **
69091    **    x>=y AND x<=z
69092    **
69093    ** X is stored in pExpr->pLeft.
69094    ** Y is stored in pExpr->pList->a[0].pExpr.
69095    ** Z is stored in pExpr->pList->a[1].pExpr.
69096    */
69097    case TK_BETWEEN: {
69098      Expr *pLeft = pExpr->pLeft;
69099      struct ExprList_item *pLItem = pExpr->x.pList->a;
69100      Expr *pRight = pLItem->pExpr;
69101
69102      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
69103      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69104      testcase( regFree1==0 );
69105      testcase( regFree2==0 );
69106      r3 = sqlite3GetTempReg(pParse);
69107      r4 = sqlite3GetTempReg(pParse);
69108      codeCompare(pParse, pLeft, pRight, OP_Ge,
69109                  r1, r2, r3, SQLITE_STOREP2);
69110      pLItem++;
69111      pRight = pLItem->pExpr;
69112      sqlite3ReleaseTempReg(pParse, regFree2);
69113      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69114      testcase( regFree2==0 );
69115      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
69116      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
69117      sqlite3ReleaseTempReg(pParse, r3);
69118      sqlite3ReleaseTempReg(pParse, r4);
69119      break;
69120    }
69121    case TK_UPLUS: {
69122      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
69123      break;
69124    }
69125
69126    case TK_TRIGGER: {
69127      /* If the opcode is TK_TRIGGER, then the expression is a reference
69128      ** to a column in the new.* or old.* pseudo-tables available to
69129      ** trigger programs. In this case Expr.iTable is set to 1 for the
69130      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
69131      ** is set to the column of the pseudo-table to read, or to -1 to
69132      ** read the rowid field.
69133      **
69134      ** The expression is implemented using an OP_Param opcode. The p1
69135      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
69136      ** to reference another column of the old.* pseudo-table, where
69137      ** i is the index of the column. For a new.rowid reference, p1 is
69138      ** set to (n+1), where n is the number of columns in each pseudo-table.
69139      ** For a reference to any other column in the new.* pseudo-table, p1
69140      ** is set to (n+2+i), where n and i are as defined previously. For
69141      ** example, if the table on which triggers are being fired is
69142      ** declared as:
69143      **
69144      **   CREATE TABLE t1(a, b);
69145      **
69146      ** Then p1 is interpreted as follows:
69147      **
69148      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
69149      **   p1==1   ->    old.a         p1==4   ->    new.a
69150      **   p1==2   ->    old.b         p1==5   ->    new.b
69151      */
69152      Table *pTab = pExpr->pTab;
69153      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
69154
69155      assert( pExpr->iTable==0 || pExpr->iTable==1 );
69156      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
69157      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
69158      assert( p1>=0 && p1<(pTab->nCol*2+2) );
69159
69160      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
69161      VdbeComment((v, "%s.%s -> $%d",
69162        (pExpr->iTable ? "new" : "old"),
69163        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
69164        target
69165      ));
69166
69167#ifndef SQLITE_OMIT_FLOATING_POINT
69168      /* If the column has REAL affinity, it may currently be stored as an
69169      ** integer. Use OP_RealAffinity to make sure it is really real.  */
69170      if( pExpr->iColumn>=0
69171       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
69172      ){
69173        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
69174      }
69175#endif
69176      break;
69177    }
69178
69179
69180    /*
69181    ** Form A:
69182    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69183    **
69184    ** Form B:
69185    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69186    **
69187    ** Form A is can be transformed into the equivalent form B as follows:
69188    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
69189    **        WHEN x=eN THEN rN ELSE y END
69190    **
69191    ** X (if it exists) is in pExpr->pLeft.
69192    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
69193    ** ELSE clause and no other term matches, then the result of the
69194    ** exprssion is NULL.
69195    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
69196    **
69197    ** The result of the expression is the Ri for the first matching Ei,
69198    ** or if there is no matching Ei, the ELSE term Y, or if there is
69199    ** no ELSE term, NULL.
69200    */
69201    default: assert( op==TK_CASE ); {
69202      int endLabel;                     /* GOTO label for end of CASE stmt */
69203      int nextCase;                     /* GOTO label for next WHEN clause */
69204      int nExpr;                        /* 2x number of WHEN terms */
69205      int i;                            /* Loop counter */
69206      ExprList *pEList;                 /* List of WHEN terms */
69207      struct ExprList_item *aListelem;  /* Array of WHEN terms */
69208      Expr opCompare;                   /* The X==Ei expression */
69209      Expr cacheX;                      /* Cached expression X */
69210      Expr *pX;                         /* The X expression */
69211      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
69212      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
69213
69214      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
69215      assert((pExpr->x.pList->nExpr % 2) == 0);
69216      assert(pExpr->x.pList->nExpr > 0);
69217      pEList = pExpr->x.pList;
69218      aListelem = pEList->a;
69219      nExpr = pEList->nExpr;
69220      endLabel = sqlite3VdbeMakeLabel(v);
69221      if( (pX = pExpr->pLeft)!=0 ){
69222        cacheX = *pX;
69223        testcase( pX->op==TK_COLUMN );
69224        testcase( pX->op==TK_REGISTER );
69225        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
69226        testcase( regFree1==0 );
69227        cacheX.op = TK_REGISTER;
69228        opCompare.op = TK_EQ;
69229        opCompare.pLeft = &cacheX;
69230        pTest = &opCompare;
69231      }
69232      for(i=0; i<nExpr; i=i+2){
69233        sqlite3ExprCachePush(pParse);
69234        if( pX ){
69235          assert( pTest!=0 );
69236          opCompare.pRight = aListelem[i].pExpr;
69237        }else{
69238          pTest = aListelem[i].pExpr;
69239        }
69240        nextCase = sqlite3VdbeMakeLabel(v);
69241        testcase( pTest->op==TK_COLUMN );
69242        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
69243        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
69244        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
69245        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
69246        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
69247        sqlite3ExprCachePop(pParse, 1);
69248        sqlite3VdbeResolveLabel(v, nextCase);
69249      }
69250      if( pExpr->pRight ){
69251        sqlite3ExprCachePush(pParse);
69252        sqlite3ExprCode(pParse, pExpr->pRight, target);
69253        sqlite3ExprCachePop(pParse, 1);
69254      }else{
69255        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69256      }
69257      assert( db->mallocFailed || pParse->nErr>0
69258           || pParse->iCacheLevel==iCacheLevel );
69259      sqlite3VdbeResolveLabel(v, endLabel);
69260      break;
69261    }
69262#ifndef SQLITE_OMIT_TRIGGER
69263    case TK_RAISE: {
69264      assert( pExpr->affinity==OE_Rollback
69265           || pExpr->affinity==OE_Abort
69266           || pExpr->affinity==OE_Fail
69267           || pExpr->affinity==OE_Ignore
69268      );
69269      if( !pParse->pTriggerTab ){
69270        sqlite3ErrorMsg(pParse,
69271                       "RAISE() may only be used within a trigger-program");
69272        return 0;
69273      }
69274      if( pExpr->affinity==OE_Abort ){
69275        sqlite3MayAbort(pParse);
69276      }
69277      assert( !ExprHasProperty(pExpr, EP_IntValue) );
69278      if( pExpr->affinity==OE_Ignore ){
69279        sqlite3VdbeAddOp4(
69280            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
69281      }else{
69282        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
69283      }
69284
69285      break;
69286    }
69287#endif
69288  }
69289  sqlite3ReleaseTempReg(pParse, regFree1);
69290  sqlite3ReleaseTempReg(pParse, regFree2);
69291  return inReg;
69292}
69293
69294/*
69295** Generate code to evaluate an expression and store the results
69296** into a register.  Return the register number where the results
69297** are stored.
69298**
69299** If the register is a temporary register that can be deallocated,
69300** then write its number into *pReg.  If the result register is not
69301** a temporary, then set *pReg to zero.
69302*/
69303SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
69304  int r1 = sqlite3GetTempReg(pParse);
69305  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69306  if( r2==r1 ){
69307    *pReg = r1;
69308  }else{
69309    sqlite3ReleaseTempReg(pParse, r1);
69310    *pReg = 0;
69311  }
69312  return r2;
69313}
69314
69315/*
69316** Generate code that will evaluate expression pExpr and store the
69317** results in register target.  The results are guaranteed to appear
69318** in register target.
69319*/
69320SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
69321  int inReg;
69322
69323  assert( target>0 && target<=pParse->nMem );
69324  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69325  assert( pParse->pVdbe || pParse->db->mallocFailed );
69326  if( inReg!=target && pParse->pVdbe ){
69327    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
69328  }
69329  return target;
69330}
69331
69332/*
69333** Generate code that evalutes the given expression and puts the result
69334** in register target.
69335**
69336** Also make a copy of the expression results into another "cache" register
69337** and modify the expression so that the next time it is evaluated,
69338** the result is a copy of the cache register.
69339**
69340** This routine is used for expressions that are used multiple
69341** times.  They are evaluated once and the results of the expression
69342** are reused.
69343*/
69344SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
69345  Vdbe *v = pParse->pVdbe;
69346  int inReg;
69347  inReg = sqlite3ExprCode(pParse, pExpr, target);
69348  assert( target>0 );
69349  /* This routine is called for terms to INSERT or UPDATE.  And the only
69350  ** other place where expressions can be converted into TK_REGISTER is
69351  ** in WHERE clause processing.  So as currently implemented, there is
69352  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
69353  ** keep the ALWAYS() in case the conditions above change with future
69354  ** modifications or enhancements. */
69355  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
69356    int iMem;
69357    iMem = ++pParse->nMem;
69358    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
69359    pExpr->iTable = iMem;
69360    pExpr->op2 = pExpr->op;
69361    pExpr->op = TK_REGISTER;
69362  }
69363  return inReg;
69364}
69365
69366/*
69367** Return TRUE if pExpr is an constant expression that is appropriate
69368** for factoring out of a loop.  Appropriate expressions are:
69369**
69370**    *  Any expression that evaluates to two or more opcodes.
69371**
69372**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
69373**       or OP_Variable that does not need to be placed in a
69374**       specific register.
69375**
69376** There is no point in factoring out single-instruction constant
69377** expressions that need to be placed in a particular register.
69378** We could factor them out, but then we would end up adding an
69379** OP_SCopy instruction to move the value into the correct register
69380** later.  We might as well just use the original instruction and
69381** avoid the OP_SCopy.
69382*/
69383static int isAppropriateForFactoring(Expr *p){
69384  if( !sqlite3ExprIsConstantNotJoin(p) ){
69385    return 0;  /* Only constant expressions are appropriate for factoring */
69386  }
69387  if( (p->flags & EP_FixedDest)==0 ){
69388    return 1;  /* Any constant without a fixed destination is appropriate */
69389  }
69390  while( p->op==TK_UPLUS ) p = p->pLeft;
69391  switch( p->op ){
69392#ifndef SQLITE_OMIT_BLOB_LITERAL
69393    case TK_BLOB:
69394#endif
69395    case TK_VARIABLE:
69396    case TK_INTEGER:
69397    case TK_FLOAT:
69398    case TK_NULL:
69399    case TK_STRING: {
69400      testcase( p->op==TK_BLOB );
69401      testcase( p->op==TK_VARIABLE );
69402      testcase( p->op==TK_INTEGER );
69403      testcase( p->op==TK_FLOAT );
69404      testcase( p->op==TK_NULL );
69405      testcase( p->op==TK_STRING );
69406      /* Single-instruction constants with a fixed destination are
69407      ** better done in-line.  If we factor them, they will just end
69408      ** up generating an OP_SCopy to move the value to the destination
69409      ** register. */
69410      return 0;
69411    }
69412    case TK_UMINUS: {
69413      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
69414        return 0;
69415      }
69416      break;
69417    }
69418    default: {
69419      break;
69420    }
69421  }
69422  return 1;
69423}
69424
69425/*
69426** If pExpr is a constant expression that is appropriate for
69427** factoring out of a loop, then evaluate the expression
69428** into a register and convert the expression into a TK_REGISTER
69429** expression.
69430*/
69431static int evalConstExpr(Walker *pWalker, Expr *pExpr){
69432  Parse *pParse = pWalker->pParse;
69433  switch( pExpr->op ){
69434    case TK_IN:
69435    case TK_REGISTER: {
69436      return WRC_Prune;
69437    }
69438    case TK_FUNCTION:
69439    case TK_AGG_FUNCTION:
69440    case TK_CONST_FUNC: {
69441      /* The arguments to a function have a fixed destination.
69442      ** Mark them this way to avoid generated unneeded OP_SCopy
69443      ** instructions.
69444      */
69445      ExprList *pList = pExpr->x.pList;
69446      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69447      if( pList ){
69448        int i = pList->nExpr;
69449        struct ExprList_item *pItem = pList->a;
69450        for(; i>0; i--, pItem++){
69451          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
69452        }
69453      }
69454      break;
69455    }
69456  }
69457  if( isAppropriateForFactoring(pExpr) ){
69458    int r1 = ++pParse->nMem;
69459    int r2;
69460    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69461    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
69462    pExpr->op2 = pExpr->op;
69463    pExpr->op = TK_REGISTER;
69464    pExpr->iTable = r2;
69465    return WRC_Prune;
69466  }
69467  return WRC_Continue;
69468}
69469
69470/*
69471** Preevaluate constant subexpressions within pExpr and store the
69472** results in registers.  Modify pExpr so that the constant subexpresions
69473** are TK_REGISTER opcodes that refer to the precomputed values.
69474*/
69475SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
69476  Walker w;
69477  w.xExprCallback = evalConstExpr;
69478  w.xSelectCallback = 0;
69479  w.pParse = pParse;
69480  sqlite3WalkExpr(&w, pExpr);
69481}
69482
69483
69484/*
69485** Generate code that pushes the value of every element of the given
69486** expression list into a sequence of registers beginning at target.
69487**
69488** Return the number of elements evaluated.
69489*/
69490SQLITE_PRIVATE int sqlite3ExprCodeExprList(
69491  Parse *pParse,     /* Parsing context */
69492  ExprList *pList,   /* The expression list to be coded */
69493  int target,        /* Where to write results */
69494  int doHardCopy     /* Make a hard copy of every element */
69495){
69496  struct ExprList_item *pItem;
69497  int i, n;
69498  assert( pList!=0 );
69499  assert( target>0 );
69500  n = pList->nExpr;
69501  for(pItem=pList->a, i=0; i<n; i++, pItem++){
69502    if( pItem->iAlias ){
69503      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
69504      Vdbe *v = sqlite3GetVdbe(pParse);
69505      if( iReg!=target+i ){
69506        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
69507      }
69508    }else{
69509      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
69510    }
69511    if( doHardCopy && !pParse->db->mallocFailed ){
69512      sqlite3ExprHardCopy(pParse, target, n);
69513    }
69514  }
69515  return n;
69516}
69517
69518/*
69519** Generate code for a BETWEEN operator.
69520**
69521**    x BETWEEN y AND z
69522**
69523** The above is equivalent to
69524**
69525**    x>=y AND x<=z
69526**
69527** Code it as such, taking care to do the common subexpression
69528** elementation of x.
69529*/
69530static void exprCodeBetween(
69531  Parse *pParse,    /* Parsing and code generating context */
69532  Expr *pExpr,      /* The BETWEEN expression */
69533  int dest,         /* Jump here if the jump is taken */
69534  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
69535  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
69536){
69537  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
69538  Expr compLeft;    /* The  x>=y  term */
69539  Expr compRight;   /* The  x<=z  term */
69540  Expr exprX;       /* The  x  subexpression */
69541  int regFree1 = 0; /* Temporary use register */
69542
69543  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69544  exprX = *pExpr->pLeft;
69545  exprAnd.op = TK_AND;
69546  exprAnd.pLeft = &compLeft;
69547  exprAnd.pRight = &compRight;
69548  compLeft.op = TK_GE;
69549  compLeft.pLeft = &exprX;
69550  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
69551  compRight.op = TK_LE;
69552  compRight.pLeft = &exprX;
69553  compRight.pRight = pExpr->x.pList->a[1].pExpr;
69554  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
69555  exprX.op = TK_REGISTER;
69556  if( jumpIfTrue ){
69557    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
69558  }else{
69559    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
69560  }
69561  sqlite3ReleaseTempReg(pParse, regFree1);
69562
69563  /* Ensure adequate test coverage */
69564  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
69565  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
69566  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
69567  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
69568  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
69569  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
69570  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
69571  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
69572}
69573
69574/*
69575** Generate code for a boolean expression such that a jump is made
69576** to the label "dest" if the expression is true but execution
69577** continues straight thru if the expression is false.
69578**
69579** If the expression evaluates to NULL (neither true nor false), then
69580** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
69581**
69582** This code depends on the fact that certain token values (ex: TK_EQ)
69583** are the same as opcode values (ex: OP_Eq) that implement the corresponding
69584** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
69585** the make process cause these values to align.  Assert()s in the code
69586** below verify that the numbers are aligned correctly.
69587*/
69588SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
69589  Vdbe *v = pParse->pVdbe;
69590  int op = 0;
69591  int regFree1 = 0;
69592  int regFree2 = 0;
69593  int r1, r2;
69594
69595  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
69596  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
69597  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
69598  op = pExpr->op;
69599  switch( op ){
69600    case TK_AND: {
69601      int d2 = sqlite3VdbeMakeLabel(v);
69602      testcase( jumpIfNull==0 );
69603      sqlite3ExprCachePush(pParse);
69604      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
69605      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69606      sqlite3VdbeResolveLabel(v, d2);
69607      sqlite3ExprCachePop(pParse, 1);
69608      break;
69609    }
69610    case TK_OR: {
69611      testcase( jumpIfNull==0 );
69612      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
69613      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69614      break;
69615    }
69616    case TK_NOT: {
69617      testcase( jumpIfNull==0 );
69618      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
69619      break;
69620    }
69621    case TK_LT:
69622    case TK_LE:
69623    case TK_GT:
69624    case TK_GE:
69625    case TK_NE:
69626    case TK_EQ: {
69627      assert( TK_LT==OP_Lt );
69628      assert( TK_LE==OP_Le );
69629      assert( TK_GT==OP_Gt );
69630      assert( TK_GE==OP_Ge );
69631      assert( TK_EQ==OP_Eq );
69632      assert( TK_NE==OP_Ne );
69633      testcase( op==TK_LT );
69634      testcase( op==TK_LE );
69635      testcase( op==TK_GT );
69636      testcase( op==TK_GE );
69637      testcase( op==TK_EQ );
69638      testcase( op==TK_NE );
69639      testcase( jumpIfNull==0 );
69640      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69641      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69642      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69643                  r1, r2, dest, jumpIfNull);
69644      testcase( regFree1==0 );
69645      testcase( regFree2==0 );
69646      break;
69647    }
69648    case TK_IS:
69649    case TK_ISNOT: {
69650      testcase( op==TK_IS );
69651      testcase( op==TK_ISNOT );
69652      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69653      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69654      op = (op==TK_IS) ? TK_EQ : TK_NE;
69655      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69656                  r1, r2, dest, SQLITE_NULLEQ);
69657      testcase( regFree1==0 );
69658      testcase( regFree2==0 );
69659      break;
69660    }
69661    case TK_ISNULL:
69662    case TK_NOTNULL: {
69663      assert( TK_ISNULL==OP_IsNull );
69664      assert( TK_NOTNULL==OP_NotNull );
69665      testcase( op==TK_ISNULL );
69666      testcase( op==TK_NOTNULL );
69667      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69668      sqlite3VdbeAddOp2(v, op, r1, dest);
69669      testcase( regFree1==0 );
69670      break;
69671    }
69672    case TK_BETWEEN: {
69673      testcase( jumpIfNull==0 );
69674      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
69675      break;
69676    }
69677    case TK_IN: {
69678      int destIfFalse = sqlite3VdbeMakeLabel(v);
69679      int destIfNull = jumpIfNull ? dest : destIfFalse;
69680      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
69681      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
69682      sqlite3VdbeResolveLabel(v, destIfFalse);
69683      break;
69684    }
69685    default: {
69686      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
69687      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
69688      testcase( regFree1==0 );
69689      testcase( jumpIfNull==0 );
69690      break;
69691    }
69692  }
69693  sqlite3ReleaseTempReg(pParse, regFree1);
69694  sqlite3ReleaseTempReg(pParse, regFree2);
69695}
69696
69697/*
69698** Generate code for a boolean expression such that a jump is made
69699** to the label "dest" if the expression is false but execution
69700** continues straight thru if the expression is true.
69701**
69702** If the expression evaluates to NULL (neither true nor false) then
69703** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
69704** is 0.
69705*/
69706SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
69707  Vdbe *v = pParse->pVdbe;
69708  int op = 0;
69709  int regFree1 = 0;
69710  int regFree2 = 0;
69711  int r1, r2;
69712
69713  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
69714  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
69715  if( pExpr==0 )    return;
69716
69717  /* The value of pExpr->op and op are related as follows:
69718  **
69719  **       pExpr->op            op
69720  **       ---------          ----------
69721  **       TK_ISNULL          OP_NotNull
69722  **       TK_NOTNULL         OP_IsNull
69723  **       TK_NE              OP_Eq
69724  **       TK_EQ              OP_Ne
69725  **       TK_GT              OP_Le
69726  **       TK_LE              OP_Gt
69727  **       TK_GE              OP_Lt
69728  **       TK_LT              OP_Ge
69729  **
69730  ** For other values of pExpr->op, op is undefined and unused.
69731  ** The value of TK_ and OP_ constants are arranged such that we
69732  ** can compute the mapping above using the following expression.
69733  ** Assert()s verify that the computation is correct.
69734  */
69735  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
69736
69737  /* Verify correct alignment of TK_ and OP_ constants
69738  */
69739  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
69740  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
69741  assert( pExpr->op!=TK_NE || op==OP_Eq );
69742  assert( pExpr->op!=TK_EQ || op==OP_Ne );
69743  assert( pExpr->op!=TK_LT || op==OP_Ge );
69744  assert( pExpr->op!=TK_LE || op==OP_Gt );
69745  assert( pExpr->op!=TK_GT || op==OP_Le );
69746  assert( pExpr->op!=TK_GE || op==OP_Lt );
69747
69748  switch( pExpr->op ){
69749    case TK_AND: {
69750      testcase( jumpIfNull==0 );
69751      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
69752      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
69753      break;
69754    }
69755    case TK_OR: {
69756      int d2 = sqlite3VdbeMakeLabel(v);
69757      testcase( jumpIfNull==0 );
69758      sqlite3ExprCachePush(pParse);
69759      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
69760      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
69761      sqlite3VdbeResolveLabel(v, d2);
69762      sqlite3ExprCachePop(pParse, 1);
69763      break;
69764    }
69765    case TK_NOT: {
69766      testcase( jumpIfNull==0 );
69767      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
69768      break;
69769    }
69770    case TK_LT:
69771    case TK_LE:
69772    case TK_GT:
69773    case TK_GE:
69774    case TK_NE:
69775    case TK_EQ: {
69776      testcase( op==TK_LT );
69777      testcase( op==TK_LE );
69778      testcase( op==TK_GT );
69779      testcase( op==TK_GE );
69780      testcase( op==TK_EQ );
69781      testcase( op==TK_NE );
69782      testcase( jumpIfNull==0 );
69783      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69784      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69785      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69786                  r1, r2, dest, jumpIfNull);
69787      testcase( regFree1==0 );
69788      testcase( regFree2==0 );
69789      break;
69790    }
69791    case TK_IS:
69792    case TK_ISNOT: {
69793      testcase( pExpr->op==TK_IS );
69794      testcase( pExpr->op==TK_ISNOT );
69795      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69796      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69797      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
69798      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69799                  r1, r2, dest, SQLITE_NULLEQ);
69800      testcase( regFree1==0 );
69801      testcase( regFree2==0 );
69802      break;
69803    }
69804    case TK_ISNULL:
69805    case TK_NOTNULL: {
69806      testcase( op==TK_ISNULL );
69807      testcase( op==TK_NOTNULL );
69808      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69809      sqlite3VdbeAddOp2(v, op, r1, dest);
69810      testcase( regFree1==0 );
69811      break;
69812    }
69813    case TK_BETWEEN: {
69814      testcase( jumpIfNull==0 );
69815      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
69816      break;
69817    }
69818    case TK_IN: {
69819      if( jumpIfNull ){
69820        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
69821      }else{
69822        int destIfNull = sqlite3VdbeMakeLabel(v);
69823        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
69824        sqlite3VdbeResolveLabel(v, destIfNull);
69825      }
69826      break;
69827    }
69828    default: {
69829      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
69830      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
69831      testcase( regFree1==0 );
69832      testcase( jumpIfNull==0 );
69833      break;
69834    }
69835  }
69836  sqlite3ReleaseTempReg(pParse, regFree1);
69837  sqlite3ReleaseTempReg(pParse, regFree2);
69838}
69839
69840/*
69841** Do a deep comparison of two expression trees.  Return 0 if the two
69842** expressions are completely identical.  Return 1 if they differ only
69843** by a COLLATE operator at the top level.  Return 2 if there are differences
69844** other than the top-level COLLATE operator.
69845**
69846** Sometimes this routine will return 2 even if the two expressions
69847** really are equivalent.  If we cannot prove that the expressions are
69848** identical, we return 2 just to be safe.  So if this routine
69849** returns 2, then you do not really know for certain if the two
69850** expressions are the same.  But if you get a 0 or 1 return, then you
69851** can be sure the expressions are the same.  In the places where
69852** this routine is used, it does not hurt to get an extra 2 - that
69853** just might result in some slightly slower code.  But returning
69854** an incorrect 0 or 1 could lead to a malfunction.
69855*/
69856SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
69857  if( pA==0||pB==0 ){
69858    return pB==pA ? 0 : 2;
69859  }
69860  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
69861  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
69862  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
69863    return 2;
69864  }
69865  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
69866  if( pA->op!=pB->op ) return 2;
69867  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
69868  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
69869  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
69870  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
69871  if( ExprHasProperty(pA, EP_IntValue) ){
69872    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
69873      return 2;
69874    }
69875  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
69876    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
69877    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
69878      return 2;
69879    }
69880  }
69881  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
69882  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
69883  return 0;
69884}
69885
69886/*
69887** Compare two ExprList objects.  Return 0 if they are identical and
69888** non-zero if they differ in any way.
69889**
69890** This routine might return non-zero for equivalent ExprLists.  The
69891** only consequence will be disabled optimizations.  But this routine
69892** must never return 0 if the two ExprList objects are different, or
69893** a malfunction will result.
69894**
69895** Two NULL pointers are considered to be the same.  But a NULL pointer
69896** always differs from a non-NULL pointer.
69897*/
69898SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
69899  int i;
69900  if( pA==0 && pB==0 ) return 0;
69901  if( pA==0 || pB==0 ) return 1;
69902  if( pA->nExpr!=pB->nExpr ) return 1;
69903  for(i=0; i<pA->nExpr; i++){
69904    Expr *pExprA = pA->a[i].pExpr;
69905    Expr *pExprB = pB->a[i].pExpr;
69906    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
69907    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
69908  }
69909  return 0;
69910}
69911
69912/*
69913** Add a new element to the pAggInfo->aCol[] array.  Return the index of
69914** the new element.  Return a negative number if malloc fails.
69915*/
69916static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
69917  int i;
69918  pInfo->aCol = sqlite3ArrayAllocate(
69919       db,
69920       pInfo->aCol,
69921       sizeof(pInfo->aCol[0]),
69922       3,
69923       &pInfo->nColumn,
69924       &pInfo->nColumnAlloc,
69925       &i
69926  );
69927  return i;
69928}
69929
69930/*
69931** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
69932** the new element.  Return a negative number if malloc fails.
69933*/
69934static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
69935  int i;
69936  pInfo->aFunc = sqlite3ArrayAllocate(
69937       db,
69938       pInfo->aFunc,
69939       sizeof(pInfo->aFunc[0]),
69940       3,
69941       &pInfo->nFunc,
69942       &pInfo->nFuncAlloc,
69943       &i
69944  );
69945  return i;
69946}
69947
69948/*
69949** This is the xExprCallback for a tree walker.  It is used to
69950** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
69951** for additional information.
69952*/
69953static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
69954  int i;
69955  NameContext *pNC = pWalker->u.pNC;
69956  Parse *pParse = pNC->pParse;
69957  SrcList *pSrcList = pNC->pSrcList;
69958  AggInfo *pAggInfo = pNC->pAggInfo;
69959
69960  switch( pExpr->op ){
69961    case TK_AGG_COLUMN:
69962    case TK_COLUMN: {
69963      testcase( pExpr->op==TK_AGG_COLUMN );
69964      testcase( pExpr->op==TK_COLUMN );
69965      /* Check to see if the column is in one of the tables in the FROM
69966      ** clause of the aggregate query */
69967      if( ALWAYS(pSrcList!=0) ){
69968        struct SrcList_item *pItem = pSrcList->a;
69969        for(i=0; i<pSrcList->nSrc; i++, pItem++){
69970          struct AggInfo_col *pCol;
69971          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
69972          if( pExpr->iTable==pItem->iCursor ){
69973            /* If we reach this point, it means that pExpr refers to a table
69974            ** that is in the FROM clause of the aggregate query.
69975            **
69976            ** Make an entry for the column in pAggInfo->aCol[] if there
69977            ** is not an entry there already.
69978            */
69979            int k;
69980            pCol = pAggInfo->aCol;
69981            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
69982              if( pCol->iTable==pExpr->iTable &&
69983                  pCol->iColumn==pExpr->iColumn ){
69984                break;
69985              }
69986            }
69987            if( (k>=pAggInfo->nColumn)
69988             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
69989            ){
69990              pCol = &pAggInfo->aCol[k];
69991              pCol->pTab = pExpr->pTab;
69992              pCol->iTable = pExpr->iTable;
69993              pCol->iColumn = pExpr->iColumn;
69994              pCol->iMem = ++pParse->nMem;
69995              pCol->iSorterColumn = -1;
69996              pCol->pExpr = pExpr;
69997              if( pAggInfo->pGroupBy ){
69998                int j, n;
69999                ExprList *pGB = pAggInfo->pGroupBy;
70000                struct ExprList_item *pTerm = pGB->a;
70001                n = pGB->nExpr;
70002                for(j=0; j<n; j++, pTerm++){
70003                  Expr *pE = pTerm->pExpr;
70004                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
70005                      pE->iColumn==pExpr->iColumn ){
70006                    pCol->iSorterColumn = j;
70007                    break;
70008                  }
70009                }
70010              }
70011              if( pCol->iSorterColumn<0 ){
70012                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
70013              }
70014            }
70015            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
70016            ** because it was there before or because we just created it).
70017            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
70018            ** pAggInfo->aCol[] entry.
70019            */
70020            ExprSetIrreducible(pExpr);
70021            pExpr->pAggInfo = pAggInfo;
70022            pExpr->op = TK_AGG_COLUMN;
70023            pExpr->iAgg = (i16)k;
70024            break;
70025          } /* endif pExpr->iTable==pItem->iCursor */
70026        } /* end loop over pSrcList */
70027      }
70028      return WRC_Prune;
70029    }
70030    case TK_AGG_FUNCTION: {
70031      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
70032      ** to be ignored */
70033      if( pNC->nDepth==0 ){
70034        /* Check to see if pExpr is a duplicate of another aggregate
70035        ** function that is already in the pAggInfo structure
70036        */
70037        struct AggInfo_func *pItem = pAggInfo->aFunc;
70038        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
70039          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
70040            break;
70041          }
70042        }
70043        if( i>=pAggInfo->nFunc ){
70044          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
70045          */
70046          u8 enc = ENC(pParse->db);
70047          i = addAggInfoFunc(pParse->db, pAggInfo);
70048          if( i>=0 ){
70049            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70050            pItem = &pAggInfo->aFunc[i];
70051            pItem->pExpr = pExpr;
70052            pItem->iMem = ++pParse->nMem;
70053            assert( !ExprHasProperty(pExpr, EP_IntValue) );
70054            pItem->pFunc = sqlite3FindFunction(pParse->db,
70055                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
70056                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
70057            if( pExpr->flags & EP_Distinct ){
70058              pItem->iDistinct = pParse->nTab++;
70059            }else{
70060              pItem->iDistinct = -1;
70061            }
70062          }
70063        }
70064        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
70065        */
70066        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70067        ExprSetIrreducible(pExpr);
70068        pExpr->iAgg = (i16)i;
70069        pExpr->pAggInfo = pAggInfo;
70070        return WRC_Prune;
70071      }
70072    }
70073  }
70074  return WRC_Continue;
70075}
70076static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
70077  NameContext *pNC = pWalker->u.pNC;
70078  if( pNC->nDepth==0 ){
70079    pNC->nDepth++;
70080    sqlite3WalkSelect(pWalker, pSelect);
70081    pNC->nDepth--;
70082    return WRC_Prune;
70083  }else{
70084    return WRC_Continue;
70085  }
70086}
70087
70088/*
70089** Analyze the given expression looking for aggregate functions and
70090** for variables that need to be added to the pParse->aAgg[] array.
70091** Make additional entries to the pParse->aAgg[] array as necessary.
70092**
70093** This routine should only be called after the expression has been
70094** analyzed by sqlite3ResolveExprNames().
70095*/
70096SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
70097  Walker w;
70098  w.xExprCallback = analyzeAggregate;
70099  w.xSelectCallback = analyzeAggregatesInSelect;
70100  w.u.pNC = pNC;
70101  assert( pNC->pSrcList!=0 );
70102  sqlite3WalkExpr(&w, pExpr);
70103}
70104
70105/*
70106** Call sqlite3ExprAnalyzeAggregates() for every expression in an
70107** expression list.  Return the number of errors.
70108**
70109** If an error is found, the analysis is cut short.
70110*/
70111SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
70112  struct ExprList_item *pItem;
70113  int i;
70114  if( pList ){
70115    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
70116      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
70117    }
70118  }
70119}
70120
70121/*
70122** Allocate a single new register for use to hold some intermediate result.
70123*/
70124SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
70125  if( pParse->nTempReg==0 ){
70126    return ++pParse->nMem;
70127  }
70128  return pParse->aTempReg[--pParse->nTempReg];
70129}
70130
70131/*
70132** Deallocate a register, making available for reuse for some other
70133** purpose.
70134**
70135** If a register is currently being used by the column cache, then
70136** the dallocation is deferred until the column cache line that uses
70137** the register becomes stale.
70138*/
70139SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
70140  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70141    int i;
70142    struct yColCache *p;
70143    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70144      if( p->iReg==iReg ){
70145        p->tempReg = 1;
70146        return;
70147      }
70148    }
70149    pParse->aTempReg[pParse->nTempReg++] = iReg;
70150  }
70151}
70152
70153/*
70154** Allocate or deallocate a block of nReg consecutive registers
70155*/
70156SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
70157  int i, n;
70158  i = pParse->iRangeReg;
70159  n = pParse->nRangeReg;
70160  if( nReg<=n ){
70161    assert( !usedAsColumnCache(pParse, i, i+n-1) );
70162    pParse->iRangeReg += nReg;
70163    pParse->nRangeReg -= nReg;
70164  }else{
70165    i = pParse->nMem+1;
70166    pParse->nMem += nReg;
70167  }
70168  return i;
70169}
70170SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
70171  sqlite3ExprCacheRemove(pParse, iReg, nReg);
70172  if( nReg>pParse->nRangeReg ){
70173    pParse->nRangeReg = nReg;
70174    pParse->iRangeReg = iReg;
70175  }
70176}
70177
70178/************** End of expr.c ************************************************/
70179/************** Begin file alter.c *******************************************/
70180/*
70181** 2005 February 15
70182**
70183** The author disclaims copyright to this source code.  In place of
70184** a legal notice, here is a blessing:
70185**
70186**    May you do good and not evil.
70187**    May you find forgiveness for yourself and forgive others.
70188**    May you share freely, never taking more than you give.
70189**
70190*************************************************************************
70191** This file contains C code routines that used to generate VDBE code
70192** that implements the ALTER TABLE command.
70193*/
70194
70195/*
70196** The code in this file only exists if we are not omitting the
70197** ALTER TABLE logic from the build.
70198*/
70199#ifndef SQLITE_OMIT_ALTERTABLE
70200
70201
70202/*
70203** This function is used by SQL generated to implement the
70204** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
70205** CREATE INDEX command. The second is a table name. The table name in
70206** the CREATE TABLE or CREATE INDEX statement is replaced with the third
70207** argument and the result returned. Examples:
70208**
70209** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
70210**     -> 'CREATE TABLE def(a, b, c)'
70211**
70212** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
70213**     -> 'CREATE INDEX i ON def(a, b, c)'
70214*/
70215static void renameTableFunc(
70216  sqlite3_context *context,
70217  int NotUsed,
70218  sqlite3_value **argv
70219){
70220  unsigned char const *zSql = sqlite3_value_text(argv[0]);
70221  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70222
70223  int token;
70224  Token tname;
70225  unsigned char const *zCsr = zSql;
70226  int len = 0;
70227  char *zRet;
70228
70229  sqlite3 *db = sqlite3_context_db_handle(context);
70230
70231  UNUSED_PARAMETER(NotUsed);
70232
70233  /* The principle used to locate the table name in the CREATE TABLE
70234  ** statement is that the table name is the first non-space token that
70235  ** is immediately followed by a TK_LP or TK_USING token.
70236  */
70237  if( zSql ){
70238    do {
70239      if( !*zCsr ){
70240        /* Ran out of input before finding an opening bracket. Return NULL. */
70241        return;
70242      }
70243
70244      /* Store the token that zCsr points to in tname. */
70245      tname.z = (char*)zCsr;
70246      tname.n = len;
70247
70248      /* Advance zCsr to the next token. Store that token type in 'token',
70249      ** and its length in 'len' (to be used next iteration of this loop).
70250      */
70251      do {
70252        zCsr += len;
70253        len = sqlite3GetToken(zCsr, &token);
70254      } while( token==TK_SPACE );
70255      assert( len>0 );
70256    } while( token!=TK_LP && token!=TK_USING );
70257
70258    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
70259       zTableName, tname.z+tname.n);
70260    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70261  }
70262}
70263
70264/*
70265** This C function implements an SQL user function that is used by SQL code
70266** generated by the ALTER TABLE ... RENAME command to modify the definition
70267** of any foreign key constraints that use the table being renamed as the
70268** parent table. It is passed three arguments:
70269**
70270**   1) The complete text of the CREATE TABLE statement being modified,
70271**   2) The old name of the table being renamed, and
70272**   3) The new name of the table being renamed.
70273**
70274** It returns the new CREATE TABLE statement. For example:
70275**
70276**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
70277**       -> 'CREATE TABLE t1(a REFERENCES t3)'
70278*/
70279#ifndef SQLITE_OMIT_FOREIGN_KEY
70280static void renameParentFunc(
70281  sqlite3_context *context,
70282  int NotUsed,
70283  sqlite3_value **argv
70284){
70285  sqlite3 *db = sqlite3_context_db_handle(context);
70286  char *zOutput = 0;
70287  char *zResult;
70288  unsigned char const *zInput = sqlite3_value_text(argv[0]);
70289  unsigned char const *zOld = sqlite3_value_text(argv[1]);
70290  unsigned char const *zNew = sqlite3_value_text(argv[2]);
70291
70292  unsigned const char *z;         /* Pointer to token */
70293  int n;                          /* Length of token z */
70294  int token;                      /* Type of token */
70295
70296  UNUSED_PARAMETER(NotUsed);
70297  for(z=zInput; *z; z=z+n){
70298    n = sqlite3GetToken(z, &token);
70299    if( token==TK_REFERENCES ){
70300      char *zParent;
70301      do {
70302        z += n;
70303        n = sqlite3GetToken(z, &token);
70304      }while( token==TK_SPACE );
70305
70306      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
70307      if( zParent==0 ) break;
70308      sqlite3Dequote(zParent);
70309      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
70310        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
70311            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
70312        );
70313        sqlite3DbFree(db, zOutput);
70314        zOutput = zOut;
70315        zInput = &z[n];
70316      }
70317      sqlite3DbFree(db, zParent);
70318    }
70319  }
70320
70321  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
70322  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
70323  sqlite3DbFree(db, zOutput);
70324}
70325#endif
70326
70327#ifndef SQLITE_OMIT_TRIGGER
70328/* This function is used by SQL generated to implement the
70329** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
70330** statement. The second is a table name. The table name in the CREATE
70331** TRIGGER statement is replaced with the third argument and the result
70332** returned. This is analagous to renameTableFunc() above, except for CREATE
70333** TRIGGER, not CREATE INDEX and CREATE TABLE.
70334*/
70335static void renameTriggerFunc(
70336  sqlite3_context *context,
70337  int NotUsed,
70338  sqlite3_value **argv
70339){
70340  unsigned char const *zSql = sqlite3_value_text(argv[0]);
70341  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70342
70343  int token;
70344  Token tname;
70345  int dist = 3;
70346  unsigned char const *zCsr = zSql;
70347  int len = 0;
70348  char *zRet;
70349  sqlite3 *db = sqlite3_context_db_handle(context);
70350
70351  UNUSED_PARAMETER(NotUsed);
70352
70353  /* The principle used to locate the table name in the CREATE TRIGGER
70354  ** statement is that the table name is the first token that is immediatedly
70355  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
70356  ** of TK_WHEN, TK_BEGIN or TK_FOR.
70357  */
70358  if( zSql ){
70359    do {
70360
70361      if( !*zCsr ){
70362        /* Ran out of input before finding the table name. Return NULL. */
70363        return;
70364      }
70365
70366      /* Store the token that zCsr points to in tname. */
70367      tname.z = (char*)zCsr;
70368      tname.n = len;
70369
70370      /* Advance zCsr to the next token. Store that token type in 'token',
70371      ** and its length in 'len' (to be used next iteration of this loop).
70372      */
70373      do {
70374        zCsr += len;
70375        len = sqlite3GetToken(zCsr, &token);
70376      }while( token==TK_SPACE );
70377      assert( len>0 );
70378
70379      /* Variable 'dist' stores the number of tokens read since the most
70380      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
70381      ** token is read and 'dist' equals 2, the condition stated above
70382      ** to be met.
70383      **
70384      ** Note that ON cannot be a database, table or column name, so
70385      ** there is no need to worry about syntax like
70386      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
70387      */
70388      dist++;
70389      if( token==TK_DOT || token==TK_ON ){
70390        dist = 0;
70391      }
70392    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
70393
70394    /* Variable tname now contains the token that is the old table-name
70395    ** in the CREATE TRIGGER statement.
70396    */
70397    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
70398       zTableName, tname.z+tname.n);
70399    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70400  }
70401}
70402#endif   /* !SQLITE_OMIT_TRIGGER */
70403
70404/*
70405** Register built-in functions used to help implement ALTER TABLE
70406*/
70407SQLITE_PRIVATE void sqlite3AlterFunctions(void){
70408  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
70409    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
70410#ifndef SQLITE_OMIT_TRIGGER
70411    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
70412#endif
70413#ifndef SQLITE_OMIT_FOREIGN_KEY
70414    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
70415#endif
70416  };
70417  int i;
70418  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70419  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
70420
70421  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
70422    sqlite3FuncDefInsert(pHash, &aFunc[i]);
70423  }
70424}
70425
70426/*
70427** This function is used to create the text of expressions of the form:
70428**
70429**   name=<constant1> OR name=<constant2> OR ...
70430**
70431** If argument zWhere is NULL, then a pointer string containing the text
70432** "name=<constant>" is returned, where <constant> is the quoted version
70433** of the string passed as argument zConstant. The returned buffer is
70434** allocated using sqlite3DbMalloc(). It is the responsibility of the
70435** caller to ensure that it is eventually freed.
70436**
70437** If argument zWhere is not NULL, then the string returned is
70438** "<where> OR name=<constant>", where <where> is the contents of zWhere.
70439** In this case zWhere is passed to sqlite3DbFree() before returning.
70440**
70441*/
70442static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
70443  char *zNew;
70444  if( !zWhere ){
70445    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
70446  }else{
70447    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
70448    sqlite3DbFree(db, zWhere);
70449  }
70450  return zNew;
70451}
70452
70453#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
70454/*
70455** Generate the text of a WHERE expression which can be used to select all
70456** tables that have foreign key constraints that refer to table pTab (i.e.
70457** constraints for which pTab is the parent table) from the sqlite_master
70458** table.
70459*/
70460static char *whereForeignKeys(Parse *pParse, Table *pTab){
70461  FKey *p;
70462  char *zWhere = 0;
70463  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
70464    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
70465  }
70466  return zWhere;
70467}
70468#endif
70469
70470/*
70471** Generate the text of a WHERE expression which can be used to select all
70472** temporary triggers on table pTab from the sqlite_temp_master table. If
70473** table pTab has no temporary triggers, or is itself stored in the
70474** temporary database, NULL is returned.
70475*/
70476static char *whereTempTriggers(Parse *pParse, Table *pTab){
70477  Trigger *pTrig;
70478  char *zWhere = 0;
70479  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
70480
70481  /* If the table is not located in the temp-db (in which case NULL is
70482  ** returned, loop through the tables list of triggers. For each trigger
70483  ** that is not part of the temp-db schema, add a clause to the WHERE
70484  ** expression being built up in zWhere.
70485  */
70486  if( pTab->pSchema!=pTempSchema ){
70487    sqlite3 *db = pParse->db;
70488    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70489      if( pTrig->pSchema==pTempSchema ){
70490        zWhere = whereOrName(db, zWhere, pTrig->zName);
70491      }
70492    }
70493  }
70494  return zWhere;
70495}
70496
70497/*
70498** Generate code to drop and reload the internal representation of table
70499** pTab from the database, including triggers and temporary triggers.
70500** Argument zName is the name of the table in the database schema at
70501** the time the generated code is executed. This can be different from
70502** pTab->zName if this function is being called to code part of an
70503** "ALTER TABLE RENAME TO" statement.
70504*/
70505static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
70506  Vdbe *v;
70507  char *zWhere;
70508  int iDb;                   /* Index of database containing pTab */
70509#ifndef SQLITE_OMIT_TRIGGER
70510  Trigger *pTrig;
70511#endif
70512
70513  v = sqlite3GetVdbe(pParse);
70514  if( NEVER(v==0) ) return;
70515  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70516  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70517  assert( iDb>=0 );
70518
70519#ifndef SQLITE_OMIT_TRIGGER
70520  /* Drop any table triggers from the internal schema. */
70521  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70522    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
70523    assert( iTrigDb==iDb || iTrigDb==1 );
70524    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
70525  }
70526#endif
70527
70528  /* Drop the table and index from the internal schema.  */
70529  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
70530
70531  /* Reload the table, index and permanent trigger schemas. */
70532  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
70533  if( !zWhere ) return;
70534  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70535
70536#ifndef SQLITE_OMIT_TRIGGER
70537  /* Now, if the table is not stored in the temp database, reload any temp
70538  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
70539  */
70540  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
70541    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
70542  }
70543#endif
70544}
70545
70546/*
70547** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
70548** command.
70549*/
70550SQLITE_PRIVATE void sqlite3AlterRenameTable(
70551  Parse *pParse,            /* Parser context. */
70552  SrcList *pSrc,            /* The table to rename. */
70553  Token *pName              /* The new table name. */
70554){
70555  int iDb;                  /* Database that contains the table */
70556  char *zDb;                /* Name of database iDb */
70557  Table *pTab;              /* Table being renamed */
70558  char *zName = 0;          /* NULL-terminated version of pName */
70559  sqlite3 *db = pParse->db; /* Database connection */
70560  int nTabName;             /* Number of UTF-8 characters in zTabName */
70561  const char *zTabName;     /* Original name of the table */
70562  Vdbe *v;
70563#ifndef SQLITE_OMIT_TRIGGER
70564  char *zWhere = 0;         /* Where clause to locate temp triggers */
70565#endif
70566  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
70567  int savedDbFlags;         /* Saved value of db->flags */
70568
70569  savedDbFlags = db->flags;
70570  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
70571  assert( pSrc->nSrc==1 );
70572  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70573
70574  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
70575  if( !pTab ) goto exit_rename_table;
70576  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70577  zDb = db->aDb[iDb].zName;
70578  db->flags |= SQLITE_PreferBuiltin;
70579
70580  /* Get a NULL terminated version of the new table name. */
70581  zName = sqlite3NameFromToken(db, pName);
70582  if( !zName ) goto exit_rename_table;
70583
70584  /* Check that a table or index named 'zName' does not already exist
70585  ** in database iDb. If so, this is an error.
70586  */
70587  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
70588    sqlite3ErrorMsg(pParse,
70589        "there is already another table or index with this name: %s", zName);
70590    goto exit_rename_table;
70591  }
70592
70593  /* Make sure it is not a system table being altered, or a reserved name
70594  ** that the table is being renamed to.
70595  */
70596  if( sqlite3Strlen30(pTab->zName)>6
70597   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
70598  ){
70599    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
70600    goto exit_rename_table;
70601  }
70602  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
70603    goto exit_rename_table;
70604  }
70605
70606#ifndef SQLITE_OMIT_VIEW
70607  if( pTab->pSelect ){
70608    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
70609    goto exit_rename_table;
70610  }
70611#endif
70612
70613#ifndef SQLITE_OMIT_AUTHORIZATION
70614  /* Invoke the authorization callback. */
70615  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
70616    goto exit_rename_table;
70617  }
70618#endif
70619
70620#ifndef SQLITE_OMIT_VIRTUALTABLE
70621  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70622    goto exit_rename_table;
70623  }
70624  if( IsVirtual(pTab) ){
70625    pVTab = sqlite3GetVTable(db, pTab);
70626    if( pVTab->pVtab->pModule->xRename==0 ){
70627      pVTab = 0;
70628    }
70629  }
70630#endif
70631
70632  /* Begin a transaction and code the VerifyCookie for database iDb.
70633  ** Then modify the schema cookie (since the ALTER TABLE modifies the
70634  ** schema). Open a statement transaction if the table is a virtual
70635  ** table.
70636  */
70637  v = sqlite3GetVdbe(pParse);
70638  if( v==0 ){
70639    goto exit_rename_table;
70640  }
70641  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
70642  sqlite3ChangeCookie(pParse, iDb);
70643
70644  /* If this is a virtual table, invoke the xRename() function if
70645  ** one is defined. The xRename() callback will modify the names
70646  ** of any resources used by the v-table implementation (including other
70647  ** SQLite tables) that are identified by the name of the virtual table.
70648  */
70649#ifndef SQLITE_OMIT_VIRTUALTABLE
70650  if( pVTab ){
70651    int i = ++pParse->nMem;
70652    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
70653    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
70654    sqlite3MayAbort(pParse);
70655  }
70656#endif
70657
70658  /* figure out how many UTF-8 characters are in zName */
70659  zTabName = pTab->zName;
70660  nTabName = sqlite3Utf8CharLen(zTabName, -1);
70661
70662#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
70663  if( db->flags&SQLITE_ForeignKeys ){
70664    /* If foreign-key support is enabled, rewrite the CREATE TABLE
70665    ** statements corresponding to all child tables of foreign key constraints
70666    ** for which the renamed table is the parent table.  */
70667    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
70668      sqlite3NestedParse(pParse,
70669          "UPDATE \"%w\".%s SET "
70670              "sql = sqlite_rename_parent(sql, %Q, %Q) "
70671              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
70672      sqlite3DbFree(db, zWhere);
70673    }
70674  }
70675#endif
70676
70677  /* Modify the sqlite_master table to use the new table name. */
70678  sqlite3NestedParse(pParse,
70679      "UPDATE %Q.%s SET "
70680#ifdef SQLITE_OMIT_TRIGGER
70681          "sql = sqlite_rename_table(sql, %Q), "
70682#else
70683          "sql = CASE "
70684            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
70685            "ELSE sqlite_rename_table(sql, %Q) END, "
70686#endif
70687          "tbl_name = %Q, "
70688          "name = CASE "
70689            "WHEN type='table' THEN %Q "
70690            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
70691             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
70692            "ELSE name END "
70693      "WHERE tbl_name=%Q AND "
70694          "(type='table' OR type='index' OR type='trigger');",
70695      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
70696#ifndef SQLITE_OMIT_TRIGGER
70697      zName,
70698#endif
70699      zName, nTabName, zTabName
70700  );
70701
70702#ifndef SQLITE_OMIT_AUTOINCREMENT
70703  /* If the sqlite_sequence table exists in this database, then update
70704  ** it with the new table name.
70705  */
70706  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
70707    sqlite3NestedParse(pParse,
70708        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
70709        zDb, zName, pTab->zName);
70710  }
70711#endif
70712
70713#ifndef SQLITE_OMIT_TRIGGER
70714  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
70715  ** table. Don't do this if the table being ALTERed is itself located in
70716  ** the temp database.
70717  */
70718  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
70719    sqlite3NestedParse(pParse,
70720        "UPDATE sqlite_temp_master SET "
70721            "sql = sqlite_rename_trigger(sql, %Q), "
70722            "tbl_name = %Q "
70723            "WHERE %s;", zName, zName, zWhere);
70724    sqlite3DbFree(db, zWhere);
70725  }
70726#endif
70727
70728#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
70729  if( db->flags&SQLITE_ForeignKeys ){
70730    FKey *p;
70731    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
70732      Table *pFrom = p->pFrom;
70733      if( pFrom!=pTab ){
70734        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
70735      }
70736    }
70737  }
70738#endif
70739
70740  /* Drop and reload the internal table schema. */
70741  reloadTableSchema(pParse, pTab, zName);
70742
70743exit_rename_table:
70744  sqlite3SrcListDelete(db, pSrc);
70745  sqlite3DbFree(db, zName);
70746  db->flags = savedDbFlags;
70747}
70748
70749
70750/*
70751** Generate code to make sure the file format number is at least minFormat.
70752** The generated code will increase the file format number if necessary.
70753*/
70754SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
70755  Vdbe *v;
70756  v = sqlite3GetVdbe(pParse);
70757  /* The VDBE should have been allocated before this routine is called.
70758  ** If that allocation failed, we would have quit before reaching this
70759  ** point */
70760  if( ALWAYS(v) ){
70761    int r1 = sqlite3GetTempReg(pParse);
70762    int r2 = sqlite3GetTempReg(pParse);
70763    int j1;
70764    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
70765    sqlite3VdbeUsesBtree(v, iDb);
70766    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
70767    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
70768    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
70769    sqlite3VdbeJumpHere(v, j1);
70770    sqlite3ReleaseTempReg(pParse, r1);
70771    sqlite3ReleaseTempReg(pParse, r2);
70772  }
70773}
70774
70775/*
70776** This function is called after an "ALTER TABLE ... ADD" statement
70777** has been parsed. Argument pColDef contains the text of the new
70778** column definition.
70779**
70780** The Table structure pParse->pNewTable was extended to include
70781** the new column during parsing.
70782*/
70783SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
70784  Table *pNew;              /* Copy of pParse->pNewTable */
70785  Table *pTab;              /* Table being altered */
70786  int iDb;                  /* Database number */
70787  const char *zDb;          /* Database name */
70788  const char *zTab;         /* Table name */
70789  char *zCol;               /* Null-terminated column definition */
70790  Column *pCol;             /* The new column */
70791  Expr *pDflt;              /* Default value for the new column */
70792  sqlite3 *db;              /* The database connection; */
70793
70794  db = pParse->db;
70795  if( pParse->nErr || db->mallocFailed ) return;
70796  pNew = pParse->pNewTable;
70797  assert( pNew );
70798
70799  assert( sqlite3BtreeHoldsAllMutexes(db) );
70800  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
70801  zDb = db->aDb[iDb].zName;
70802  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
70803  pCol = &pNew->aCol[pNew->nCol-1];
70804  pDflt = pCol->pDflt;
70805  pTab = sqlite3FindTable(db, zTab, zDb);
70806  assert( pTab );
70807
70808#ifndef SQLITE_OMIT_AUTHORIZATION
70809  /* Invoke the authorization callback. */
70810  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
70811    return;
70812  }
70813#endif
70814
70815  /* If the default value for the new column was specified with a
70816  ** literal NULL, then set pDflt to 0. This simplifies checking
70817  ** for an SQL NULL default below.
70818  */
70819  if( pDflt && pDflt->op==TK_NULL ){
70820    pDflt = 0;
70821  }
70822
70823  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
70824  ** If there is a NOT NULL constraint, then the default value for the
70825  ** column must not be NULL.
70826  */
70827  if( pCol->isPrimKey ){
70828    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
70829    return;
70830  }
70831  if( pNew->pIndex ){
70832    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
70833    return;
70834  }
70835  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
70836    sqlite3ErrorMsg(pParse,
70837        "Cannot add a REFERENCES column with non-NULL default value");
70838    return;
70839  }
70840  if( pCol->notNull && !pDflt ){
70841    sqlite3ErrorMsg(pParse,
70842        "Cannot add a NOT NULL column with default value NULL");
70843    return;
70844  }
70845
70846  /* Ensure the default expression is something that sqlite3ValueFromExpr()
70847  ** can handle (i.e. not CURRENT_TIME etc.)
70848  */
70849  if( pDflt ){
70850    sqlite3_value *pVal;
70851    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
70852      db->mallocFailed = 1;
70853      return;
70854    }
70855    if( !pVal ){
70856      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
70857      return;
70858    }
70859    sqlite3ValueFree(pVal);
70860  }
70861
70862  /* Modify the CREATE TABLE statement. */
70863  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
70864  if( zCol ){
70865    char *zEnd = &zCol[pColDef->n-1];
70866    int savedDbFlags = db->flags;
70867    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
70868      *zEnd-- = '\0';
70869    }
70870    db->flags |= SQLITE_PreferBuiltin;
70871    sqlite3NestedParse(pParse,
70872        "UPDATE \"%w\".%s SET "
70873          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
70874        "WHERE type = 'table' AND name = %Q",
70875      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
70876      zTab
70877    );
70878    sqlite3DbFree(db, zCol);
70879    db->flags = savedDbFlags;
70880  }
70881
70882  /* If the default value of the new column is NULL, then set the file
70883  ** format to 2. If the default value of the new column is not NULL,
70884  ** the file format becomes 3.
70885  */
70886  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
70887
70888  /* Reload the schema of the modified table. */
70889  reloadTableSchema(pParse, pTab, pTab->zName);
70890}
70891
70892/*
70893** This function is called by the parser after the table-name in
70894** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
70895** pSrc is the full-name of the table being altered.
70896**
70897** This routine makes a (partial) copy of the Table structure
70898** for the table being altered and sets Parse.pNewTable to point
70899** to it. Routines called by the parser as the column definition
70900** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
70901** the copy. The copy of the Table structure is deleted by tokenize.c
70902** after parsing is finished.
70903**
70904** Routine sqlite3AlterFinishAddColumn() will be called to complete
70905** coding the "ALTER TABLE ... ADD" statement.
70906*/
70907SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
70908  Table *pNew;
70909  Table *pTab;
70910  Vdbe *v;
70911  int iDb;
70912  int i;
70913  int nAlloc;
70914  sqlite3 *db = pParse->db;
70915
70916  /* Look up the table being altered. */
70917  assert( pParse->pNewTable==0 );
70918  assert( sqlite3BtreeHoldsAllMutexes(db) );
70919  if( db->mallocFailed ) goto exit_begin_add_column;
70920  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
70921  if( !pTab ) goto exit_begin_add_column;
70922
70923#ifndef SQLITE_OMIT_VIRTUALTABLE
70924  if( IsVirtual(pTab) ){
70925    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
70926    goto exit_begin_add_column;
70927  }
70928#endif
70929
70930  /* Make sure this is not an attempt to ALTER a view. */
70931  if( pTab->pSelect ){
70932    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
70933    goto exit_begin_add_column;
70934  }
70935
70936  assert( pTab->addColOffset>0 );
70937  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70938
70939  /* Put a copy of the Table struct in Parse.pNewTable for the
70940  ** sqlite3AddColumn() function and friends to modify.  But modify
70941  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
70942  ** prefix, we insure that the name will not collide with an existing
70943  ** table because user table are not allowed to have the "sqlite_"
70944  ** prefix on their name.
70945  */
70946  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
70947  if( !pNew ) goto exit_begin_add_column;
70948  pParse->pNewTable = pNew;
70949  pNew->nRef = 1;
70950  pNew->dbMem = pTab->dbMem;
70951  pNew->nCol = pTab->nCol;
70952  assert( pNew->nCol>0 );
70953  nAlloc = (((pNew->nCol-1)/8)*8)+8;
70954  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
70955  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
70956  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
70957  if( !pNew->aCol || !pNew->zName ){
70958    db->mallocFailed = 1;
70959    goto exit_begin_add_column;
70960  }
70961  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
70962  for(i=0; i<pNew->nCol; i++){
70963    Column *pCol = &pNew->aCol[i];
70964    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
70965    pCol->zColl = 0;
70966    pCol->zType = 0;
70967    pCol->pDflt = 0;
70968    pCol->zDflt = 0;
70969  }
70970  pNew->pSchema = db->aDb[iDb].pSchema;
70971  pNew->addColOffset = pTab->addColOffset;
70972  pNew->nRef = 1;
70973
70974  /* Begin a transaction and increment the schema cookie.  */
70975  sqlite3BeginWriteOperation(pParse, 0, iDb);
70976  v = sqlite3GetVdbe(pParse);
70977  if( !v ) goto exit_begin_add_column;
70978  sqlite3ChangeCookie(pParse, iDb);
70979
70980exit_begin_add_column:
70981  sqlite3SrcListDelete(db, pSrc);
70982  return;
70983}
70984#endif  /* SQLITE_ALTER_TABLE */
70985
70986/************** End of alter.c ***********************************************/
70987/************** Begin file analyze.c *****************************************/
70988/*
70989** 2005 July 8
70990**
70991** The author disclaims copyright to this source code.  In place of
70992** a legal notice, here is a blessing:
70993**
70994**    May you do good and not evil.
70995**    May you find forgiveness for yourself and forgive others.
70996**    May you share freely, never taking more than you give.
70997**
70998*************************************************************************
70999** This file contains code associated with the ANALYZE command.
71000*/
71001#ifndef SQLITE_OMIT_ANALYZE
71002
71003/*
71004** This routine generates code that opens the sqlite_stat1 table for
71005** writing with cursor iStatCur. If the library was built with the
71006** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
71007** opened for writing using cursor (iStatCur+1)
71008**
71009** If the sqlite_stat1 tables does not previously exist, it is created.
71010** Similarly, if the sqlite_stat2 table does not exist and the library
71011** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
71012**
71013** Argument zWhere may be a pointer to a buffer containing a table name,
71014** or it may be a NULL pointer. If it is not NULL, then all entries in
71015** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
71016** with the named table are deleted. If zWhere==0, then code is generated
71017** to delete all stat table entries.
71018*/
71019static void openStatTable(
71020  Parse *pParse,          /* Parsing context */
71021  int iDb,                /* The database we are looking in */
71022  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
71023  const char *zWhere      /* Delete entries associated with this table */
71024){
71025  static const struct {
71026    const char *zName;
71027    const char *zCols;
71028  } aTable[] = {
71029    { "sqlite_stat1", "tbl,idx,stat" },
71030#ifdef SQLITE_ENABLE_STAT2
71031    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
71032#endif
71033  };
71034
71035  int aRoot[] = {0, 0};
71036  u8 aCreateTbl[] = {0, 0};
71037
71038  int i;
71039  sqlite3 *db = pParse->db;
71040  Db *pDb;
71041  Vdbe *v = sqlite3GetVdbe(pParse);
71042  if( v==0 ) return;
71043  assert( sqlite3BtreeHoldsAllMutexes(db) );
71044  assert( sqlite3VdbeDb(v)==db );
71045  pDb = &db->aDb[iDb];
71046
71047  for(i=0; i<ArraySize(aTable); i++){
71048    const char *zTab = aTable[i].zName;
71049    Table *pStat;
71050    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
71051      /* The sqlite_stat[12] table does not exist. Create it. Note that a
71052      ** side-effect of the CREATE TABLE statement is to leave the rootpage
71053      ** of the new table in register pParse->regRoot. This is important
71054      ** because the OpenWrite opcode below will be needing it. */
71055      sqlite3NestedParse(pParse,
71056          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
71057      );
71058      aRoot[i] = pParse->regRoot;
71059      aCreateTbl[i] = 1;
71060    }else{
71061      /* The table already exists. If zWhere is not NULL, delete all entries
71062      ** associated with the table zWhere. If zWhere is NULL, delete the
71063      ** entire contents of the table. */
71064      aRoot[i] = pStat->tnum;
71065      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
71066      if( zWhere ){
71067        sqlite3NestedParse(pParse,
71068           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
71069        );
71070      }else{
71071        /* The sqlite_stat[12] table already exists.  Delete all rows. */
71072        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
71073      }
71074    }
71075  }
71076
71077  /* Open the sqlite_stat[12] tables for writing. */
71078  for(i=0; i<ArraySize(aTable); i++){
71079    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
71080    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
71081    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
71082  }
71083}
71084
71085/*
71086** Generate code to do an analysis of all indices associated with
71087** a single table.
71088*/
71089static void analyzeOneTable(
71090  Parse *pParse,   /* Parser context */
71091  Table *pTab,     /* Table whose indices are to be analyzed */
71092  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
71093  int iMem         /* Available memory locations begin here */
71094){
71095  sqlite3 *db = pParse->db;    /* Database handle */
71096  Index *pIdx;                 /* An index to being analyzed */
71097  int iIdxCur;                 /* Cursor open on index being analyzed */
71098  Vdbe *v;                     /* The virtual machine being built up */
71099  int i;                       /* Loop counter */
71100  int topOfLoop;               /* The top of the loop */
71101  int endOfLoop;               /* The end of the loop */
71102  int addr;                    /* The address of an instruction */
71103  int iDb;                     /* Index of database containing pTab */
71104  int regTabname = iMem++;     /* Register containing table name */
71105  int regIdxname = iMem++;     /* Register containing index name */
71106  int regSampleno = iMem++;    /* Register containing next sample number */
71107  int regCol = iMem++;         /* Content of a column analyzed table */
71108  int regRec = iMem++;         /* Register holding completed record */
71109  int regTemp = iMem++;        /* Temporary use register */
71110  int regRowid = iMem++;       /* Rowid for the inserted record */
71111
71112#ifdef SQLITE_ENABLE_STAT2
71113  int regTemp2 = iMem++;       /* Temporary use register */
71114  int regSamplerecno = iMem++; /* Index of next sample to record */
71115  int regRecno = iMem++;       /* Current sample index */
71116  int regLast = iMem++;        /* Index of last sample to record */
71117  int regFirst = iMem++;       /* Index of first sample to record */
71118#endif
71119
71120  v = sqlite3GetVdbe(pParse);
71121  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
71122    /* Do no analysis for tables that have no indices */
71123    return;
71124  }
71125  assert( sqlite3BtreeHoldsAllMutexes(db) );
71126  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71127  assert( iDb>=0 );
71128#ifndef SQLITE_OMIT_AUTHORIZATION
71129  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
71130      db->aDb[iDb].zName ) ){
71131    return;
71132  }
71133#endif
71134
71135  /* Establish a read-lock on the table at the shared-cache level. */
71136  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
71137
71138  iIdxCur = pParse->nTab++;
71139  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71140    int nCol = pIdx->nColumn;
71141    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
71142
71143    if( iMem+1+(nCol*2)>pParse->nMem ){
71144      pParse->nMem = iMem+1+(nCol*2);
71145    }
71146
71147    /* Open a cursor to the index to be analyzed. */
71148    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
71149    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
71150        (char *)pKey, P4_KEYINFO_HANDOFF);
71151    VdbeComment((v, "%s", pIdx->zName));
71152
71153    /* Populate the registers containing the table and index names. */
71154    if( pTab->pIndex==pIdx ){
71155      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
71156    }
71157    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
71158
71159#ifdef SQLITE_ENABLE_STAT2
71160
71161    /* If this iteration of the loop is generating code to analyze the
71162    ** first index in the pTab->pIndex list, then register regLast has
71163    ** not been populated. In this case populate it now.  */
71164    if( pTab->pIndex==pIdx ){
71165      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
71166      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
71167      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
71168
71169      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
71170      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
71171      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
71172      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
71173      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
71174      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
71175      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
71176      sqlite3VdbeJumpHere(v, addr);
71177    }
71178
71179    /* Zero the regSampleno and regRecno registers. */
71180    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
71181    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
71182    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
71183#endif
71184
71185    /* The block of memory cells initialized here is used as follows.
71186    **
71187    **    iMem:
71188    **        The total number of rows in the table.
71189    **
71190    **    iMem+1 .. iMem+nCol:
71191    **        Number of distinct entries in index considering the
71192    **        left-most N columns only, where N is between 1 and nCol,
71193    **        inclusive.
71194    **
71195    **    iMem+nCol+1 .. Mem+2*nCol:
71196    **        Previous value of indexed columns, from left to right.
71197    **
71198    ** Cells iMem through iMem+nCol are initialized to 0. The others are
71199    ** initialized to contain an SQL NULL.
71200    */
71201    for(i=0; i<=nCol; i++){
71202      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
71203    }
71204    for(i=0; i<nCol; i++){
71205      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
71206    }
71207
71208    /* Start the analysis loop. This loop runs through all the entries in
71209    ** the index b-tree.  */
71210    endOfLoop = sqlite3VdbeMakeLabel(v);
71211    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
71212    topOfLoop = sqlite3VdbeCurrentAddr(v);
71213    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
71214
71215    for(i=0; i<nCol; i++){
71216      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
71217#ifdef SQLITE_ENABLE_STAT2
71218      if( i==0 ){
71219        /* Check if the record that cursor iIdxCur points to contains a
71220        ** value that should be stored in the sqlite_stat2 table. If so,
71221        ** store it.  */
71222        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
71223        assert( regTabname+1==regIdxname
71224             && regTabname+2==regSampleno
71225             && regTabname+3==regCol
71226        );
71227        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71228        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
71229        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
71230        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
71231
71232        /* Calculate new values for regSamplerecno and regSampleno.
71233        **
71234        **   sampleno = sampleno + 1
71235        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
71236        */
71237        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
71238        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
71239        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71240        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
71241        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
71242        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
71243        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
71244
71245        sqlite3VdbeJumpHere(v, ne);
71246        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
71247      }
71248#endif
71249
71250      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
71251      /**** TODO:  add collating sequence *****/
71252      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71253    }
71254    if( db->mallocFailed ){
71255      /* If a malloc failure has occurred, then the result of the expression
71256      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
71257      ** below may be negative. Which causes an assert() to fail (or an
71258      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
71259      return;
71260    }
71261    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
71262    for(i=0; i<nCol; i++){
71263      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
71264      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
71265      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
71266    }
71267
71268    /* End of the analysis loop. */
71269    sqlite3VdbeResolveLabel(v, endOfLoop);
71270    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
71271    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
71272
71273    /* Store the results in sqlite_stat1.
71274    **
71275    ** The result is a single row of the sqlite_stat1 table.  The first
71276    ** two columns are the names of the table and index.  The third column
71277    ** is a string composed of a list of integer statistics about the
71278    ** index.  The first integer in the list is the total number of entries
71279    ** in the index.  There is one additional integer in the list for each
71280    ** column of the table.  This additional integer is a guess of how many
71281    ** rows of the table the index will select.  If D is the count of distinct
71282    ** values and K is the total number of rows, then the integer is computed
71283    ** as:
71284    **
71285    **        I = (K+D-1)/D
71286    **
71287    ** If K==0 then no entry is made into the sqlite_stat1 table.
71288    ** If K>0 then it is always the case the D>0 so division by zero
71289    ** is never possible.
71290    */
71291    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
71292    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
71293    for(i=0; i<nCol; i++){
71294      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
71295      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71296      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
71297      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71298      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
71299      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
71300      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71301    }
71302    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
71303    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
71304    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
71305    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
71306    sqlite3VdbeJumpHere(v, addr);
71307  }
71308}
71309
71310/*
71311** Generate code that will cause the most recent index analysis to
71312** be laoded into internal hash tables where is can be used.
71313*/
71314static void loadAnalysis(Parse *pParse, int iDb){
71315  Vdbe *v = sqlite3GetVdbe(pParse);
71316  if( v ){
71317    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
71318  }
71319}
71320
71321/*
71322** Generate code that will do an analysis of an entire database
71323*/
71324static void analyzeDatabase(Parse *pParse, int iDb){
71325  sqlite3 *db = pParse->db;
71326  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
71327  HashElem *k;
71328  int iStatCur;
71329  int iMem;
71330
71331  sqlite3BeginWriteOperation(pParse, 0, iDb);
71332  iStatCur = pParse->nTab;
71333  pParse->nTab += 2;
71334  openStatTable(pParse, iDb, iStatCur, 0);
71335  iMem = pParse->nMem+1;
71336  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
71337    Table *pTab = (Table*)sqliteHashData(k);
71338    analyzeOneTable(pParse, pTab, iStatCur, iMem);
71339  }
71340  loadAnalysis(pParse, iDb);
71341}
71342
71343/*
71344** Generate code that will do an analysis of a single table in
71345** a database.
71346*/
71347static void analyzeTable(Parse *pParse, Table *pTab){
71348  int iDb;
71349  int iStatCur;
71350
71351  assert( pTab!=0 );
71352  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71353  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71354  sqlite3BeginWriteOperation(pParse, 0, iDb);
71355  iStatCur = pParse->nTab;
71356  pParse->nTab += 2;
71357  openStatTable(pParse, iDb, iStatCur, pTab->zName);
71358  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
71359  loadAnalysis(pParse, iDb);
71360}
71361
71362/*
71363** Generate code for the ANALYZE command.  The parser calls this routine
71364** when it recognizes an ANALYZE command.
71365**
71366**        ANALYZE                            -- 1
71367**        ANALYZE  <database>                -- 2
71368**        ANALYZE  ?<database>.?<tablename>  -- 3
71369**
71370** Form 1 causes all indices in all attached databases to be analyzed.
71371** Form 2 analyzes all indices the single database named.
71372** Form 3 analyzes all indices associated with the named table.
71373*/
71374SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
71375  sqlite3 *db = pParse->db;
71376  int iDb;
71377  int i;
71378  char *z, *zDb;
71379  Table *pTab;
71380  Token *pTableName;
71381
71382  /* Read the database schema. If an error occurs, leave an error message
71383  ** and code in pParse and return NULL. */
71384  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71385  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
71386    return;
71387  }
71388
71389  assert( pName2!=0 || pName1==0 );
71390  if( pName1==0 ){
71391    /* Form 1:  Analyze everything */
71392    for(i=0; i<db->nDb; i++){
71393      if( i==1 ) continue;  /* Do not analyze the TEMP database */
71394      analyzeDatabase(pParse, i);
71395    }
71396  }else if( pName2->n==0 ){
71397    /* Form 2:  Analyze the database or table named */
71398    iDb = sqlite3FindDb(db, pName1);
71399    if( iDb>=0 ){
71400      analyzeDatabase(pParse, iDb);
71401    }else{
71402      z = sqlite3NameFromToken(db, pName1);
71403      if( z ){
71404        pTab = sqlite3LocateTable(pParse, 0, z, 0);
71405        sqlite3DbFree(db, z);
71406        if( pTab ){
71407          analyzeTable(pParse, pTab);
71408        }
71409      }
71410    }
71411  }else{
71412    /* Form 3: Analyze the fully qualified table name */
71413    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
71414    if( iDb>=0 ){
71415      zDb = db->aDb[iDb].zName;
71416      z = sqlite3NameFromToken(db, pTableName);
71417      if( z ){
71418        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
71419        sqlite3DbFree(db, z);
71420        if( pTab ){
71421          analyzeTable(pParse, pTab);
71422        }
71423      }
71424    }
71425  }
71426}
71427
71428/*
71429** Used to pass information from the analyzer reader through to the
71430** callback routine.
71431*/
71432typedef struct analysisInfo analysisInfo;
71433struct analysisInfo {
71434  sqlite3 *db;
71435  const char *zDatabase;
71436};
71437
71438/*
71439** This callback is invoked once for each index when reading the
71440** sqlite_stat1 table.
71441**
71442**     argv[0] = name of the index
71443**     argv[1] = results of analysis - on integer for each column
71444*/
71445static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
71446  analysisInfo *pInfo = (analysisInfo*)pData;
71447  Index *pIndex;
71448  int i, c;
71449  unsigned int v;
71450  const char *z;
71451
71452  assert( argc==2 );
71453  UNUSED_PARAMETER2(NotUsed, argc);
71454
71455  if( argv==0 || argv[0]==0 || argv[1]==0 ){
71456    return 0;
71457  }
71458  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
71459  if( pIndex==0 ){
71460    return 0;
71461  }
71462  z = argv[1];
71463  for(i=0; *z && i<=pIndex->nColumn; i++){
71464    v = 0;
71465    while( (c=z[0])>='0' && c<='9' ){
71466      v = v*10 + c - '0';
71467      z++;
71468    }
71469    pIndex->aiRowEst[i] = v;
71470    if( *z==' ' ) z++;
71471  }
71472  return 0;
71473}
71474
71475/*
71476** If the Index.aSample variable is not NULL, delete the aSample[] array
71477** and its contents.
71478*/
71479SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
71480#ifdef SQLITE_ENABLE_STAT2
71481  if( pIdx->aSample ){
71482    int j;
71483    sqlite3 *dbMem = pIdx->pTable->dbMem;
71484    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
71485      IndexSample *p = &pIdx->aSample[j];
71486      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
71487        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
71488      }
71489    }
71490    sqlite3DbFree(dbMem, pIdx->aSample);
71491    pIdx->aSample = 0;
71492  }
71493#else
71494  UNUSED_PARAMETER(pIdx);
71495#endif
71496}
71497
71498/*
71499** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
71500** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
71501** arrays. The contents of sqlite_stat2 are used to populate the
71502** Index.aSample[] arrays.
71503**
71504** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
71505** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
71506** during compilation and the sqlite_stat2 table is present, no data is
71507** read from it.
71508**
71509** If SQLITE_ENABLE_STAT2 was defined during compilation and the
71510** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
71511** returned. However, in this case, data is read from the sqlite_stat1
71512** table (if it is present) before returning.
71513**
71514** If an OOM error occurs, this function always sets db->mallocFailed.
71515** This means if the caller does not care about other errors, the return
71516** code may be ignored.
71517*/
71518SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
71519  analysisInfo sInfo;
71520  HashElem *i;
71521  char *zSql;
71522  int rc;
71523
71524  assert( iDb>=0 && iDb<db->nDb );
71525  assert( db->aDb[iDb].pBt!=0 );
71526  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
71527
71528  /* Clear any prior statistics */
71529  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
71530    Index *pIdx = sqliteHashData(i);
71531    sqlite3DefaultRowEst(pIdx);
71532    sqlite3DeleteIndexSamples(pIdx);
71533  }
71534
71535  /* Check to make sure the sqlite_stat1 table exists */
71536  sInfo.db = db;
71537  sInfo.zDatabase = db->aDb[iDb].zName;
71538  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
71539    return SQLITE_ERROR;
71540  }
71541
71542  /* Load new statistics out of the sqlite_stat1 table */
71543  zSql = sqlite3MPrintf(db,
71544      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
71545  if( zSql==0 ){
71546    rc = SQLITE_NOMEM;
71547  }else{
71548    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
71549    sqlite3DbFree(db, zSql);
71550  }
71551
71552
71553  /* Load the statistics from the sqlite_stat2 table. */
71554#ifdef SQLITE_ENABLE_STAT2
71555  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
71556    rc = SQLITE_ERROR;
71557  }
71558  if( rc==SQLITE_OK ){
71559    sqlite3_stmt *pStmt = 0;
71560
71561    zSql = sqlite3MPrintf(db,
71562        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
71563    if( !zSql ){
71564      rc = SQLITE_NOMEM;
71565    }else{
71566      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
71567      sqlite3DbFree(db, zSql);
71568    }
71569
71570    if( rc==SQLITE_OK ){
71571      while( sqlite3_step(pStmt)==SQLITE_ROW ){
71572        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
71573        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
71574        if( pIdx ){
71575          int iSample = sqlite3_column_int(pStmt, 1);
71576          sqlite3 *dbMem = pIdx->pTable->dbMem;
71577          assert( dbMem==db || dbMem==0 );
71578          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
71579            int eType = sqlite3_column_type(pStmt, 2);
71580
71581            if( pIdx->aSample==0 ){
71582              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
71583              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
71584              if( pIdx->aSample==0 ){
71585                db->mallocFailed = 1;
71586                break;
71587              }
71588            }
71589
71590            assert( pIdx->aSample );
71591            {
71592              IndexSample *pSample = &pIdx->aSample[iSample];
71593              pSample->eType = (u8)eType;
71594              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
71595                pSample->u.r = sqlite3_column_double(pStmt, 2);
71596              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
71597                const char *z = (const char *)(
71598                    (eType==SQLITE_BLOB) ?
71599                    sqlite3_column_blob(pStmt, 2):
71600                    sqlite3_column_text(pStmt, 2)
71601                );
71602                int n = sqlite3_column_bytes(pStmt, 2);
71603                if( n>24 ){
71604                  n = 24;
71605                }
71606                pSample->nByte = (u8)n;
71607                if( n < 1){
71608                  pSample->u.z = 0;
71609                }else{
71610                  pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
71611                  if( pSample->u.z ){
71612                    memcpy(pSample->u.z, z, n);
71613                  }else{
71614                    db->mallocFailed = 1;
71615                    break;
71616                  }
71617                }
71618              }
71619            }
71620          }
71621        }
71622      }
71623      rc = sqlite3_finalize(pStmt);
71624    }
71625  }
71626#endif
71627
71628  if( rc==SQLITE_NOMEM ){
71629    db->mallocFailed = 1;
71630  }
71631  return rc;
71632}
71633
71634
71635#endif /* SQLITE_OMIT_ANALYZE */
71636
71637/************** End of analyze.c *********************************************/
71638/************** Begin file attach.c ******************************************/
71639/*
71640** 2003 April 6
71641**
71642** The author disclaims copyright to this source code.  In place of
71643** a legal notice, here is a blessing:
71644**
71645**    May you do good and not evil.
71646**    May you find forgiveness for yourself and forgive others.
71647**    May you share freely, never taking more than you give.
71648**
71649*************************************************************************
71650** This file contains code used to implement the ATTACH and DETACH commands.
71651*/
71652
71653#ifndef SQLITE_OMIT_ATTACH
71654/*
71655** Resolve an expression that was part of an ATTACH or DETACH statement. This
71656** is slightly different from resolving a normal SQL expression, because simple
71657** identifiers are treated as strings, not possible column names or aliases.
71658**
71659** i.e. if the parser sees:
71660**
71661**     ATTACH DATABASE abc AS def
71662**
71663** it treats the two expressions as literal strings 'abc' and 'def' instead of
71664** looking for columns of the same name.
71665**
71666** This only applies to the root node of pExpr, so the statement:
71667**
71668**     ATTACH DATABASE abc||def AS 'db2'
71669**
71670** will fail because neither abc or def can be resolved.
71671*/
71672static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
71673{
71674  int rc = SQLITE_OK;
71675  if( pExpr ){
71676    if( pExpr->op!=TK_ID ){
71677      rc = sqlite3ResolveExprNames(pName, pExpr);
71678      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
71679        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
71680        return SQLITE_ERROR;
71681      }
71682    }else{
71683      pExpr->op = TK_STRING;
71684    }
71685  }
71686  return rc;
71687}
71688
71689/*
71690** An SQL user-function registered to do the work of an ATTACH statement. The
71691** three arguments to the function come directly from an attach statement:
71692**
71693**     ATTACH DATABASE x AS y KEY z
71694**
71695**     SELECT sqlite_attach(x, y, z)
71696**
71697** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
71698** third argument.
71699*/
71700static void attachFunc(
71701  sqlite3_context *context,
71702  int NotUsed,
71703  sqlite3_value **argv
71704){
71705  int i;
71706  int rc = 0;
71707  sqlite3 *db = sqlite3_context_db_handle(context);
71708  const char *zName;
71709  const char *zFile;
71710  Db *aNew;
71711  char *zErrDyn = 0;
71712
71713  UNUSED_PARAMETER(NotUsed);
71714
71715  zFile = (const char *)sqlite3_value_text(argv[0]);
71716  zName = (const char *)sqlite3_value_text(argv[1]);
71717  if( zFile==0 ) zFile = "";
71718  if( zName==0 ) zName = "";
71719
71720  /* Check for the following errors:
71721  **
71722  **     * Too many attached databases,
71723  **     * Transaction currently open
71724  **     * Specified database name already being used.
71725  */
71726  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
71727    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
71728      db->aLimit[SQLITE_LIMIT_ATTACHED]
71729    );
71730    goto attach_error;
71731  }
71732  if( !db->autoCommit ){
71733    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
71734    goto attach_error;
71735  }
71736  for(i=0; i<db->nDb; i++){
71737    char *z = db->aDb[i].zName;
71738    assert( z && zName );
71739    if( sqlite3StrICmp(z, zName)==0 ){
71740      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
71741      goto attach_error;
71742    }
71743  }
71744
71745  /* Allocate the new entry in the db->aDb[] array and initialise the schema
71746  ** hash tables.
71747  */
71748  if( db->aDb==db->aDbStatic ){
71749    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
71750    if( aNew==0 ) return;
71751    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
71752  }else{
71753    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
71754    if( aNew==0 ) return;
71755  }
71756  db->aDb = aNew;
71757  aNew = &db->aDb[db->nDb];
71758  memset(aNew, 0, sizeof(*aNew));
71759
71760  /* Open the database file. If the btree is successfully opened, use
71761  ** it to obtain the database schema. At this point the schema may
71762  ** or may not be initialised.
71763  */
71764  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
71765                           db->openFlags | SQLITE_OPEN_MAIN_DB,
71766                           &aNew->pBt);
71767  db->nDb++;
71768  if( rc==SQLITE_CONSTRAINT ){
71769    rc = SQLITE_ERROR;
71770    zErrDyn = sqlite3MPrintf(db, "database is already attached");
71771  }else if( rc==SQLITE_OK ){
71772    Pager *pPager;
71773    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
71774    if( !aNew->pSchema ){
71775      rc = SQLITE_NOMEM;
71776    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
71777      zErrDyn = sqlite3MPrintf(db,
71778        "attached databases must use the same text encoding as main database");
71779      rc = SQLITE_ERROR;
71780    }
71781    pPager = sqlite3BtreePager(aNew->pBt);
71782    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
71783    /* journal_mode set by the OP_JournalMode opcode that will following
71784    ** the OP_Function opcode that invoked this function. */
71785    sqlite3BtreeSecureDelete(aNew->pBt,
71786                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
71787  }
71788  aNew->safety_level = 3;
71789  aNew->zName = sqlite3DbStrDup(db, zName);
71790  if( rc==SQLITE_OK && aNew->zName==0 ){
71791    rc = SQLITE_NOMEM;
71792  }
71793
71794
71795#ifdef SQLITE_HAS_CODEC
71796  if( rc==SQLITE_OK ){
71797    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
71798    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
71799    int nKey;
71800    char *zKey;
71801    int t = sqlite3_value_type(argv[2]);
71802    switch( t ){
71803      case SQLITE_INTEGER:
71804      case SQLITE_FLOAT:
71805        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
71806        rc = SQLITE_ERROR;
71807        break;
71808
71809      case SQLITE_TEXT:
71810      case SQLITE_BLOB:
71811        nKey = sqlite3_value_bytes(argv[2]);
71812        zKey = (char *)sqlite3_value_blob(argv[2]);
71813        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
71814        break;
71815
71816      case SQLITE_NULL:
71817        /* No key specified.  Use the key from the main database */
71818        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
71819        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
71820        break;
71821    }
71822  }
71823#endif
71824
71825  /* If the file was opened successfully, read the schema for the new database.
71826  ** If this fails, or if opening the file failed, then close the file and
71827  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
71828  ** we found it.
71829  */
71830  if( rc==SQLITE_OK ){
71831    sqlite3BtreeEnterAll(db);
71832    rc = sqlite3Init(db, &zErrDyn);
71833    sqlite3BtreeLeaveAll(db);
71834  }
71835  if( rc ){
71836    int iDb = db->nDb - 1;
71837    assert( iDb>=2 );
71838    if( db->aDb[iDb].pBt ){
71839      sqlite3BtreeClose(db->aDb[iDb].pBt);
71840      db->aDb[iDb].pBt = 0;
71841      db->aDb[iDb].pSchema = 0;
71842    }
71843    sqlite3ResetInternalSchema(db, 0);
71844    db->nDb = iDb;
71845    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
71846      db->mallocFailed = 1;
71847      sqlite3DbFree(db, zErrDyn);
71848      zErrDyn = sqlite3MPrintf(db, "out of memory");
71849    }else if( zErrDyn==0 ){
71850      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
71851    }
71852    goto attach_error;
71853  }
71854
71855  return;
71856
71857attach_error:
71858  /* Return an error if we get here */
71859  if( zErrDyn ){
71860    sqlite3_result_error(context, zErrDyn, -1);
71861    sqlite3DbFree(db, zErrDyn);
71862  }
71863  if( rc ) sqlite3_result_error_code(context, rc);
71864}
71865
71866/*
71867** An SQL user-function registered to do the work of an DETACH statement. The
71868** three arguments to the function come directly from a detach statement:
71869**
71870**     DETACH DATABASE x
71871**
71872**     SELECT sqlite_detach(x)
71873*/
71874static void detachFunc(
71875  sqlite3_context *context,
71876  int NotUsed,
71877  sqlite3_value **argv
71878){
71879  const char *zName = (const char *)sqlite3_value_text(argv[0]);
71880  sqlite3 *db = sqlite3_context_db_handle(context);
71881  int i;
71882  Db *pDb = 0;
71883  char zErr[128];
71884
71885  UNUSED_PARAMETER(NotUsed);
71886
71887  if( zName==0 ) zName = "";
71888  for(i=0; i<db->nDb; i++){
71889    pDb = &db->aDb[i];
71890    if( pDb->pBt==0 ) continue;
71891    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
71892  }
71893
71894  if( i>=db->nDb ){
71895    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
71896    goto detach_error;
71897  }
71898  if( i<2 ){
71899    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
71900    goto detach_error;
71901  }
71902  if( !db->autoCommit ){
71903    sqlite3_snprintf(sizeof(zErr), zErr,
71904                     "cannot DETACH database within transaction");
71905    goto detach_error;
71906  }
71907  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
71908    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
71909    goto detach_error;
71910  }
71911
71912  sqlite3BtreeClose(pDb->pBt);
71913  pDb->pBt = 0;
71914  pDb->pSchema = 0;
71915  sqlite3ResetInternalSchema(db, 0);
71916  return;
71917
71918detach_error:
71919  sqlite3_result_error(context, zErr, -1);
71920}
71921
71922/*
71923** This procedure generates VDBE code for a single invocation of either the
71924** sqlite_detach() or sqlite_attach() SQL user functions.
71925*/
71926static void codeAttach(
71927  Parse *pParse,       /* The parser context */
71928  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
71929  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
71930  Expr *pAuthArg,      /* Expression to pass to authorization callback */
71931  Expr *pFilename,     /* Name of database file */
71932  Expr *pDbname,       /* Name of the database to use internally */
71933  Expr *pKey           /* Database key for encryption extension */
71934){
71935  int rc;
71936  NameContext sName;
71937  Vdbe *v;
71938  sqlite3* db = pParse->db;
71939  int regArgs;
71940
71941  memset(&sName, 0, sizeof(NameContext));
71942  sName.pParse = pParse;
71943
71944  if(
71945      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
71946      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
71947      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
71948  ){
71949    pParse->nErr++;
71950    goto attach_end;
71951  }
71952
71953#ifndef SQLITE_OMIT_AUTHORIZATION
71954  if( pAuthArg ){
71955    char *zAuthArg = pAuthArg->u.zToken;
71956    if( NEVER(zAuthArg==0) ){
71957      goto attach_end;
71958    }
71959    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
71960    if(rc!=SQLITE_OK ){
71961      goto attach_end;
71962    }
71963  }
71964#endif /* SQLITE_OMIT_AUTHORIZATION */
71965
71966
71967  v = sqlite3GetVdbe(pParse);
71968  regArgs = sqlite3GetTempRange(pParse, 4);
71969  sqlite3ExprCode(pParse, pFilename, regArgs);
71970  sqlite3ExprCode(pParse, pDbname, regArgs+1);
71971  sqlite3ExprCode(pParse, pKey, regArgs+2);
71972
71973  assert( v || db->mallocFailed );
71974  if( v ){
71975    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
71976    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
71977    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
71978    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
71979
71980    if( type==SQLITE_ATTACH ){
71981      /* On an attach, also set the journal mode.  Note that
71982      ** sqlite3VdbeUsesBtree() is not call here since the iDb index
71983      ** will be out of range prior to the new database being attached.
71984      ** The OP_JournalMode opcode will all sqlite3VdbeUsesBtree() for us.
71985      */
71986      sqlite3VdbeAddOp3(v, OP_JournalMode, db->nDb, regArgs+3,
71987                           db->dfltJournalMode);
71988      sqlite3VdbeChangeP5(v, 1);
71989    }
71990
71991    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
71992    ** statement only). For DETACH, set it to false (expire all existing
71993    ** statements).
71994    */
71995    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
71996  }
71997
71998attach_end:
71999  sqlite3ExprDelete(db, pFilename);
72000  sqlite3ExprDelete(db, pDbname);
72001  sqlite3ExprDelete(db, pKey);
72002}
72003
72004/*
72005** Called by the parser to compile a DETACH statement.
72006**
72007**     DETACH pDbname
72008*/
72009SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
72010  static const FuncDef detach_func = {
72011    1,                /* nArg */
72012    SQLITE_UTF8,      /* iPrefEnc */
72013    0,                /* flags */
72014    0,                /* pUserData */
72015    0,                /* pNext */
72016    detachFunc,       /* xFunc */
72017    0,                /* xStep */
72018    0,                /* xFinalize */
72019    "sqlite_detach",  /* zName */
72020    0                 /* pHash */
72021  };
72022  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
72023}
72024
72025/*
72026** Called by the parser to compile an ATTACH statement.
72027**
72028**     ATTACH p AS pDbname KEY pKey
72029*/
72030SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
72031  static const FuncDef attach_func = {
72032    3,                /* nArg */
72033    SQLITE_UTF8,      /* iPrefEnc */
72034    0,                /* flags */
72035    0,                /* pUserData */
72036    0,                /* pNext */
72037    attachFunc,       /* xFunc */
72038    0,                /* xStep */
72039    0,                /* xFinalize */
72040    "sqlite_attach",  /* zName */
72041    0                 /* pHash */
72042  };
72043  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
72044}
72045#endif /* SQLITE_OMIT_ATTACH */
72046
72047/*
72048** Initialize a DbFixer structure.  This routine must be called prior
72049** to passing the structure to one of the sqliteFixAAAA() routines below.
72050**
72051** The return value indicates whether or not fixation is required.  TRUE
72052** means we do need to fix the database references, FALSE means we do not.
72053*/
72054SQLITE_PRIVATE int sqlite3FixInit(
72055  DbFixer *pFix,      /* The fixer to be initialized */
72056  Parse *pParse,      /* Error messages will be written here */
72057  int iDb,            /* This is the database that must be used */
72058  const char *zType,  /* "view", "trigger", or "index" */
72059  const Token *pName  /* Name of the view, trigger, or index */
72060){
72061  sqlite3 *db;
72062
72063  if( NEVER(iDb<0) || iDb==1 ) return 0;
72064  db = pParse->db;
72065  assert( db->nDb>iDb );
72066  pFix->pParse = pParse;
72067  pFix->zDb = db->aDb[iDb].zName;
72068  pFix->zType = zType;
72069  pFix->pName = pName;
72070  return 1;
72071}
72072
72073/*
72074** The following set of routines walk through the parse tree and assign
72075** a specific database to all table references where the database name
72076** was left unspecified in the original SQL statement.  The pFix structure
72077** must have been initialized by a prior call to sqlite3FixInit().
72078**
72079** These routines are used to make sure that an index, trigger, or
72080** view in one database does not refer to objects in a different database.
72081** (Exception: indices, triggers, and views in the TEMP database are
72082** allowed to refer to anything.)  If a reference is explicitly made
72083** to an object in a different database, an error message is added to
72084** pParse->zErrMsg and these routines return non-zero.  If everything
72085** checks out, these routines return 0.
72086*/
72087SQLITE_PRIVATE int sqlite3FixSrcList(
72088  DbFixer *pFix,       /* Context of the fixation */
72089  SrcList *pList       /* The Source list to check and modify */
72090){
72091  int i;
72092  const char *zDb;
72093  struct SrcList_item *pItem;
72094
72095  if( NEVER(pList==0) ) return 0;
72096  zDb = pFix->zDb;
72097  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
72098    if( pItem->zDatabase==0 ){
72099      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
72100    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
72101      sqlite3ErrorMsg(pFix->pParse,
72102         "%s %T cannot reference objects in database %s",
72103         pFix->zType, pFix->pName, pItem->zDatabase);
72104      return 1;
72105    }
72106#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72107    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
72108    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
72109#endif
72110  }
72111  return 0;
72112}
72113#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72114SQLITE_PRIVATE int sqlite3FixSelect(
72115  DbFixer *pFix,       /* Context of the fixation */
72116  Select *pSelect      /* The SELECT statement to be fixed to one database */
72117){
72118  while( pSelect ){
72119    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
72120      return 1;
72121    }
72122    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
72123      return 1;
72124    }
72125    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
72126      return 1;
72127    }
72128    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
72129      return 1;
72130    }
72131    pSelect = pSelect->pPrior;
72132  }
72133  return 0;
72134}
72135SQLITE_PRIVATE int sqlite3FixExpr(
72136  DbFixer *pFix,     /* Context of the fixation */
72137  Expr *pExpr        /* The expression to be fixed to one database */
72138){
72139  while( pExpr ){
72140    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
72141    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72142      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
72143    }else{
72144      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
72145    }
72146    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
72147      return 1;
72148    }
72149    pExpr = pExpr->pLeft;
72150  }
72151  return 0;
72152}
72153SQLITE_PRIVATE int sqlite3FixExprList(
72154  DbFixer *pFix,     /* Context of the fixation */
72155  ExprList *pList    /* The expression to be fixed to one database */
72156){
72157  int i;
72158  struct ExprList_item *pItem;
72159  if( pList==0 ) return 0;
72160  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
72161    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
72162      return 1;
72163    }
72164  }
72165  return 0;
72166}
72167#endif
72168
72169#ifndef SQLITE_OMIT_TRIGGER
72170SQLITE_PRIVATE int sqlite3FixTriggerStep(
72171  DbFixer *pFix,     /* Context of the fixation */
72172  TriggerStep *pStep /* The trigger step be fixed to one database */
72173){
72174  while( pStep ){
72175    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
72176      return 1;
72177    }
72178    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
72179      return 1;
72180    }
72181    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
72182      return 1;
72183    }
72184    pStep = pStep->pNext;
72185  }
72186  return 0;
72187}
72188#endif
72189
72190/************** End of attach.c **********************************************/
72191/************** Begin file auth.c ********************************************/
72192/*
72193** 2003 January 11
72194**
72195** The author disclaims copyright to this source code.  In place of
72196** a legal notice, here is a blessing:
72197**
72198**    May you do good and not evil.
72199**    May you find forgiveness for yourself and forgive others.
72200**    May you share freely, never taking more than you give.
72201**
72202*************************************************************************
72203** This file contains code used to implement the sqlite3_set_authorizer()
72204** API.  This facility is an optional feature of the library.  Embedded
72205** systems that do not need this facility may omit it by recompiling
72206** the library with -DSQLITE_OMIT_AUTHORIZATION=1
72207*/
72208
72209/*
72210** All of the code in this file may be omitted by defining a single
72211** macro.
72212*/
72213#ifndef SQLITE_OMIT_AUTHORIZATION
72214
72215/*
72216** Set or clear the access authorization function.
72217**
72218** The access authorization function is be called during the compilation
72219** phase to verify that the user has read and/or write access permission on
72220** various fields of the database.  The first argument to the auth function
72221** is a copy of the 3rd argument to this routine.  The second argument
72222** to the auth function is one of these constants:
72223**
72224**       SQLITE_CREATE_INDEX
72225**       SQLITE_CREATE_TABLE
72226**       SQLITE_CREATE_TEMP_INDEX
72227**       SQLITE_CREATE_TEMP_TABLE
72228**       SQLITE_CREATE_TEMP_TRIGGER
72229**       SQLITE_CREATE_TEMP_VIEW
72230**       SQLITE_CREATE_TRIGGER
72231**       SQLITE_CREATE_VIEW
72232**       SQLITE_DELETE
72233**       SQLITE_DROP_INDEX
72234**       SQLITE_DROP_TABLE
72235**       SQLITE_DROP_TEMP_INDEX
72236**       SQLITE_DROP_TEMP_TABLE
72237**       SQLITE_DROP_TEMP_TRIGGER
72238**       SQLITE_DROP_TEMP_VIEW
72239**       SQLITE_DROP_TRIGGER
72240**       SQLITE_DROP_VIEW
72241**       SQLITE_INSERT
72242**       SQLITE_PRAGMA
72243**       SQLITE_READ
72244**       SQLITE_SELECT
72245**       SQLITE_TRANSACTION
72246**       SQLITE_UPDATE
72247**
72248** The third and fourth arguments to the auth function are the name of
72249** the table and the column that are being accessed.  The auth function
72250** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
72251** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
72252** means that the SQL statement will never-run - the sqlite3_exec() call
72253** will return with an error.  SQLITE_IGNORE means that the SQL statement
72254** should run but attempts to read the specified column will return NULL
72255** and attempts to write the column will be ignored.
72256**
72257** Setting the auth function to NULL disables this hook.  The default
72258** setting of the auth function is NULL.
72259*/
72260SQLITE_API int sqlite3_set_authorizer(
72261  sqlite3 *db,
72262  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
72263  void *pArg
72264){
72265  sqlite3_mutex_enter(db->mutex);
72266  db->xAuth = xAuth;
72267  db->pAuthArg = pArg;
72268  sqlite3ExpirePreparedStatements(db);
72269  sqlite3_mutex_leave(db->mutex);
72270  return SQLITE_OK;
72271}
72272
72273/*
72274** Write an error message into pParse->zErrMsg that explains that the
72275** user-supplied authorization function returned an illegal value.
72276*/
72277static void sqliteAuthBadReturnCode(Parse *pParse){
72278  sqlite3ErrorMsg(pParse, "authorizer malfunction");
72279  pParse->rc = SQLITE_ERROR;
72280}
72281
72282/*
72283** Invoke the authorization callback for permission to read column zCol from
72284** table zTab in database zDb. This function assumes that an authorization
72285** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
72286**
72287** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
72288** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
72289** is treated as SQLITE_DENY. In this case an error is left in pParse.
72290*/
72291SQLITE_PRIVATE int sqlite3AuthReadCol(
72292  Parse *pParse,                  /* The parser context */
72293  const char *zTab,               /* Table name */
72294  const char *zCol,               /* Column name */
72295  int iDb                         /* Index of containing database. */
72296){
72297  sqlite3 *db = pParse->db;       /* Database handle */
72298  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
72299  int rc;                         /* Auth callback return code */
72300
72301  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
72302  if( rc==SQLITE_DENY ){
72303    if( db->nDb>2 || iDb!=0 ){
72304      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
72305    }else{
72306      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
72307    }
72308    pParse->rc = SQLITE_AUTH;
72309  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
72310    sqliteAuthBadReturnCode(pParse);
72311  }
72312  return rc;
72313}
72314
72315/*
72316** The pExpr should be a TK_COLUMN expression.  The table referred to
72317** is in pTabList or else it is the NEW or OLD table of a trigger.
72318** Check to see if it is OK to read this particular column.
72319**
72320** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
72321** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
72322** then generate an error.
72323*/
72324SQLITE_PRIVATE void sqlite3AuthRead(
72325  Parse *pParse,        /* The parser context */
72326  Expr *pExpr,          /* The expression to check authorization on */
72327  Schema *pSchema,      /* The schema of the expression */
72328  SrcList *pTabList     /* All table that pExpr might refer to */
72329){
72330  sqlite3 *db = pParse->db;
72331  Table *pTab = 0;      /* The table being read */
72332  const char *zCol;     /* Name of the column of the table */
72333  int iSrc;             /* Index in pTabList->a[] of table being read */
72334  int iDb;              /* The index of the database the expression refers to */
72335  int iCol;             /* Index of column in table */
72336
72337  if( db->xAuth==0 ) return;
72338  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
72339  if( iDb<0 ){
72340    /* An attempt to read a column out of a subquery or other
72341    ** temporary table. */
72342    return;
72343  }
72344
72345  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
72346  if( pExpr->op==TK_TRIGGER ){
72347    pTab = pParse->pTriggerTab;
72348  }else{
72349    assert( pTabList );
72350    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
72351      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
72352        pTab = pTabList->a[iSrc].pTab;
72353        break;
72354      }
72355    }
72356  }
72357  iCol = pExpr->iColumn;
72358  if( NEVER(pTab==0) ) return;
72359
72360  if( iCol>=0 ){
72361    assert( iCol<pTab->nCol );
72362    zCol = pTab->aCol[iCol].zName;
72363  }else if( pTab->iPKey>=0 ){
72364    assert( pTab->iPKey<pTab->nCol );
72365    zCol = pTab->aCol[pTab->iPKey].zName;
72366  }else{
72367    zCol = "ROWID";
72368  }
72369  assert( iDb>=0 && iDb<db->nDb );
72370  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
72371    pExpr->op = TK_NULL;
72372  }
72373}
72374
72375/*
72376** Do an authorization check using the code and arguments given.  Return
72377** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
72378** is returned, then the error count and error message in pParse are
72379** modified appropriately.
72380*/
72381SQLITE_PRIVATE int sqlite3AuthCheck(
72382  Parse *pParse,
72383  int code,
72384  const char *zArg1,
72385  const char *zArg2,
72386  const char *zArg3
72387){
72388  sqlite3 *db = pParse->db;
72389  int rc;
72390
72391  /* Don't do any authorization checks if the database is initialising
72392  ** or if the parser is being invoked from within sqlite3_declare_vtab.
72393  */
72394  if( db->init.busy || IN_DECLARE_VTAB ){
72395    return SQLITE_OK;
72396  }
72397
72398  if( db->xAuth==0 ){
72399    return SQLITE_OK;
72400  }
72401  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
72402  if( rc==SQLITE_DENY ){
72403    sqlite3ErrorMsg(pParse, "not authorized");
72404    pParse->rc = SQLITE_AUTH;
72405  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
72406    rc = SQLITE_DENY;
72407    sqliteAuthBadReturnCode(pParse);
72408  }
72409  return rc;
72410}
72411
72412/*
72413** Push an authorization context.  After this routine is called, the
72414** zArg3 argument to authorization callbacks will be zContext until
72415** popped.  Or if pParse==0, this routine is a no-op.
72416*/
72417SQLITE_PRIVATE void sqlite3AuthContextPush(
72418  Parse *pParse,
72419  AuthContext *pContext,
72420  const char *zContext
72421){
72422  assert( pParse );
72423  pContext->pParse = pParse;
72424  pContext->zAuthContext = pParse->zAuthContext;
72425  pParse->zAuthContext = zContext;
72426}
72427
72428/*
72429** Pop an authorization context that was previously pushed
72430** by sqlite3AuthContextPush
72431*/
72432SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
72433  if( pContext->pParse ){
72434    pContext->pParse->zAuthContext = pContext->zAuthContext;
72435    pContext->pParse = 0;
72436  }
72437}
72438
72439#endif /* SQLITE_OMIT_AUTHORIZATION */
72440
72441/************** End of auth.c ************************************************/
72442/************** Begin file build.c *******************************************/
72443/*
72444** 2001 September 15
72445**
72446** The author disclaims copyright to this source code.  In place of
72447** a legal notice, here is a blessing:
72448**
72449**    May you do good and not evil.
72450**    May you find forgiveness for yourself and forgive others.
72451**    May you share freely, never taking more than you give.
72452**
72453*************************************************************************
72454** This file contains C code routines that are called by the SQLite parser
72455** when syntax rules are reduced.  The routines in this file handle the
72456** following kinds of SQL syntax:
72457**
72458**     CREATE TABLE
72459**     DROP TABLE
72460**     CREATE INDEX
72461**     DROP INDEX
72462**     creating ID lists
72463**     BEGIN TRANSACTION
72464**     COMMIT
72465**     ROLLBACK
72466*/
72467
72468/*
72469** This routine is called when a new SQL statement is beginning to
72470** be parsed.  Initialize the pParse structure as needed.
72471*/
72472SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
72473  pParse->explain = (u8)explainFlag;
72474  pParse->nVar = 0;
72475}
72476
72477#ifndef SQLITE_OMIT_SHARED_CACHE
72478/*
72479** The TableLock structure is only used by the sqlite3TableLock() and
72480** codeTableLocks() functions.
72481*/
72482struct TableLock {
72483  int iDb;             /* The database containing the table to be locked */
72484  int iTab;            /* The root page of the table to be locked */
72485  u8 isWriteLock;      /* True for write lock.  False for a read lock */
72486  const char *zName;   /* Name of the table */
72487};
72488
72489/*
72490** Record the fact that we want to lock a table at run-time.
72491**
72492** The table to be locked has root page iTab and is found in database iDb.
72493** A read or a write lock can be taken depending on isWritelock.
72494**
72495** This routine just records the fact that the lock is desired.  The
72496** code to make the lock occur is generated by a later call to
72497** codeTableLocks() which occurs during sqlite3FinishCoding().
72498*/
72499SQLITE_PRIVATE void sqlite3TableLock(
72500  Parse *pParse,     /* Parsing context */
72501  int iDb,           /* Index of the database containing the table to lock */
72502  int iTab,          /* Root page number of the table to be locked */
72503  u8 isWriteLock,    /* True for a write lock */
72504  const char *zName  /* Name of the table to be locked */
72505){
72506  Parse *pToplevel = sqlite3ParseToplevel(pParse);
72507  int i;
72508  int nBytes;
72509  TableLock *p;
72510  assert( iDb>=0 );
72511
72512  for(i=0; i<pToplevel->nTableLock; i++){
72513    p = &pToplevel->aTableLock[i];
72514    if( p->iDb==iDb && p->iTab==iTab ){
72515      p->isWriteLock = (p->isWriteLock || isWriteLock);
72516      return;
72517    }
72518  }
72519
72520  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
72521  pToplevel->aTableLock =
72522      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
72523  if( pToplevel->aTableLock ){
72524    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
72525    p->iDb = iDb;
72526    p->iTab = iTab;
72527    p->isWriteLock = isWriteLock;
72528    p->zName = zName;
72529  }else{
72530    pToplevel->nTableLock = 0;
72531    pToplevel->db->mallocFailed = 1;
72532  }
72533}
72534
72535/*
72536** Code an OP_TableLock instruction for each table locked by the
72537** statement (configured by calls to sqlite3TableLock()).
72538*/
72539static void codeTableLocks(Parse *pParse){
72540  int i;
72541  Vdbe *pVdbe;
72542
72543  pVdbe = sqlite3GetVdbe(pParse);
72544  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
72545
72546  for(i=0; i<pParse->nTableLock; i++){
72547    TableLock *p = &pParse->aTableLock[i];
72548    int p1 = p->iDb;
72549    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
72550                      p->zName, P4_STATIC);
72551  }
72552}
72553#else
72554  #define codeTableLocks(x)
72555#endif
72556
72557/*
72558** This routine is called after a single SQL statement has been
72559** parsed and a VDBE program to execute that statement has been
72560** prepared.  This routine puts the finishing touches on the
72561** VDBE program and resets the pParse structure for the next
72562** parse.
72563**
72564** Note that if an error occurred, it might be the case that
72565** no VDBE code was generated.
72566*/
72567SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
72568  sqlite3 *db;
72569  Vdbe *v;
72570
72571  db = pParse->db;
72572  if( db->mallocFailed ) return;
72573  if( pParse->nested ) return;
72574  if( pParse->nErr ) return;
72575
72576  /* Begin by generating some termination code at the end of the
72577  ** vdbe program
72578  */
72579  v = sqlite3GetVdbe(pParse);
72580  assert( !pParse->isMultiWrite
72581       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
72582  if( v ){
72583    sqlite3VdbeAddOp0(v, OP_Halt);
72584
72585    /* The cookie mask contains one bit for each database file open.
72586    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
72587    ** set for each database that is used.  Generate code to start a
72588    ** transaction on each used database and to verify the schema cookie
72589    ** on each used database.
72590    */
72591    if( pParse->cookieGoto>0 ){
72592      u32 mask;
72593      int iDb;
72594      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
72595      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
72596        if( (mask & pParse->cookieMask)==0 ) continue;
72597        sqlite3VdbeUsesBtree(v, iDb);
72598        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
72599        if( db->init.busy==0 ){
72600          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
72601        }
72602      }
72603#ifndef SQLITE_OMIT_VIRTUALTABLE
72604      {
72605        int i;
72606        for(i=0; i<pParse->nVtabLock; i++){
72607          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
72608          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
72609        }
72610        pParse->nVtabLock = 0;
72611      }
72612#endif
72613
72614      /* Once all the cookies have been verified and transactions opened,
72615      ** obtain the required table-locks. This is a no-op unless the
72616      ** shared-cache feature is enabled.
72617      */
72618      codeTableLocks(pParse);
72619
72620      /* Initialize any AUTOINCREMENT data structures required.
72621      */
72622      sqlite3AutoincrementBegin(pParse);
72623
72624      /* Finally, jump back to the beginning of the executable code. */
72625      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
72626    }
72627  }
72628
72629
72630  /* Get the VDBE program ready for execution
72631  */
72632  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
72633#ifdef SQLITE_DEBUG
72634    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
72635    sqlite3VdbeTrace(v, trace);
72636#endif
72637    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
72638    /* A minimum of one cursor is required if autoincrement is used
72639    *  See ticket [a696379c1f08866] */
72640    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
72641    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
72642                         pParse->nTab, pParse->nMaxArg, pParse->explain,
72643                         pParse->isMultiWrite && pParse->mayAbort);
72644    pParse->rc = SQLITE_DONE;
72645    pParse->colNamesSet = 0;
72646  }else{
72647    pParse->rc = SQLITE_ERROR;
72648  }
72649  pParse->nTab = 0;
72650  pParse->nMem = 0;
72651  pParse->nSet = 0;
72652  pParse->nVar = 0;
72653  pParse->cookieMask = 0;
72654  pParse->cookieGoto = 0;
72655}
72656
72657/*
72658** Run the parser and code generator recursively in order to generate
72659** code for the SQL statement given onto the end of the pParse context
72660** currently under construction.  When the parser is run recursively
72661** this way, the final OP_Halt is not appended and other initialization
72662** and finalization steps are omitted because those are handling by the
72663** outermost parser.
72664**
72665** Not everything is nestable.  This facility is designed to permit
72666** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
72667** care if you decide to try to use this routine for some other purposes.
72668*/
72669SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
72670  va_list ap;
72671  char *zSql;
72672  char *zErrMsg = 0;
72673  sqlite3 *db = pParse->db;
72674# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
72675  char saveBuf[SAVE_SZ];
72676
72677  if( pParse->nErr ) return;
72678  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
72679  va_start(ap, zFormat);
72680  zSql = sqlite3VMPrintf(db, zFormat, ap);
72681  va_end(ap);
72682  if( zSql==0 ){
72683    return;   /* A malloc must have failed */
72684  }
72685  pParse->nested++;
72686  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
72687  memset(&pParse->nVar, 0, SAVE_SZ);
72688  sqlite3RunParser(pParse, zSql, &zErrMsg);
72689  sqlite3DbFree(db, zErrMsg);
72690  sqlite3DbFree(db, zSql);
72691  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
72692  pParse->nested--;
72693}
72694
72695/*
72696** Locate the in-memory structure that describes a particular database
72697** table given the name of that table and (optionally) the name of the
72698** database containing the table.  Return NULL if not found.
72699**
72700** If zDatabase is 0, all databases are searched for the table and the
72701** first matching table is returned.  (No checking for duplicate table
72702** names is done.)  The search order is TEMP first, then MAIN, then any
72703** auxiliary databases added using the ATTACH command.
72704**
72705** See also sqlite3LocateTable().
72706*/
72707SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
72708  Table *p = 0;
72709  int i;
72710  int nName;
72711  assert( zName!=0 );
72712  nName = sqlite3Strlen30(zName);
72713  for(i=OMIT_TEMPDB; i<db->nDb; i++){
72714    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
72715    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
72716    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
72717    if( p ) break;
72718  }
72719  return p;
72720}
72721
72722/*
72723** Locate the in-memory structure that describes a particular database
72724** table given the name of that table and (optionally) the name of the
72725** database containing the table.  Return NULL if not found.  Also leave an
72726** error message in pParse->zErrMsg.
72727**
72728** The difference between this routine and sqlite3FindTable() is that this
72729** routine leaves an error message in pParse->zErrMsg where
72730** sqlite3FindTable() does not.
72731*/
72732SQLITE_PRIVATE Table *sqlite3LocateTable(
72733  Parse *pParse,         /* context in which to report errors */
72734  int isView,            /* True if looking for a VIEW rather than a TABLE */
72735  const char *zName,     /* Name of the table we are looking for */
72736  const char *zDbase     /* Name of the database.  Might be NULL */
72737){
72738  Table *p;
72739
72740  /* Read the database schema. If an error occurs, leave an error message
72741  ** and code in pParse and return NULL. */
72742  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
72743    return 0;
72744  }
72745
72746  p = sqlite3FindTable(pParse->db, zName, zDbase);
72747  if( p==0 ){
72748    const char *zMsg = isView ? "no such view" : "no such table";
72749    if( zDbase ){
72750      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
72751    }else{
72752      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
72753    }
72754    pParse->checkSchema = 1;
72755  }
72756  return p;
72757}
72758
72759/*
72760** Locate the in-memory structure that describes
72761** a particular index given the name of that index
72762** and the name of the database that contains the index.
72763** Return NULL if not found.
72764**
72765** If zDatabase is 0, all databases are searched for the
72766** table and the first matching index is returned.  (No checking
72767** for duplicate index names is done.)  The search order is
72768** TEMP first, then MAIN, then any auxiliary databases added
72769** using the ATTACH command.
72770*/
72771SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
72772  Index *p = 0;
72773  int i;
72774  int nName = sqlite3Strlen30(zName);
72775  for(i=OMIT_TEMPDB; i<db->nDb; i++){
72776    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
72777    Schema *pSchema = db->aDb[j].pSchema;
72778    assert( pSchema );
72779    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
72780    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
72781    if( p ) break;
72782  }
72783  return p;
72784}
72785
72786/*
72787** Reclaim the memory used by an index
72788*/
72789static void freeIndex(Index *p){
72790  sqlite3 *db = p->pTable->dbMem;
72791#ifndef SQLITE_OMIT_ANALYZE
72792  sqlite3DeleteIndexSamples(p);
72793#endif
72794  sqlite3DbFree(db, p->zColAff);
72795  sqlite3DbFree(db, p);
72796}
72797
72798/*
72799** Remove the given index from the index hash table, and free
72800** its memory structures.
72801**
72802** The index is removed from the database hash tables but
72803** it is not unlinked from the Table that it indexes.
72804** Unlinking from the Table must be done by the calling function.
72805*/
72806static void sqlite3DeleteIndex(Index *p){
72807  Index *pOld;
72808  const char *zName = p->zName;
72809
72810  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
72811                           sqlite3Strlen30(zName), 0);
72812  assert( pOld==0 || pOld==p );
72813  freeIndex(p);
72814}
72815
72816/*
72817** For the index called zIdxName which is found in the database iDb,
72818** unlike that index from its Table then remove the index from
72819** the index hash table and free all memory structures associated
72820** with the index.
72821*/
72822SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
72823  Index *pIndex;
72824  int len;
72825  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
72826
72827  len = sqlite3Strlen30(zIdxName);
72828  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
72829  if( pIndex ){
72830    if( pIndex->pTable->pIndex==pIndex ){
72831      pIndex->pTable->pIndex = pIndex->pNext;
72832    }else{
72833      Index *p;
72834      /* Justification of ALWAYS();  The index must be on the list of
72835      ** indices. */
72836      p = pIndex->pTable->pIndex;
72837      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
72838      if( ALWAYS(p && p->pNext==pIndex) ){
72839        p->pNext = pIndex->pNext;
72840      }
72841    }
72842    freeIndex(pIndex);
72843  }
72844  db->flags |= SQLITE_InternChanges;
72845}
72846
72847/*
72848** Erase all schema information from the in-memory hash tables of
72849** a single database.  This routine is called to reclaim memory
72850** before the database closes.  It is also called during a rollback
72851** if there were schema changes during the transaction or if a
72852** schema-cookie mismatch occurs.
72853**
72854** If iDb==0 then reset the internal schema tables for all database
72855** files.  If iDb>=1 then reset the internal schema for only the
72856** single file indicated.
72857*/
72858SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
72859  int i, j;
72860  assert( iDb>=0 && iDb<db->nDb );
72861
72862  if( iDb==0 ){
72863    sqlite3BtreeEnterAll(db);
72864  }
72865  for(i=iDb; i<db->nDb; i++){
72866    Db *pDb = &db->aDb[i];
72867    if( pDb->pSchema ){
72868      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
72869      sqlite3SchemaFree(pDb->pSchema);
72870    }
72871    if( iDb>0 ) return;
72872  }
72873  assert( iDb==0 );
72874  db->flags &= ~SQLITE_InternChanges;
72875  sqlite3VtabUnlockList(db);
72876  sqlite3BtreeLeaveAll(db);
72877
72878  /* If one or more of the auxiliary database files has been closed,
72879  ** then remove them from the auxiliary database list.  We take the
72880  ** opportunity to do this here since we have just deleted all of the
72881  ** schema hash tables and therefore do not have to make any changes
72882  ** to any of those tables.
72883  */
72884  for(i=j=2; i<db->nDb; i++){
72885    struct Db *pDb = &db->aDb[i];
72886    if( pDb->pBt==0 ){
72887      sqlite3DbFree(db, pDb->zName);
72888      pDb->zName = 0;
72889      continue;
72890    }
72891    if( j<i ){
72892      db->aDb[j] = db->aDb[i];
72893    }
72894    j++;
72895  }
72896  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
72897  db->nDb = j;
72898  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
72899    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
72900    sqlite3DbFree(db, db->aDb);
72901    db->aDb = db->aDbStatic;
72902  }
72903}
72904
72905/*
72906** This routine is called when a commit occurs.
72907*/
72908SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
72909  db->flags &= ~SQLITE_InternChanges;
72910}
72911
72912/*
72913** Clear the column names from a table or view.
72914*/
72915static void sqliteResetColumnNames(Table *pTable){
72916  int i;
72917  Column *pCol;
72918  sqlite3 *db = pTable->dbMem;
72919  testcase( db==0 );
72920  assert( pTable!=0 );
72921  if( (pCol = pTable->aCol)!=0 ){
72922    for(i=0; i<pTable->nCol; i++, pCol++){
72923      sqlite3DbFree(db, pCol->zName);
72924      sqlite3ExprDelete(db, pCol->pDflt);
72925      sqlite3DbFree(db, pCol->zDflt);
72926      sqlite3DbFree(db, pCol->zType);
72927      sqlite3DbFree(db, pCol->zColl);
72928    }
72929    sqlite3DbFree(db, pTable->aCol);
72930  }
72931  pTable->aCol = 0;
72932  pTable->nCol = 0;
72933}
72934
72935/*
72936** Remove the memory data structures associated with the given
72937** Table.  No changes are made to disk by this routine.
72938**
72939** This routine just deletes the data structure.  It does not unlink
72940** the table data structure from the hash table.  But it does destroy
72941** memory structures of the indices and foreign keys associated with
72942** the table.
72943*/
72944SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
72945  Index *pIndex, *pNext;
72946  sqlite3 *db;
72947
72948  if( pTable==0 ) return;
72949  db = pTable->dbMem;
72950  testcase( db==0 );
72951
72952  /* Do not delete the table until the reference count reaches zero. */
72953  pTable->nRef--;
72954  if( pTable->nRef>0 ){
72955    return;
72956  }
72957  assert( pTable->nRef==0 );
72958
72959  /* Delete all indices associated with this table
72960  */
72961  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
72962    pNext = pIndex->pNext;
72963    assert( pIndex->pSchema==pTable->pSchema );
72964    sqlite3DeleteIndex(pIndex);
72965  }
72966
72967  /* Delete any foreign keys attached to this table. */
72968  sqlite3FkDelete(pTable);
72969
72970  /* Delete the Table structure itself.
72971  */
72972  sqliteResetColumnNames(pTable);
72973  sqlite3DbFree(db, pTable->zName);
72974  sqlite3DbFree(db, pTable->zColAff);
72975  sqlite3SelectDelete(db, pTable->pSelect);
72976#ifndef SQLITE_OMIT_CHECK
72977  sqlite3ExprDelete(db, pTable->pCheck);
72978#endif
72979  sqlite3VtabClear(pTable);
72980  sqlite3DbFree(db, pTable);
72981}
72982
72983/*
72984** Unlink the given table from the hash tables and the delete the
72985** table structure with all its indices and foreign keys.
72986*/
72987SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
72988  Table *p;
72989  Db *pDb;
72990
72991  assert( db!=0 );
72992  assert( iDb>=0 && iDb<db->nDb );
72993  assert( zTabName );
72994  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
72995  pDb = &db->aDb[iDb];
72996  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
72997                        sqlite3Strlen30(zTabName),0);
72998  sqlite3DeleteTable(p);
72999  db->flags |= SQLITE_InternChanges;
73000}
73001
73002/*
73003** Given a token, return a string that consists of the text of that
73004** token.  Space to hold the returned string
73005** is obtained from sqliteMalloc() and must be freed by the calling
73006** function.
73007**
73008** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
73009** surround the body of the token are removed.
73010**
73011** Tokens are often just pointers into the original SQL text and so
73012** are not \000 terminated and are not persistent.  The returned string
73013** is \000 terminated and is persistent.
73014*/
73015SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
73016  char *zName;
73017  if( pName ){
73018    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
73019    sqlite3Dequote(zName);
73020  }else{
73021    zName = 0;
73022  }
73023  return zName;
73024}
73025
73026/*
73027** Open the sqlite_master table stored in database number iDb for
73028** writing. The table is opened using cursor 0.
73029*/
73030SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
73031  Vdbe *v = sqlite3GetVdbe(p);
73032  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
73033  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
73034  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
73035  if( p->nTab==0 ){
73036    p->nTab = 1;
73037  }
73038}
73039
73040/*
73041** Parameter zName points to a nul-terminated buffer containing the name
73042** of a database ("main", "temp" or the name of an attached db). This
73043** function returns the index of the named database in db->aDb[], or
73044** -1 if the named db cannot be found.
73045*/
73046SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
73047  int i = -1;         /* Database number */
73048  if( zName ){
73049    Db *pDb;
73050    int n = sqlite3Strlen30(zName);
73051    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
73052      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
73053          0==sqlite3StrICmp(pDb->zName, zName) ){
73054        break;
73055      }
73056    }
73057  }
73058  return i;
73059}
73060
73061/*
73062** The token *pName contains the name of a database (either "main" or
73063** "temp" or the name of an attached db). This routine returns the
73064** index of the named database in db->aDb[], or -1 if the named db
73065** does not exist.
73066*/
73067SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
73068  int i;                               /* Database number */
73069  char *zName;                         /* Name we are searching for */
73070  zName = sqlite3NameFromToken(db, pName);
73071  i = sqlite3FindDbName(db, zName);
73072  sqlite3DbFree(db, zName);
73073  return i;
73074}
73075
73076/* The table or view or trigger name is passed to this routine via tokens
73077** pName1 and pName2. If the table name was fully qualified, for example:
73078**
73079** CREATE TABLE xxx.yyy (...);
73080**
73081** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73082** the table name is not fully qualified, i.e.:
73083**
73084** CREATE TABLE yyy(...);
73085**
73086** Then pName1 is set to "yyy" and pName2 is "".
73087**
73088** This routine sets the *ppUnqual pointer to point at the token (pName1 or
73089** pName2) that stores the unqualified table name.  The index of the
73090** database "xxx" is returned.
73091*/
73092SQLITE_PRIVATE int sqlite3TwoPartName(
73093  Parse *pParse,      /* Parsing and code generating context */
73094  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
73095  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
73096  Token **pUnqual     /* Write the unqualified object name here */
73097){
73098  int iDb;                    /* Database holding the object */
73099  sqlite3 *db = pParse->db;
73100
73101  if( ALWAYS(pName2!=0) && pName2->n>0 ){
73102    if( db->init.busy ) {
73103      sqlite3ErrorMsg(pParse, "corrupt database");
73104      pParse->nErr++;
73105      return -1;
73106    }
73107    *pUnqual = pName2;
73108    iDb = sqlite3FindDb(db, pName1);
73109    if( iDb<0 ){
73110      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
73111      pParse->nErr++;
73112      return -1;
73113    }
73114  }else{
73115    assert( db->init.iDb==0 || db->init.busy );
73116    iDb = db->init.iDb;
73117    *pUnqual = pName1;
73118  }
73119  return iDb;
73120}
73121
73122/*
73123** This routine is used to check if the UTF-8 string zName is a legal
73124** unqualified name for a new schema object (table, index, view or
73125** trigger). All names are legal except those that begin with the string
73126** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
73127** is reserved for internal use.
73128*/
73129SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
73130  if( !pParse->db->init.busy && pParse->nested==0
73131          && (pParse->db->flags & SQLITE_WriteSchema)==0
73132          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
73133    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
73134    return SQLITE_ERROR;
73135  }
73136  return SQLITE_OK;
73137}
73138
73139/*
73140** Begin constructing a new table representation in memory.  This is
73141** the first of several action routines that get called in response
73142** to a CREATE TABLE statement.  In particular, this routine is called
73143** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
73144** flag is true if the table should be stored in the auxiliary database
73145** file instead of in the main database file.  This is normally the case
73146** when the "TEMP" or "TEMPORARY" keyword occurs in between
73147** CREATE and TABLE.
73148**
73149** The new table record is initialized and put in pParse->pNewTable.
73150** As more of the CREATE TABLE statement is parsed, additional action
73151** routines will be called to add more information to this record.
73152** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
73153** is called to complete the construction of the new table record.
73154*/
73155SQLITE_PRIVATE void sqlite3StartTable(
73156  Parse *pParse,   /* Parser context */
73157  Token *pName1,   /* First part of the name of the table or view */
73158  Token *pName2,   /* Second part of the name of the table or view */
73159  int isTemp,      /* True if this is a TEMP table */
73160  int isView,      /* True if this is a VIEW */
73161  int isVirtual,   /* True if this is a VIRTUAL table */
73162  int noErr        /* Do nothing if table already exists */
73163){
73164  Table *pTable;
73165  char *zName = 0; /* The name of the new table */
73166  sqlite3 *db = pParse->db;
73167  Vdbe *v;
73168  int iDb;         /* Database number to create the table in */
73169  Token *pName;    /* Unqualified name of the table to create */
73170
73171  /* The table or view name to create is passed to this routine via tokens
73172  ** pName1 and pName2. If the table name was fully qualified, for example:
73173  **
73174  ** CREATE TABLE xxx.yyy (...);
73175  **
73176  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73177  ** the table name is not fully qualified, i.e.:
73178  **
73179  ** CREATE TABLE yyy(...);
73180  **
73181  ** Then pName1 is set to "yyy" and pName2 is "".
73182  **
73183  ** The call below sets the pName pointer to point at the token (pName1 or
73184  ** pName2) that stores the unqualified table name. The variable iDb is
73185  ** set to the index of the database that the table or view is to be
73186  ** created in.
73187  */
73188  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
73189  if( iDb<0 ) return;
73190  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
73191    /* If creating a temp table, the name may not be qualified */
73192    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
73193    return;
73194  }
73195  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
73196
73197  pParse->sNameToken = *pName;
73198  zName = sqlite3NameFromToken(db, pName);
73199  if( zName==0 ) return;
73200  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
73201    goto begin_table_error;
73202  }
73203  if( db->init.iDb==1 ) isTemp = 1;
73204#ifndef SQLITE_OMIT_AUTHORIZATION
73205  assert( (isTemp & 1)==isTemp );
73206  {
73207    int code;
73208    char *zDb = db->aDb[iDb].zName;
73209    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
73210      goto begin_table_error;
73211    }
73212    if( isView ){
73213      if( !OMIT_TEMPDB && isTemp ){
73214        code = SQLITE_CREATE_TEMP_VIEW;
73215      }else{
73216        code = SQLITE_CREATE_VIEW;
73217      }
73218    }else{
73219      if( !OMIT_TEMPDB && isTemp ){
73220        code = SQLITE_CREATE_TEMP_TABLE;
73221      }else{
73222        code = SQLITE_CREATE_TABLE;
73223      }
73224    }
73225    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
73226      goto begin_table_error;
73227    }
73228  }
73229#endif
73230
73231  /* Make sure the new table name does not collide with an existing
73232  ** index or table name in the same database.  Issue an error message if
73233  ** it does. The exception is if the statement being parsed was passed
73234  ** to an sqlite3_declare_vtab() call. In that case only the column names
73235  ** and types will be used, so there is no need to test for namespace
73236  ** collisions.
73237  */
73238  if( !IN_DECLARE_VTAB ){
73239    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73240      goto begin_table_error;
73241    }
73242    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
73243    if( pTable ){
73244      if( !noErr ){
73245        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
73246      }
73247      goto begin_table_error;
73248    }
73249    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
73250      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
73251      goto begin_table_error;
73252    }
73253  }
73254
73255  pTable = sqlite3DbMallocZero(db, sizeof(Table));
73256  if( pTable==0 ){
73257    db->mallocFailed = 1;
73258    pParse->rc = SQLITE_NOMEM;
73259    pParse->nErr++;
73260    goto begin_table_error;
73261  }
73262  pTable->zName = zName;
73263  pTable->iPKey = -1;
73264  pTable->pSchema = db->aDb[iDb].pSchema;
73265  pTable->nRef = 1;
73266  pTable->dbMem = 0;
73267  assert( pParse->pNewTable==0 );
73268  pParse->pNewTable = pTable;
73269
73270  /* If this is the magic sqlite_sequence table used by autoincrement,
73271  ** then record a pointer to this table in the main database structure
73272  ** so that INSERT can find the table easily.
73273  */
73274#ifndef SQLITE_OMIT_AUTOINCREMENT
73275  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
73276    pTable->pSchema->pSeqTab = pTable;
73277  }
73278#endif
73279
73280  /* Begin generating the code that will insert the table record into
73281  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
73282  ** and allocate the record number for the table entry now.  Before any
73283  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
73284  ** indices to be created and the table record must come before the
73285  ** indices.  Hence, the record number for the table must be allocated
73286  ** now.
73287  */
73288  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
73289    int j1;
73290    int fileFormat;
73291    int reg1, reg2, reg3;
73292    sqlite3BeginWriteOperation(pParse, 0, iDb);
73293
73294#ifndef SQLITE_OMIT_VIRTUALTABLE
73295    if( isVirtual ){
73296      sqlite3VdbeAddOp0(v, OP_VBegin);
73297    }
73298#endif
73299
73300    /* If the file format and encoding in the database have not been set,
73301    ** set them now.
73302    */
73303    reg1 = pParse->regRowid = ++pParse->nMem;
73304    reg2 = pParse->regRoot = ++pParse->nMem;
73305    reg3 = ++pParse->nMem;
73306    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
73307    sqlite3VdbeUsesBtree(v, iDb);
73308    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
73309    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
73310                  1 : SQLITE_MAX_FILE_FORMAT;
73311    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
73312    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
73313    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
73314    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
73315    sqlite3VdbeJumpHere(v, j1);
73316
73317    /* This just creates a place-holder record in the sqlite_master table.
73318    ** The record created does not contain anything yet.  It will be replaced
73319    ** by the real entry in code generated at sqlite3EndTable().
73320    **
73321    ** The rowid for the new entry is left in register pParse->regRowid.
73322    ** The root page number of the new table is left in reg pParse->regRoot.
73323    ** The rowid and root page number values are needed by the code that
73324    ** sqlite3EndTable will generate.
73325    */
73326#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
73327    if( isView || isVirtual ){
73328      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
73329    }else
73330#endif
73331    {
73332      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
73333    }
73334    sqlite3OpenMasterTable(pParse, iDb);
73335    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
73336    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
73337    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
73338    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73339    sqlite3VdbeAddOp0(v, OP_Close);
73340  }
73341
73342  /* Normal (non-error) return. */
73343  return;
73344
73345  /* If an error occurs, we jump here */
73346begin_table_error:
73347  sqlite3DbFree(db, zName);
73348  return;
73349}
73350
73351/*
73352** This macro is used to compare two strings in a case-insensitive manner.
73353** It is slightly faster than calling sqlite3StrICmp() directly, but
73354** produces larger code.
73355**
73356** WARNING: This macro is not compatible with the strcmp() family. It
73357** returns true if the two strings are equal, otherwise false.
73358*/
73359#define STRICMP(x, y) (\
73360sqlite3UpperToLower[*(unsigned char *)(x)]==   \
73361sqlite3UpperToLower[*(unsigned char *)(y)]     \
73362&& sqlite3StrICmp((x)+1,(y)+1)==0 )
73363
73364/*
73365** Add a new column to the table currently being constructed.
73366**
73367** The parser calls this routine once for each column declaration
73368** in a CREATE TABLE statement.  sqlite3StartTable() gets called
73369** first to get things going.  Then this routine is called for each
73370** column.
73371*/
73372SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
73373  Table *p;
73374  int i;
73375  char *z;
73376  Column *pCol;
73377  sqlite3 *db = pParse->db;
73378  if( (p = pParse->pNewTable)==0 ) return;
73379#if SQLITE_MAX_COLUMN
73380  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73381    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
73382    return;
73383  }
73384#endif
73385  z = sqlite3NameFromToken(db, pName);
73386  if( z==0 ) return;
73387  for(i=0; i<p->nCol; i++){
73388    if( STRICMP(z, p->aCol[i].zName) ){
73389      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
73390      sqlite3DbFree(db, z);
73391      return;
73392    }
73393  }
73394  if( (p->nCol & 0x7)==0 ){
73395    Column *aNew;
73396    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
73397    if( aNew==0 ){
73398      sqlite3DbFree(db, z);
73399      return;
73400    }
73401    p->aCol = aNew;
73402  }
73403  pCol = &p->aCol[p->nCol];
73404  memset(pCol, 0, sizeof(p->aCol[0]));
73405  pCol->zName = z;
73406
73407  /* If there is no type specified, columns have the default affinity
73408  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
73409  ** be called next to set pCol->affinity correctly.
73410  */
73411  pCol->affinity = SQLITE_AFF_NONE;
73412  p->nCol++;
73413}
73414
73415/*
73416** This routine is called by the parser while in the middle of
73417** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
73418** been seen on a column.  This routine sets the notNull flag on
73419** the column currently under construction.
73420*/
73421SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
73422  Table *p;
73423  p = pParse->pNewTable;
73424  if( p==0 || NEVER(p->nCol<1) ) return;
73425  p->aCol[p->nCol-1].notNull = (u8)onError;
73426}
73427
73428/*
73429** Scan the column type name zType (length nType) and return the
73430** associated affinity type.
73431**
73432** This routine does a case-independent search of zType for the
73433** substrings in the following table. If one of the substrings is
73434** found, the corresponding affinity is returned. If zType contains
73435** more than one of the substrings, entries toward the top of
73436** the table take priority. For example, if zType is 'BLOBINT',
73437** SQLITE_AFF_INTEGER is returned.
73438**
73439** Substring     | Affinity
73440** --------------------------------
73441** 'INT'         | SQLITE_AFF_INTEGER
73442** 'CHAR'        | SQLITE_AFF_TEXT
73443** 'CLOB'        | SQLITE_AFF_TEXT
73444** 'TEXT'        | SQLITE_AFF_TEXT
73445** 'BLOB'        | SQLITE_AFF_NONE
73446** 'REAL'        | SQLITE_AFF_REAL
73447** 'FLOA'        | SQLITE_AFF_REAL
73448** 'DOUB'        | SQLITE_AFF_REAL
73449**
73450** If none of the substrings in the above table are found,
73451** SQLITE_AFF_NUMERIC is returned.
73452*/
73453SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
73454  u32 h = 0;
73455  char aff = SQLITE_AFF_NUMERIC;
73456
73457  if( zIn ) while( zIn[0] ){
73458    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
73459    zIn++;
73460    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
73461      aff = SQLITE_AFF_TEXT;
73462    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
73463      aff = SQLITE_AFF_TEXT;
73464    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
73465      aff = SQLITE_AFF_TEXT;
73466    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
73467        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
73468      aff = SQLITE_AFF_NONE;
73469#ifndef SQLITE_OMIT_FLOATING_POINT
73470    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
73471        && aff==SQLITE_AFF_NUMERIC ){
73472      aff = SQLITE_AFF_REAL;
73473    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
73474        && aff==SQLITE_AFF_NUMERIC ){
73475      aff = SQLITE_AFF_REAL;
73476    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
73477        && aff==SQLITE_AFF_NUMERIC ){
73478      aff = SQLITE_AFF_REAL;
73479#endif
73480    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
73481      aff = SQLITE_AFF_INTEGER;
73482      break;
73483    }
73484  }
73485
73486  return aff;
73487}
73488
73489/*
73490** This routine is called by the parser while in the middle of
73491** parsing a CREATE TABLE statement.  The pFirst token is the first
73492** token in the sequence of tokens that describe the type of the
73493** column currently under construction.   pLast is the last token
73494** in the sequence.  Use this information to construct a string
73495** that contains the typename of the column and store that string
73496** in zType.
73497*/
73498SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
73499  Table *p;
73500  Column *pCol;
73501
73502  p = pParse->pNewTable;
73503  if( p==0 || NEVER(p->nCol<1) ) return;
73504  pCol = &p->aCol[p->nCol-1];
73505  assert( pCol->zType==0 );
73506  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
73507  pCol->affinity = sqlite3AffinityType(pCol->zType);
73508}
73509
73510/*
73511** The expression is the default value for the most recently added column
73512** of the table currently under construction.
73513**
73514** Default value expressions must be constant.  Raise an exception if this
73515** is not the case.
73516**
73517** This routine is called by the parser while in the middle of
73518** parsing a CREATE TABLE statement.
73519*/
73520SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
73521  Table *p;
73522  Column *pCol;
73523  sqlite3 *db = pParse->db;
73524  p = pParse->pNewTable;
73525  if( p!=0 ){
73526    pCol = &(p->aCol[p->nCol-1]);
73527    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
73528      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
73529          pCol->zName);
73530    }else{
73531      /* A copy of pExpr is used instead of the original, as pExpr contains
73532      ** tokens that point to volatile memory. The 'span' of the expression
73533      ** is required by pragma table_info.
73534      */
73535      sqlite3ExprDelete(db, pCol->pDflt);
73536      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
73537      sqlite3DbFree(db, pCol->zDflt);
73538      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
73539                                     (int)(pSpan->zEnd - pSpan->zStart));
73540    }
73541  }
73542  sqlite3ExprDelete(db, pSpan->pExpr);
73543}
73544
73545/*
73546** Designate the PRIMARY KEY for the table.  pList is a list of names
73547** of columns that form the primary key.  If pList is NULL, then the
73548** most recently added column of the table is the primary key.
73549**
73550** A table can have at most one primary key.  If the table already has
73551** a primary key (and this is the second primary key) then create an
73552** error.
73553**
73554** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
73555** then we will try to use that column as the rowid.  Set the Table.iPKey
73556** field of the table under construction to be the index of the
73557** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
73558** no INTEGER PRIMARY KEY.
73559**
73560** If the key is not an INTEGER PRIMARY KEY, then create a unique
73561** index for the key.  No index is created for INTEGER PRIMARY KEYs.
73562*/
73563SQLITE_PRIVATE void sqlite3AddPrimaryKey(
73564  Parse *pParse,    /* Parsing context */
73565  ExprList *pList,  /* List of field names to be indexed */
73566  int onError,      /* What to do with a uniqueness conflict */
73567  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
73568  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
73569){
73570  Table *pTab = pParse->pNewTable;
73571  char *zType = 0;
73572  int iCol = -1, i;
73573  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
73574  if( pTab->tabFlags & TF_HasPrimaryKey ){
73575    sqlite3ErrorMsg(pParse,
73576      "table \"%s\" has more than one primary key", pTab->zName);
73577    goto primary_key_exit;
73578  }
73579  pTab->tabFlags |= TF_HasPrimaryKey;
73580  if( pList==0 ){
73581    iCol = pTab->nCol - 1;
73582    pTab->aCol[iCol].isPrimKey = 1;
73583  }else{
73584    for(i=0; i<pList->nExpr; i++){
73585      for(iCol=0; iCol<pTab->nCol; iCol++){
73586        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
73587          break;
73588        }
73589      }
73590      if( iCol<pTab->nCol ){
73591        pTab->aCol[iCol].isPrimKey = 1;
73592      }
73593    }
73594    if( pList->nExpr>1 ) iCol = -1;
73595  }
73596  if( iCol>=0 && iCol<pTab->nCol ){
73597    zType = pTab->aCol[iCol].zType;
73598  }
73599  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
73600        && sortOrder==SQLITE_SO_ASC ){
73601    pTab->iPKey = iCol;
73602    pTab->keyConf = (u8)onError;
73603    assert( autoInc==0 || autoInc==1 );
73604    pTab->tabFlags |= autoInc*TF_Autoincrement;
73605  }else if( autoInc ){
73606#ifndef SQLITE_OMIT_AUTOINCREMENT
73607    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
73608       "INTEGER PRIMARY KEY");
73609#endif
73610  }else{
73611    Index *p;
73612    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
73613    if( p ){
73614      p->autoIndex = 2;
73615    }
73616    pList = 0;
73617  }
73618
73619primary_key_exit:
73620  sqlite3ExprListDelete(pParse->db, pList);
73621  return;
73622}
73623
73624/*
73625** Add a new CHECK constraint to the table currently under construction.
73626*/
73627SQLITE_PRIVATE void sqlite3AddCheckConstraint(
73628  Parse *pParse,    /* Parsing context */
73629  Expr *pCheckExpr  /* The check expression */
73630){
73631  sqlite3 *db = pParse->db;
73632#ifndef SQLITE_OMIT_CHECK
73633  Table *pTab = pParse->pNewTable;
73634  if( pTab && !IN_DECLARE_VTAB ){
73635    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
73636  }else
73637#endif
73638  {
73639    sqlite3ExprDelete(db, pCheckExpr);
73640  }
73641}
73642
73643/*
73644** Set the collation function of the most recently parsed table column
73645** to the CollSeq given.
73646*/
73647SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
73648  Table *p;
73649  int i;
73650  char *zColl;              /* Dequoted name of collation sequence */
73651  sqlite3 *db;
73652
73653  if( (p = pParse->pNewTable)==0 ) return;
73654  i = p->nCol-1;
73655  db = pParse->db;
73656  zColl = sqlite3NameFromToken(db, pToken);
73657  if( !zColl ) return;
73658
73659  if( sqlite3LocateCollSeq(pParse, zColl) ){
73660    Index *pIdx;
73661    p->aCol[i].zColl = zColl;
73662
73663    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
73664    ** then an index may have been created on this column before the
73665    ** collation type was added. Correct this if it is the case.
73666    */
73667    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
73668      assert( pIdx->nColumn==1 );
73669      if( pIdx->aiColumn[0]==i ){
73670        pIdx->azColl[0] = p->aCol[i].zColl;
73671      }
73672    }
73673  }else{
73674    sqlite3DbFree(db, zColl);
73675  }
73676}
73677
73678/*
73679** This function returns the collation sequence for database native text
73680** encoding identified by the string zName, length nName.
73681**
73682** If the requested collation sequence is not available, or not available
73683** in the database native encoding, the collation factory is invoked to
73684** request it. If the collation factory does not supply such a sequence,
73685** and the sequence is available in another text encoding, then that is
73686** returned instead.
73687**
73688** If no versions of the requested collations sequence are available, or
73689** another error occurs, NULL is returned and an error message written into
73690** pParse.
73691**
73692** This routine is a wrapper around sqlite3FindCollSeq().  This routine
73693** invokes the collation factory if the named collation cannot be found
73694** and generates an error message.
73695**
73696** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
73697*/
73698SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
73699  sqlite3 *db = pParse->db;
73700  u8 enc = ENC(db);
73701  u8 initbusy = db->init.busy;
73702  CollSeq *pColl;
73703
73704  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
73705  if( !initbusy && (!pColl || !pColl->xCmp) ){
73706    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
73707    if( !pColl ){
73708      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
73709    }
73710  }
73711
73712  return pColl;
73713}
73714
73715
73716/*
73717** Generate code that will increment the schema cookie.
73718**
73719** The schema cookie is used to determine when the schema for the
73720** database changes.  After each schema change, the cookie value
73721** changes.  When a process first reads the schema it records the
73722** cookie.  Thereafter, whenever it goes to access the database,
73723** it checks the cookie to make sure the schema has not changed
73724** since it was last read.
73725**
73726** This plan is not completely bullet-proof.  It is possible for
73727** the schema to change multiple times and for the cookie to be
73728** set back to prior value.  But schema changes are infrequent
73729** and the probability of hitting the same cookie value is only
73730** 1 chance in 2^32.  So we're safe enough.
73731*/
73732SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
73733  int r1 = sqlite3GetTempReg(pParse);
73734  sqlite3 *db = pParse->db;
73735  Vdbe *v = pParse->pVdbe;
73736  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
73737  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
73738  sqlite3ReleaseTempReg(pParse, r1);
73739}
73740
73741/*
73742** Measure the number of characters needed to output the given
73743** identifier.  The number returned includes any quotes used
73744** but does not include the null terminator.
73745**
73746** The estimate is conservative.  It might be larger that what is
73747** really needed.
73748*/
73749static int identLength(const char *z){
73750  int n;
73751  for(n=0; *z; n++, z++){
73752    if( *z=='"' ){ n++; }
73753  }
73754  return n + 2;
73755}
73756
73757/*
73758** The first parameter is a pointer to an output buffer. The second
73759** parameter is a pointer to an integer that contains the offset at
73760** which to write into the output buffer. This function copies the
73761** nul-terminated string pointed to by the third parameter, zSignedIdent,
73762** to the specified offset in the buffer and updates *pIdx to refer
73763** to the first byte after the last byte written before returning.
73764**
73765** If the string zSignedIdent consists entirely of alpha-numeric
73766** characters, does not begin with a digit and is not an SQL keyword,
73767** then it is copied to the output buffer exactly as it is. Otherwise,
73768** it is quoted using double-quotes.
73769*/
73770static void identPut(char *z, int *pIdx, char *zSignedIdent){
73771  unsigned char *zIdent = (unsigned char*)zSignedIdent;
73772  int i, j, needQuote;
73773  i = *pIdx;
73774
73775  for(j=0; zIdent[j]; j++){
73776    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
73777  }
73778  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
73779  if( !needQuote ){
73780    needQuote = zIdent[j];
73781  }
73782
73783  if( needQuote ) z[i++] = '"';
73784  for(j=0; zIdent[j]; j++){
73785    z[i++] = zIdent[j];
73786    if( zIdent[j]=='"' ) z[i++] = '"';
73787  }
73788  if( needQuote ) z[i++] = '"';
73789  z[i] = 0;
73790  *pIdx = i;
73791}
73792
73793/*
73794** Generate a CREATE TABLE statement appropriate for the given
73795** table.  Memory to hold the text of the statement is obtained
73796** from sqliteMalloc() and must be freed by the calling function.
73797*/
73798static char *createTableStmt(sqlite3 *db, Table *p){
73799  int i, k, n;
73800  char *zStmt;
73801  char *zSep, *zSep2, *zEnd;
73802  Column *pCol;
73803  n = 0;
73804  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
73805    n += identLength(pCol->zName) + 5;
73806  }
73807  n += identLength(p->zName);
73808  if( n<50 ){
73809    zSep = "";
73810    zSep2 = ",";
73811    zEnd = ")";
73812  }else{
73813    zSep = "\n  ";
73814    zSep2 = ",\n  ";
73815    zEnd = "\n)";
73816  }
73817  n += 35 + 6*p->nCol;
73818  zStmt = sqlite3Malloc( n );
73819  if( zStmt==0 ){
73820    db->mallocFailed = 1;
73821    return 0;
73822  }
73823  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
73824  k = sqlite3Strlen30(zStmt);
73825  identPut(zStmt, &k, p->zName);
73826  zStmt[k++] = '(';
73827  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
73828    static const char * const azType[] = {
73829        /* SQLITE_AFF_TEXT    */ " TEXT",
73830        /* SQLITE_AFF_NONE    */ "",
73831        /* SQLITE_AFF_NUMERIC */ " NUM",
73832        /* SQLITE_AFF_INTEGER */ " INT",
73833        /* SQLITE_AFF_REAL    */ " REAL"
73834    };
73835    int len;
73836    const char *zType;
73837
73838    sqlite3_snprintf(n-k, &zStmt[k], zSep);
73839    k += sqlite3Strlen30(&zStmt[k]);
73840    zSep = zSep2;
73841    identPut(zStmt, &k, pCol->zName);
73842    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
73843    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
73844    testcase( pCol->affinity==SQLITE_AFF_TEXT );
73845    testcase( pCol->affinity==SQLITE_AFF_NONE );
73846    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
73847    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
73848    testcase( pCol->affinity==SQLITE_AFF_REAL );
73849
73850    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
73851    len = sqlite3Strlen30(zType);
73852    assert( pCol->affinity==SQLITE_AFF_NONE
73853            || pCol->affinity==sqlite3AffinityType(zType) );
73854    memcpy(&zStmt[k], zType, len);
73855    k += len;
73856    assert( k<=n );
73857  }
73858  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
73859  return zStmt;
73860}
73861
73862/*
73863** This routine is called to report the final ")" that terminates
73864** a CREATE TABLE statement.
73865**
73866** The table structure that other action routines have been building
73867** is added to the internal hash tables, assuming no errors have
73868** occurred.
73869**
73870** An entry for the table is made in the master table on disk, unless
73871** this is a temporary table or db->init.busy==1.  When db->init.busy==1
73872** it means we are reading the sqlite_master table because we just
73873** connected to the database or because the sqlite_master table has
73874** recently changed, so the entry for this table already exists in
73875** the sqlite_master table.  We do not want to create it again.
73876**
73877** If the pSelect argument is not NULL, it means that this routine
73878** was called to create a table generated from a
73879** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
73880** the new table will match the result set of the SELECT.
73881*/
73882SQLITE_PRIVATE void sqlite3EndTable(
73883  Parse *pParse,          /* Parse context */
73884  Token *pCons,           /* The ',' token after the last column defn. */
73885  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
73886  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
73887){
73888  Table *p;
73889  sqlite3 *db = pParse->db;
73890  int iDb;
73891
73892  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
73893    return;
73894  }
73895  p = pParse->pNewTable;
73896  if( p==0 ) return;
73897
73898  assert( !db->init.busy || !pSelect );
73899
73900  iDb = sqlite3SchemaToIndex(db, p->pSchema);
73901
73902#ifndef SQLITE_OMIT_CHECK
73903  /* Resolve names in all CHECK constraint expressions.
73904  */
73905  if( p->pCheck ){
73906    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
73907    NameContext sNC;                /* Name context for pParse->pNewTable */
73908
73909    memset(&sNC, 0, sizeof(sNC));
73910    memset(&sSrc, 0, sizeof(sSrc));
73911    sSrc.nSrc = 1;
73912    sSrc.a[0].zName = p->zName;
73913    sSrc.a[0].pTab = p;
73914    sSrc.a[0].iCursor = -1;
73915    sNC.pParse = pParse;
73916    sNC.pSrcList = &sSrc;
73917    sNC.isCheck = 1;
73918    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
73919      return;
73920    }
73921  }
73922#endif /* !defined(SQLITE_OMIT_CHECK) */
73923
73924  /* If the db->init.busy is 1 it means we are reading the SQL off the
73925  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
73926  ** So do not write to the disk again.  Extract the root page number
73927  ** for the table from the db->init.newTnum field.  (The page number
73928  ** should have been put there by the sqliteOpenCb routine.)
73929  */
73930  if( db->init.busy ){
73931    p->tnum = db->init.newTnum;
73932  }
73933
73934  /* If not initializing, then create a record for the new table
73935  ** in the SQLITE_MASTER table of the database.
73936  **
73937  ** If this is a TEMPORARY table, write the entry into the auxiliary
73938  ** file instead of into the main database file.
73939  */
73940  if( !db->init.busy ){
73941    int n;
73942    Vdbe *v;
73943    char *zType;    /* "view" or "table" */
73944    char *zType2;   /* "VIEW" or "TABLE" */
73945    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
73946
73947    v = sqlite3GetVdbe(pParse);
73948    if( NEVER(v==0) ) return;
73949
73950    sqlite3VdbeAddOp1(v, OP_Close, 0);
73951
73952    /*
73953    ** Initialize zType for the new view or table.
73954    */
73955    if( p->pSelect==0 ){
73956      /* A regular table */
73957      zType = "table";
73958      zType2 = "TABLE";
73959#ifndef SQLITE_OMIT_VIEW
73960    }else{
73961      /* A view */
73962      zType = "view";
73963      zType2 = "VIEW";
73964#endif
73965    }
73966
73967    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
73968    ** statement to populate the new table. The root-page number for the
73969    ** new table is in register pParse->regRoot.
73970    **
73971    ** Once the SELECT has been coded by sqlite3Select(), it is in a
73972    ** suitable state to query for the column names and types to be used
73973    ** by the new table.
73974    **
73975    ** A shared-cache write-lock is not required to write to the new table,
73976    ** as a schema-lock must have already been obtained to create it. Since
73977    ** a schema-lock excludes all other database users, the write-lock would
73978    ** be redundant.
73979    */
73980    if( pSelect ){
73981      SelectDest dest;
73982      Table *pSelTab;
73983
73984      assert(pParse->nTab==1);
73985      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
73986      sqlite3VdbeChangeP5(v, 1);
73987      pParse->nTab = 2;
73988      sqlite3SelectDestInit(&dest, SRT_Table, 1);
73989      sqlite3Select(pParse, pSelect, &dest);
73990      sqlite3VdbeAddOp1(v, OP_Close, 1);
73991      if( pParse->nErr==0 ){
73992        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
73993        if( pSelTab==0 ) return;
73994        assert( p->aCol==0 );
73995        p->nCol = pSelTab->nCol;
73996        p->aCol = pSelTab->aCol;
73997        pSelTab->nCol = 0;
73998        pSelTab->aCol = 0;
73999        sqlite3DeleteTable(pSelTab);
74000      }
74001    }
74002
74003    /* Compute the complete text of the CREATE statement */
74004    if( pSelect ){
74005      zStmt = createTableStmt(db, p);
74006    }else{
74007      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
74008      zStmt = sqlite3MPrintf(db,
74009          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
74010      );
74011    }
74012
74013    /* A slot for the record has already been allocated in the
74014    ** SQLITE_MASTER table.  We just need to update that slot with all
74015    ** the information we've collected.
74016    */
74017    sqlite3NestedParse(pParse,
74018      "UPDATE %Q.%s "
74019         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
74020       "WHERE rowid=#%d",
74021      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
74022      zType,
74023      p->zName,
74024      p->zName,
74025      pParse->regRoot,
74026      zStmt,
74027      pParse->regRowid
74028    );
74029    sqlite3DbFree(db, zStmt);
74030    sqlite3ChangeCookie(pParse, iDb);
74031
74032#ifndef SQLITE_OMIT_AUTOINCREMENT
74033    /* Check to see if we need to create an sqlite_sequence table for
74034    ** keeping track of autoincrement keys.
74035    */
74036    if( p->tabFlags & TF_Autoincrement ){
74037      Db *pDb = &db->aDb[iDb];
74038      if( pDb->pSchema->pSeqTab==0 ){
74039        sqlite3NestedParse(pParse,
74040          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
74041          pDb->zName
74042        );
74043      }
74044    }
74045#endif
74046
74047    /* Reparse everything to update our internal data structures */
74048    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
74049        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
74050  }
74051
74052
74053  /* Add the table to the in-memory representation of the database.
74054  */
74055  if( db->init.busy ){
74056    Table *pOld;
74057    Schema *pSchema = p->pSchema;
74058    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
74059                             sqlite3Strlen30(p->zName),p);
74060    if( pOld ){
74061      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
74062      db->mallocFailed = 1;
74063      return;
74064    }
74065    pParse->pNewTable = 0;
74066    db->nTable++;
74067    db->flags |= SQLITE_InternChanges;
74068
74069#ifndef SQLITE_OMIT_ALTERTABLE
74070    if( !p->pSelect ){
74071      const char *zName = (const char *)pParse->sNameToken.z;
74072      int nName;
74073      assert( !pSelect && pCons && pEnd );
74074      if( pCons->z==0 ){
74075        pCons = pEnd;
74076      }
74077      nName = (int)((const char *)pCons->z - zName);
74078      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
74079    }
74080#endif
74081  }
74082}
74083
74084#ifndef SQLITE_OMIT_VIEW
74085/*
74086** The parser calls this routine in order to create a new VIEW
74087*/
74088SQLITE_PRIVATE void sqlite3CreateView(
74089  Parse *pParse,     /* The parsing context */
74090  Token *pBegin,     /* The CREATE token that begins the statement */
74091  Token *pName1,     /* The token that holds the name of the view */
74092  Token *pName2,     /* The token that holds the name of the view */
74093  Select *pSelect,   /* A SELECT statement that will become the new view */
74094  int isTemp,        /* TRUE for a TEMPORARY view */
74095  int noErr          /* Suppress error messages if VIEW already exists */
74096){
74097  Table *p;
74098  int n;
74099  const char *z;
74100  Token sEnd;
74101  DbFixer sFix;
74102  Token *pName;
74103  int iDb;
74104  sqlite3 *db = pParse->db;
74105
74106  if( pParse->nVar>0 ){
74107    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
74108    sqlite3SelectDelete(db, pSelect);
74109    return;
74110  }
74111  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
74112  p = pParse->pNewTable;
74113  if( p==0 ){
74114    sqlite3SelectDelete(db, pSelect);
74115    return;
74116  }
74117  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
74118                             ** there could not have been an error */
74119  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74120  iDb = sqlite3SchemaToIndex(db, p->pSchema);
74121  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
74122    && sqlite3FixSelect(&sFix, pSelect)
74123  ){
74124    sqlite3SelectDelete(db, pSelect);
74125    return;
74126  }
74127
74128  /* Make a copy of the entire SELECT statement that defines the view.
74129  ** This will force all the Expr.token.z values to be dynamically
74130  ** allocated rather than point to the input string - which means that
74131  ** they will persist after the current sqlite3_exec() call returns.
74132  */
74133  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
74134  sqlite3SelectDelete(db, pSelect);
74135  if( db->mallocFailed ){
74136    return;
74137  }
74138  if( !db->init.busy ){
74139    sqlite3ViewGetColumnNames(pParse, p);
74140  }
74141
74142  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
74143  ** the end.
74144  */
74145  sEnd = pParse->sLastToken;
74146  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
74147    sEnd.z += sEnd.n;
74148  }
74149  sEnd.n = 0;
74150  n = (int)(sEnd.z - pBegin->z);
74151  z = pBegin->z;
74152  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
74153  sEnd.z = &z[n-1];
74154  sEnd.n = 1;
74155
74156  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
74157  sqlite3EndTable(pParse, 0, &sEnd, 0);
74158  return;
74159}
74160#endif /* SQLITE_OMIT_VIEW */
74161
74162#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
74163/*
74164** The Table structure pTable is really a VIEW.  Fill in the names of
74165** the columns of the view in the pTable structure.  Return the number
74166** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
74167*/
74168SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
74169  Table *pSelTab;   /* A fake table from which we get the result set */
74170  Select *pSel;     /* Copy of the SELECT that implements the view */
74171  int nErr = 0;     /* Number of errors encountered */
74172  int n;            /* Temporarily holds the number of cursors assigned */
74173  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
74174  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
74175
74176  assert( pTable );
74177
74178#ifndef SQLITE_OMIT_VIRTUALTABLE
74179  if( sqlite3VtabCallConnect(pParse, pTable) ){
74180    return SQLITE_ERROR;
74181  }
74182  if( IsVirtual(pTable) ) return 0;
74183#endif
74184
74185#ifndef SQLITE_OMIT_VIEW
74186  /* A positive nCol means the columns names for this view are
74187  ** already known.
74188  */
74189  if( pTable->nCol>0 ) return 0;
74190
74191  /* A negative nCol is a special marker meaning that we are currently
74192  ** trying to compute the column names.  If we enter this routine with
74193  ** a negative nCol, it means two or more views form a loop, like this:
74194  **
74195  **     CREATE VIEW one AS SELECT * FROM two;
74196  **     CREATE VIEW two AS SELECT * FROM one;
74197  **
74198  ** Actually, the error above is now caught prior to reaching this point.
74199  ** But the following test is still important as it does come up
74200  ** in the following:
74201  **
74202  **     CREATE TABLE main.ex1(a);
74203  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
74204  **     SELECT * FROM temp.ex1;
74205  */
74206  if( pTable->nCol<0 ){
74207    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
74208    return 1;
74209  }
74210  assert( pTable->nCol>=0 );
74211
74212  /* If we get this far, it means we need to compute the table names.
74213  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
74214  ** "*" elements in the results set of the view and will assign cursors
74215  ** to the elements of the FROM clause.  But we do not want these changes
74216  ** to be permanent.  So the computation is done on a copy of the SELECT
74217  ** statement that defines the view.
74218  */
74219  assert( pTable->pSelect );
74220  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
74221  if( pSel ){
74222    u8 enableLookaside = db->lookaside.bEnabled;
74223    n = pParse->nTab;
74224    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
74225    pTable->nCol = -1;
74226    db->lookaside.bEnabled = 0;
74227#ifndef SQLITE_OMIT_AUTHORIZATION
74228    xAuth = db->xAuth;
74229    db->xAuth = 0;
74230    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74231    db->xAuth = xAuth;
74232#else
74233    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74234#endif
74235    db->lookaside.bEnabled = enableLookaside;
74236    pParse->nTab = n;
74237    if( pSelTab ){
74238      assert( pTable->aCol==0 );
74239      pTable->nCol = pSelTab->nCol;
74240      pTable->aCol = pSelTab->aCol;
74241      pSelTab->nCol = 0;
74242      pSelTab->aCol = 0;
74243      sqlite3DeleteTable(pSelTab);
74244      pTable->pSchema->flags |= DB_UnresetViews;
74245    }else{
74246      pTable->nCol = 0;
74247      nErr++;
74248    }
74249    sqlite3SelectDelete(db, pSel);
74250  } else {
74251    nErr++;
74252  }
74253#endif /* SQLITE_OMIT_VIEW */
74254  return nErr;
74255}
74256#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
74257
74258#ifndef SQLITE_OMIT_VIEW
74259/*
74260** Clear the column names from every VIEW in database idx.
74261*/
74262static void sqliteViewResetAll(sqlite3 *db, int idx){
74263  HashElem *i;
74264  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
74265  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
74266    Table *pTab = sqliteHashData(i);
74267    if( pTab->pSelect ){
74268      sqliteResetColumnNames(pTab);
74269    }
74270  }
74271  DbClearProperty(db, idx, DB_UnresetViews);
74272}
74273#else
74274# define sqliteViewResetAll(A,B)
74275#endif /* SQLITE_OMIT_VIEW */
74276
74277/*
74278** This function is called by the VDBE to adjust the internal schema
74279** used by SQLite when the btree layer moves a table root page. The
74280** root-page of a table or index in database iDb has changed from iFrom
74281** to iTo.
74282**
74283** Ticket #1728:  The symbol table might still contain information
74284** on tables and/or indices that are the process of being deleted.
74285** If you are unlucky, one of those deleted indices or tables might
74286** have the same rootpage number as the real table or index that is
74287** being moved.  So we cannot stop searching after the first match
74288** because the first match might be for one of the deleted indices
74289** or tables and not the table/index that is actually being moved.
74290** We must continue looping until all tables and indices with
74291** rootpage==iFrom have been converted to have a rootpage of iTo
74292** in order to be certain that we got the right one.
74293*/
74294#ifndef SQLITE_OMIT_AUTOVACUUM
74295SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
74296  HashElem *pElem;
74297  Hash *pHash;
74298
74299  pHash = &pDb->pSchema->tblHash;
74300  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74301    Table *pTab = sqliteHashData(pElem);
74302    if( pTab->tnum==iFrom ){
74303      pTab->tnum = iTo;
74304    }
74305  }
74306  pHash = &pDb->pSchema->idxHash;
74307  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74308    Index *pIdx = sqliteHashData(pElem);
74309    if( pIdx->tnum==iFrom ){
74310      pIdx->tnum = iTo;
74311    }
74312  }
74313}
74314#endif
74315
74316/*
74317** Write code to erase the table with root-page iTable from database iDb.
74318** Also write code to modify the sqlite_master table and internal schema
74319** if a root-page of another table is moved by the btree-layer whilst
74320** erasing iTable (this can happen with an auto-vacuum database).
74321*/
74322static void destroyRootPage(Parse *pParse, int iTable, int iDb){
74323  Vdbe *v = sqlite3GetVdbe(pParse);
74324  int r1 = sqlite3GetTempReg(pParse);
74325  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
74326  sqlite3MayAbort(pParse);
74327#ifndef SQLITE_OMIT_AUTOVACUUM
74328  /* OP_Destroy stores an in integer r1. If this integer
74329  ** is non-zero, then it is the root page number of a table moved to
74330  ** location iTable. The following code modifies the sqlite_master table to
74331  ** reflect this.
74332  **
74333  ** The "#NNN" in the SQL is a special constant that means whatever value
74334  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
74335  ** token for additional information.
74336  */
74337  sqlite3NestedParse(pParse,
74338     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
74339     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
74340#endif
74341  sqlite3ReleaseTempReg(pParse, r1);
74342}
74343
74344/*
74345** Write VDBE code to erase table pTab and all associated indices on disk.
74346** Code to update the sqlite_master tables and internal schema definitions
74347** in case a root-page belonging to another table is moved by the btree layer
74348** is also added (this can happen with an auto-vacuum database).
74349*/
74350static void destroyTable(Parse *pParse, Table *pTab){
74351#ifdef SQLITE_OMIT_AUTOVACUUM
74352  Index *pIdx;
74353  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74354  destroyRootPage(pParse, pTab->tnum, iDb);
74355  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74356    destroyRootPage(pParse, pIdx->tnum, iDb);
74357  }
74358#else
74359  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
74360  ** is not defined), then it is important to call OP_Destroy on the
74361  ** table and index root-pages in order, starting with the numerically
74362  ** largest root-page number. This guarantees that none of the root-pages
74363  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
74364  ** following were coded:
74365  **
74366  ** OP_Destroy 4 0
74367  ** ...
74368  ** OP_Destroy 5 0
74369  **
74370  ** and root page 5 happened to be the largest root-page number in the
74371  ** database, then root page 5 would be moved to page 4 by the
74372  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
74373  ** a free-list page.
74374  */
74375  int iTab = pTab->tnum;
74376  int iDestroyed = 0;
74377
74378  while( 1 ){
74379    Index *pIdx;
74380    int iLargest = 0;
74381
74382    if( iDestroyed==0 || iTab<iDestroyed ){
74383      iLargest = iTab;
74384    }
74385    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74386      int iIdx = pIdx->tnum;
74387      assert( pIdx->pSchema==pTab->pSchema );
74388      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
74389        iLargest = iIdx;
74390      }
74391    }
74392    if( iLargest==0 ){
74393      return;
74394    }else{
74395      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74396      destroyRootPage(pParse, iLargest, iDb);
74397      iDestroyed = iLargest;
74398    }
74399  }
74400#endif
74401}
74402
74403/*
74404** This routine is called to do the work of a DROP TABLE statement.
74405** pName is the name of the table to be dropped.
74406*/
74407SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
74408  Table *pTab;
74409  Vdbe *v;
74410  sqlite3 *db = pParse->db;
74411  int iDb;
74412
74413  if( db->mallocFailed ){
74414    goto exit_drop_table;
74415  }
74416  assert( pParse->nErr==0 );
74417  assert( pName->nSrc==1 );
74418  if( noErr ) db->suppressErr++;
74419  pTab = sqlite3LocateTable(pParse, isView,
74420                            pName->a[0].zName, pName->a[0].zDatabase);
74421  if( noErr ) db->suppressErr--;
74422
74423  if( pTab==0 ){
74424    goto exit_drop_table;
74425  }
74426  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74427  assert( iDb>=0 && iDb<db->nDb );
74428
74429  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
74430  ** it is initialized.
74431  */
74432  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
74433    goto exit_drop_table;
74434  }
74435#ifndef SQLITE_OMIT_AUTHORIZATION
74436  {
74437    int code;
74438    const char *zTab = SCHEMA_TABLE(iDb);
74439    const char *zDb = db->aDb[iDb].zName;
74440    const char *zArg2 = 0;
74441    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
74442      goto exit_drop_table;
74443    }
74444    if( isView ){
74445      if( !OMIT_TEMPDB && iDb==1 ){
74446        code = SQLITE_DROP_TEMP_VIEW;
74447      }else{
74448        code = SQLITE_DROP_VIEW;
74449      }
74450#ifndef SQLITE_OMIT_VIRTUALTABLE
74451    }else if( IsVirtual(pTab) ){
74452      code = SQLITE_DROP_VTABLE;
74453      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
74454#endif
74455    }else{
74456      if( !OMIT_TEMPDB && iDb==1 ){
74457        code = SQLITE_DROP_TEMP_TABLE;
74458      }else{
74459        code = SQLITE_DROP_TABLE;
74460      }
74461    }
74462    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
74463      goto exit_drop_table;
74464    }
74465    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
74466      goto exit_drop_table;
74467    }
74468  }
74469#endif
74470  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
74471    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
74472    goto exit_drop_table;
74473  }
74474
74475#ifndef SQLITE_OMIT_VIEW
74476  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
74477  ** on a table.
74478  */
74479  if( isView && pTab->pSelect==0 ){
74480    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
74481    goto exit_drop_table;
74482  }
74483  if( !isView && pTab->pSelect ){
74484    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
74485    goto exit_drop_table;
74486  }
74487#endif
74488
74489  /* Generate code to remove the table from the master table
74490  ** on disk.
74491  */
74492  v = sqlite3GetVdbe(pParse);
74493  if( v ){
74494    Trigger *pTrigger;
74495    Db *pDb = &db->aDb[iDb];
74496    sqlite3BeginWriteOperation(pParse, 1, iDb);
74497
74498#ifndef SQLITE_OMIT_VIRTUALTABLE
74499    if( IsVirtual(pTab) ){
74500      sqlite3VdbeAddOp0(v, OP_VBegin);
74501    }
74502#endif
74503    sqlite3FkDropTable(pParse, pName, pTab);
74504
74505    /* Drop all triggers associated with the table being dropped. Code
74506    ** is generated to remove entries from sqlite_master and/or
74507    ** sqlite_temp_master if required.
74508    */
74509    pTrigger = sqlite3TriggerList(pParse, pTab);
74510    while( pTrigger ){
74511      assert( pTrigger->pSchema==pTab->pSchema ||
74512          pTrigger->pSchema==db->aDb[1].pSchema );
74513      sqlite3DropTriggerPtr(pParse, pTrigger);
74514      pTrigger = pTrigger->pNext;
74515    }
74516
74517#ifndef SQLITE_OMIT_AUTOINCREMENT
74518    /* Remove any entries of the sqlite_sequence table associated with
74519    ** the table being dropped. This is done before the table is dropped
74520    ** at the btree level, in case the sqlite_sequence table needs to
74521    ** move as a result of the drop (can happen in auto-vacuum mode).
74522    */
74523    if( pTab->tabFlags & TF_Autoincrement ){
74524      sqlite3NestedParse(pParse,
74525        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
74526        pDb->zName, pTab->zName
74527      );
74528    }
74529#endif
74530
74531    /* Drop all SQLITE_MASTER table and index entries that refer to the
74532    ** table. The program name loops through the master table and deletes
74533    ** every row that refers to a table of the same name as the one being
74534    ** dropped. Triggers are handled seperately because a trigger can be
74535    ** created in the temp database that refers to a table in another
74536    ** database.
74537    */
74538    sqlite3NestedParse(pParse,
74539        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
74540        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
74541
74542    /* Drop any statistics from the sqlite_stat1 table, if it exists */
74543    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
74544      sqlite3NestedParse(pParse,
74545        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
74546      );
74547    }
74548
74549    if( !isView && !IsVirtual(pTab) ){
74550      destroyTable(pParse, pTab);
74551    }
74552
74553    /* Remove the table entry from SQLite's internal schema and modify
74554    ** the schema cookie.
74555    */
74556    if( IsVirtual(pTab) ){
74557      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
74558    }
74559    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74560    sqlite3ChangeCookie(pParse, iDb);
74561  }
74562  sqliteViewResetAll(db, iDb);
74563
74564exit_drop_table:
74565  sqlite3SrcListDelete(db, pName);
74566}
74567
74568/*
74569** This routine is called to create a new foreign key on the table
74570** currently under construction.  pFromCol determines which columns
74571** in the current table point to the foreign key.  If pFromCol==0 then
74572** connect the key to the last column inserted.  pTo is the name of
74573** the table referred to.  pToCol is a list of tables in the other
74574** pTo table that the foreign key points to.  flags contains all
74575** information about the conflict resolution algorithms specified
74576** in the ON DELETE, ON UPDATE and ON INSERT clauses.
74577**
74578** An FKey structure is created and added to the table currently
74579** under construction in the pParse->pNewTable field.
74580**
74581** The foreign key is set for IMMEDIATE processing.  A subsequent call
74582** to sqlite3DeferForeignKey() might change this to DEFERRED.
74583*/
74584SQLITE_PRIVATE void sqlite3CreateForeignKey(
74585  Parse *pParse,       /* Parsing context */
74586  ExprList *pFromCol,  /* Columns in this table that point to other table */
74587  Token *pTo,          /* Name of the other table */
74588  ExprList *pToCol,    /* Columns in the other table */
74589  int flags            /* Conflict resolution algorithms. */
74590){
74591  sqlite3 *db = pParse->db;
74592#ifndef SQLITE_OMIT_FOREIGN_KEY
74593  FKey *pFKey = 0;
74594  FKey *pNextTo;
74595  Table *p = pParse->pNewTable;
74596  int nByte;
74597  int i;
74598  int nCol;
74599  char *z;
74600
74601  assert( pTo!=0 );
74602  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
74603  if( pFromCol==0 ){
74604    int iCol = p->nCol-1;
74605    if( NEVER(iCol<0) ) goto fk_end;
74606    if( pToCol && pToCol->nExpr!=1 ){
74607      sqlite3ErrorMsg(pParse, "foreign key on %s"
74608         " should reference only one column of table %T",
74609         p->aCol[iCol].zName, pTo);
74610      goto fk_end;
74611    }
74612    nCol = 1;
74613  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
74614    sqlite3ErrorMsg(pParse,
74615        "number of columns in foreign key does not match the number of "
74616        "columns in the referenced table");
74617    goto fk_end;
74618  }else{
74619    nCol = pFromCol->nExpr;
74620  }
74621  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
74622  if( pToCol ){
74623    for(i=0; i<pToCol->nExpr; i++){
74624      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
74625    }
74626  }
74627  pFKey = sqlite3DbMallocZero(db, nByte );
74628  if( pFKey==0 ){
74629    goto fk_end;
74630  }
74631  pFKey->pFrom = p;
74632  pFKey->pNextFrom = p->pFKey;
74633  z = (char*)&pFKey->aCol[nCol];
74634  pFKey->zTo = z;
74635  memcpy(z, pTo->z, pTo->n);
74636  z[pTo->n] = 0;
74637  sqlite3Dequote(z);
74638  z += pTo->n+1;
74639  pFKey->nCol = nCol;
74640  if( pFromCol==0 ){
74641    pFKey->aCol[0].iFrom = p->nCol-1;
74642  }else{
74643    for(i=0; i<nCol; i++){
74644      int j;
74645      for(j=0; j<p->nCol; j++){
74646        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
74647          pFKey->aCol[i].iFrom = j;
74648          break;
74649        }
74650      }
74651      if( j>=p->nCol ){
74652        sqlite3ErrorMsg(pParse,
74653          "unknown column \"%s\" in foreign key definition",
74654          pFromCol->a[i].zName);
74655        goto fk_end;
74656      }
74657    }
74658  }
74659  if( pToCol ){
74660    for(i=0; i<nCol; i++){
74661      int n = sqlite3Strlen30(pToCol->a[i].zName);
74662      pFKey->aCol[i].zCol = z;
74663      memcpy(z, pToCol->a[i].zName, n);
74664      z[n] = 0;
74665      z += n+1;
74666    }
74667  }
74668  pFKey->isDeferred = 0;
74669  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
74670  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
74671
74672  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
74673      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
74674  );
74675  if( pNextTo==pFKey ){
74676    db->mallocFailed = 1;
74677    goto fk_end;
74678  }
74679  if( pNextTo ){
74680    assert( pNextTo->pPrevTo==0 );
74681    pFKey->pNextTo = pNextTo;
74682    pNextTo->pPrevTo = pFKey;
74683  }
74684
74685  /* Link the foreign key to the table as the last step.
74686  */
74687  p->pFKey = pFKey;
74688  pFKey = 0;
74689
74690fk_end:
74691  sqlite3DbFree(db, pFKey);
74692#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
74693  sqlite3ExprListDelete(db, pFromCol);
74694  sqlite3ExprListDelete(db, pToCol);
74695}
74696
74697/*
74698** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
74699** clause is seen as part of a foreign key definition.  The isDeferred
74700** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
74701** The behavior of the most recently created foreign key is adjusted
74702** accordingly.
74703*/
74704SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
74705#ifndef SQLITE_OMIT_FOREIGN_KEY
74706  Table *pTab;
74707  FKey *pFKey;
74708  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
74709  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
74710  pFKey->isDeferred = (u8)isDeferred;
74711#endif
74712}
74713
74714/*
74715** Generate code that will erase and refill index *pIdx.  This is
74716** used to initialize a newly created index or to recompute the
74717** content of an index in response to a REINDEX command.
74718**
74719** if memRootPage is not negative, it means that the index is newly
74720** created.  The register specified by memRootPage contains the
74721** root page number of the index.  If memRootPage is negative, then
74722** the index already exists and must be cleared before being refilled and
74723** the root page number of the index is taken from pIndex->tnum.
74724*/
74725static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
74726  Table *pTab = pIndex->pTable;  /* The table that is indexed */
74727  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
74728  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
74729  int addr1;                     /* Address of top of loop */
74730  int tnum;                      /* Root page of index */
74731  Vdbe *v;                       /* Generate code into this virtual machine */
74732  KeyInfo *pKey;                 /* KeyInfo for index */
74733  int regIdxKey;                 /* Registers containing the index key */
74734  int regRecord;                 /* Register holding assemblied index record */
74735  sqlite3 *db = pParse->db;      /* The database connection */
74736  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
74737
74738#ifndef SQLITE_OMIT_AUTHORIZATION
74739  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
74740      db->aDb[iDb].zName ) ){
74741    return;
74742  }
74743#endif
74744
74745  /* Require a write-lock on the table to perform this operation */
74746  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
74747
74748  v = sqlite3GetVdbe(pParse);
74749  if( v==0 ) return;
74750  if( memRootPage>=0 ){
74751    tnum = memRootPage;
74752  }else{
74753    tnum = pIndex->tnum;
74754    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
74755  }
74756  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
74757  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
74758                    (char *)pKey, P4_KEYINFO_HANDOFF);
74759  if( memRootPage>=0 ){
74760    sqlite3VdbeChangeP5(v, 1);
74761  }
74762  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
74763  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
74764  regRecord = sqlite3GetTempReg(pParse);
74765  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
74766  if( pIndex->onError!=OE_None ){
74767    const int regRowid = regIdxKey + pIndex->nColumn;
74768    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
74769    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
74770
74771    /* The registers accessed by the OP_IsUnique opcode were allocated
74772    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
74773    ** call above. Just before that function was freed they were released
74774    ** (made available to the compiler for reuse) using
74775    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
74776    ** opcode use the values stored within seems dangerous. However, since
74777    ** we can be sure that no other temp registers have been allocated
74778    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
74779    */
74780    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
74781    sqlite3HaltConstraint(
74782        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
74783  }
74784  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
74785  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
74786  sqlite3ReleaseTempReg(pParse, regRecord);
74787  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
74788  sqlite3VdbeJumpHere(v, addr1);
74789  sqlite3VdbeAddOp1(v, OP_Close, iTab);
74790  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
74791}
74792
74793/*
74794** Create a new index for an SQL table.  pName1.pName2 is the name of the index
74795** and pTblList is the name of the table that is to be indexed.  Both will
74796** be NULL for a primary key or an index that is created to satisfy a
74797** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
74798** as the table to be indexed.  pParse->pNewTable is a table that is
74799** currently being constructed by a CREATE TABLE statement.
74800**
74801** pList is a list of columns to be indexed.  pList will be NULL if this
74802** is a primary key or unique-constraint on the most recent column added
74803** to the table currently under construction.
74804**
74805** If the index is created successfully, return a pointer to the new Index
74806** structure. This is used by sqlite3AddPrimaryKey() to mark the index
74807** as the tables primary key (Index.autoIndex==2).
74808*/
74809SQLITE_PRIVATE Index *sqlite3CreateIndex(
74810  Parse *pParse,     /* All information about this parse */
74811  Token *pName1,     /* First part of index name. May be NULL */
74812  Token *pName2,     /* Second part of index name. May be NULL */
74813  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
74814  ExprList *pList,   /* A list of columns to be indexed */
74815  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
74816  Token *pStart,     /* The CREATE token that begins this statement */
74817  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
74818  int sortOrder,     /* Sort order of primary key when pList==NULL */
74819  int ifNotExist     /* Omit error if index already exists */
74820){
74821  Index *pRet = 0;     /* Pointer to return */
74822  Table *pTab = 0;     /* Table to be indexed */
74823  Index *pIndex = 0;   /* The index to be created */
74824  char *zName = 0;     /* Name of the index */
74825  int nName;           /* Number of characters in zName */
74826  int i, j;
74827  Token nullId;        /* Fake token for an empty ID list */
74828  DbFixer sFix;        /* For assigning database names to pTable */
74829  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
74830  sqlite3 *db = pParse->db;
74831  Db *pDb;             /* The specific table containing the indexed database */
74832  int iDb;             /* Index of the database that is being written */
74833  Token *pName = 0;    /* Unqualified name of the index to create */
74834  struct ExprList_item *pListItem; /* For looping over pList */
74835  int nCol;
74836  int nExtra = 0;
74837  char *zExtra;
74838
74839  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
74840  assert( pParse->nErr==0 );      /* Never called with prior errors */
74841  if( db->mallocFailed || IN_DECLARE_VTAB ){
74842    goto exit_create_index;
74843  }
74844  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74845    goto exit_create_index;
74846  }
74847
74848  /*
74849  ** Find the table that is to be indexed.  Return early if not found.
74850  */
74851  if( pTblName!=0 ){
74852
74853    /* Use the two-part index name to determine the database
74854    ** to search for the table. 'Fix' the table name to this db
74855    ** before looking up the table.
74856    */
74857    assert( pName1 && pName2 );
74858    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74859    if( iDb<0 ) goto exit_create_index;
74860
74861#ifndef SQLITE_OMIT_TEMPDB
74862    /* If the index name was unqualified, check if the the table
74863    ** is a temp table. If so, set the database to 1. Do not do this
74864    ** if initialising a database schema.
74865    */
74866    if( !db->init.busy ){
74867      pTab = sqlite3SrcListLookup(pParse, pTblName);
74868      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
74869        iDb = 1;
74870      }
74871    }
74872#endif
74873
74874    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
74875        sqlite3FixSrcList(&sFix, pTblName)
74876    ){
74877      /* Because the parser constructs pTblName from a single identifier,
74878      ** sqlite3FixSrcList can never fail. */
74879      assert(0);
74880    }
74881    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
74882        pTblName->a[0].zDatabase);
74883    if( !pTab || db->mallocFailed ) goto exit_create_index;
74884    assert( db->aDb[iDb].pSchema==pTab->pSchema );
74885  }else{
74886    assert( pName==0 );
74887    pTab = pParse->pNewTable;
74888    if( !pTab ) goto exit_create_index;
74889    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74890  }
74891  pDb = &db->aDb[iDb];
74892
74893  assert( pTab!=0 );
74894  assert( pParse->nErr==0 );
74895  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
74896       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
74897    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
74898    goto exit_create_index;
74899  }
74900#ifndef SQLITE_OMIT_VIEW
74901  if( pTab->pSelect ){
74902    sqlite3ErrorMsg(pParse, "views may not be indexed");
74903    goto exit_create_index;
74904  }
74905#endif
74906#ifndef SQLITE_OMIT_VIRTUALTABLE
74907  if( IsVirtual(pTab) ){
74908    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
74909    goto exit_create_index;
74910  }
74911#endif
74912
74913  /*
74914  ** Find the name of the index.  Make sure there is not already another
74915  ** index or table with the same name.
74916  **
74917  ** Exception:  If we are reading the names of permanent indices from the
74918  ** sqlite_master table (because some other process changed the schema) and
74919  ** one of the index names collides with the name of a temporary table or
74920  ** index, then we will continue to process this index.
74921  **
74922  ** If pName==0 it means that we are
74923  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
74924  ** own name.
74925  */
74926  if( pName ){
74927    zName = sqlite3NameFromToken(db, pName);
74928    if( zName==0 ) goto exit_create_index;
74929    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
74930      goto exit_create_index;
74931    }
74932    if( !db->init.busy ){
74933      if( sqlite3FindTable(db, zName, 0)!=0 ){
74934        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
74935        goto exit_create_index;
74936      }
74937    }
74938    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
74939      if( !ifNotExist ){
74940        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
74941      }
74942      goto exit_create_index;
74943    }
74944  }else{
74945    int n;
74946    Index *pLoop;
74947    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
74948    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
74949    if( zName==0 ){
74950      goto exit_create_index;
74951    }
74952  }
74953
74954  /* Check for authorization to create an index.
74955  */
74956#ifndef SQLITE_OMIT_AUTHORIZATION
74957  {
74958    const char *zDb = pDb->zName;
74959    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
74960      goto exit_create_index;
74961    }
74962    i = SQLITE_CREATE_INDEX;
74963    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
74964    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
74965      goto exit_create_index;
74966    }
74967  }
74968#endif
74969
74970  /* If pList==0, it means this routine was called to make a primary
74971  ** key out of the last column added to the table under construction.
74972  ** So create a fake list to simulate this.
74973  */
74974  if( pList==0 ){
74975    nullId.z = pTab->aCol[pTab->nCol-1].zName;
74976    nullId.n = sqlite3Strlen30((char*)nullId.z);
74977    pList = sqlite3ExprListAppend(pParse, 0, 0);
74978    if( pList==0 ) goto exit_create_index;
74979    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
74980    pList->a[0].sortOrder = (u8)sortOrder;
74981  }
74982
74983  /* Figure out how many bytes of space are required to store explicitly
74984  ** specified collation sequence names.
74985  */
74986  for(i=0; i<pList->nExpr; i++){
74987    Expr *pExpr = pList->a[i].pExpr;
74988    if( pExpr ){
74989      CollSeq *pColl = pExpr->pColl;
74990      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
74991      ** failure we have quit before reaching this point. */
74992      if( ALWAYS(pColl) ){
74993        nExtra += (1 + sqlite3Strlen30(pColl->zName));
74994      }
74995    }
74996  }
74997
74998  /*
74999  ** Allocate the index structure.
75000  */
75001  nName = sqlite3Strlen30(zName);
75002  nCol = pList->nExpr;
75003  pIndex = sqlite3DbMallocZero(db,
75004      sizeof(Index) +              /* Index structure  */
75005      sizeof(int)*nCol +           /* Index.aiColumn   */
75006      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
75007      sizeof(char *)*nCol +        /* Index.azColl     */
75008      sizeof(u8)*nCol +            /* Index.aSortOrder */
75009      nName + 1 +                  /* Index.zName      */
75010      nExtra                       /* Collation sequence names */
75011  );
75012  if( db->mallocFailed ){
75013    goto exit_create_index;
75014  }
75015  pIndex->azColl = (char**)(&pIndex[1]);
75016  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
75017  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
75018  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
75019  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
75020  zExtra = (char *)(&pIndex->zName[nName+1]);
75021  memcpy(pIndex->zName, zName, nName+1);
75022  pIndex->pTable = pTab;
75023  pIndex->nColumn = pList->nExpr;
75024  pIndex->onError = (u8)onError;
75025  pIndex->autoIndex = (u8)(pName==0);
75026  pIndex->pSchema = db->aDb[iDb].pSchema;
75027
75028  /* Check to see if we should honor DESC requests on index columns
75029  */
75030  if( pDb->pSchema->file_format>=4 ){
75031    sortOrderMask = -1;   /* Honor DESC */
75032  }else{
75033    sortOrderMask = 0;    /* Ignore DESC */
75034  }
75035
75036  /* Scan the names of the columns of the table to be indexed and
75037  ** load the column indices into the Index structure.  Report an error
75038  ** if any column is not found.
75039  **
75040  ** TODO:  Add a test to make sure that the same column is not named
75041  ** more than once within the same index.  Only the first instance of
75042  ** the column will ever be used by the optimizer.  Note that using the
75043  ** same column more than once cannot be an error because that would
75044  ** break backwards compatibility - it needs to be a warning.
75045  */
75046  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
75047    const char *zColName = pListItem->zName;
75048    Column *pTabCol;
75049    int requestedSortOrder;
75050    char *zColl;                   /* Collation sequence name */
75051
75052    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
75053      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
75054    }
75055    if( j>=pTab->nCol ){
75056      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
75057        pTab->zName, zColName);
75058      pParse->checkSchema = 1;
75059      goto exit_create_index;
75060    }
75061    pIndex->aiColumn[i] = j;
75062    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
75063    ** the way the "idxlist" non-terminal is constructed by the parser,
75064    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
75065    ** must exist or else there must have been an OOM error.  But if there
75066    ** was an OOM error, we would never reach this point. */
75067    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
75068      int nColl;
75069      zColl = pListItem->pExpr->pColl->zName;
75070      nColl = sqlite3Strlen30(zColl) + 1;
75071      assert( nExtra>=nColl );
75072      memcpy(zExtra, zColl, nColl);
75073      zColl = zExtra;
75074      zExtra += nColl;
75075      nExtra -= nColl;
75076    }else{
75077      zColl = pTab->aCol[j].zColl;
75078      if( !zColl ){
75079        zColl = db->pDfltColl->zName;
75080      }
75081    }
75082    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
75083      goto exit_create_index;
75084    }
75085    pIndex->azColl[i] = zColl;
75086    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
75087    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
75088  }
75089  sqlite3DefaultRowEst(pIndex);
75090
75091  if( pTab==pParse->pNewTable ){
75092    /* This routine has been called to create an automatic index as a
75093    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
75094    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
75095    ** i.e. one of:
75096    **
75097    ** CREATE TABLE t(x PRIMARY KEY, y);
75098    ** CREATE TABLE t(x, y, UNIQUE(x, y));
75099    **
75100    ** Either way, check to see if the table already has such an index. If
75101    ** so, don't bother creating this one. This only applies to
75102    ** automatically created indices. Users can do as they wish with
75103    ** explicit indices.
75104    **
75105    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
75106    ** (and thus suppressing the second one) even if they have different
75107    ** sort orders.
75108    **
75109    ** If there are different collating sequences or if the columns of
75110    ** the constraint occur in different orders, then the constraints are
75111    ** considered distinct and both result in separate indices.
75112    */
75113    Index *pIdx;
75114    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75115      int k;
75116      assert( pIdx->onError!=OE_None );
75117      assert( pIdx->autoIndex );
75118      assert( pIndex->onError!=OE_None );
75119
75120      if( pIdx->nColumn!=pIndex->nColumn ) continue;
75121      for(k=0; k<pIdx->nColumn; k++){
75122        const char *z1;
75123        const char *z2;
75124        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
75125        z1 = pIdx->azColl[k];
75126        z2 = pIndex->azColl[k];
75127        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
75128      }
75129      if( k==pIdx->nColumn ){
75130        if( pIdx->onError!=pIndex->onError ){
75131          /* This constraint creates the same index as a previous
75132          ** constraint specified somewhere in the CREATE TABLE statement.
75133          ** However the ON CONFLICT clauses are different. If both this
75134          ** constraint and the previous equivalent constraint have explicit
75135          ** ON CONFLICT clauses this is an error. Otherwise, use the
75136          ** explicitly specified behaviour for the index.
75137          */
75138          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
75139            sqlite3ErrorMsg(pParse,
75140                "conflicting ON CONFLICT clauses specified", 0);
75141          }
75142          if( pIdx->onError==OE_Default ){
75143            pIdx->onError = pIndex->onError;
75144          }
75145        }
75146        goto exit_create_index;
75147      }
75148    }
75149  }
75150
75151  /* Link the new Index structure to its table and to the other
75152  ** in-memory database structures.
75153  */
75154  if( db->init.busy ){
75155    Index *p;
75156    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
75157                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
75158                          pIndex);
75159    if( p ){
75160      assert( p==pIndex );  /* Malloc must have failed */
75161      db->mallocFailed = 1;
75162      goto exit_create_index;
75163    }
75164    db->flags |= SQLITE_InternChanges;
75165    if( pTblName!=0 ){
75166      pIndex->tnum = db->init.newTnum;
75167    }
75168  }
75169
75170  /* If the db->init.busy is 0 then create the index on disk.  This
75171  ** involves writing the index into the master table and filling in the
75172  ** index with the current table contents.
75173  **
75174  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
75175  ** command.  db->init.busy is 1 when a database is opened and
75176  ** CREATE INDEX statements are read out of the master table.  In
75177  ** the latter case the index already exists on disk, which is why
75178  ** we don't want to recreate it.
75179  **
75180  ** If pTblName==0 it means this index is generated as a primary key
75181  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
75182  ** has just been created, it contains no data and the index initialization
75183  ** step can be skipped.
75184  */
75185  else{ /* if( db->init.busy==0 ) */
75186    Vdbe *v;
75187    char *zStmt;
75188    int iMem = ++pParse->nMem;
75189
75190    v = sqlite3GetVdbe(pParse);
75191    if( v==0 ) goto exit_create_index;
75192
75193
75194    /* Create the rootpage for the index
75195    */
75196    sqlite3BeginWriteOperation(pParse, 1, iDb);
75197    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
75198
75199    /* Gather the complete text of the CREATE INDEX statement into
75200    ** the zStmt variable
75201    */
75202    if( pStart ){
75203      assert( pEnd!=0 );
75204      /* A named index with an explicit CREATE INDEX statement */
75205      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
75206        onError==OE_None ? "" : " UNIQUE",
75207        pEnd->z - pName->z + 1,
75208        pName->z);
75209    }else{
75210      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
75211      /* zStmt = sqlite3MPrintf(""); */
75212      zStmt = 0;
75213    }
75214
75215    /* Add an entry in sqlite_master for this index
75216    */
75217    sqlite3NestedParse(pParse,
75218        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
75219        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75220        pIndex->zName,
75221        pTab->zName,
75222        iMem,
75223        zStmt
75224    );
75225    sqlite3DbFree(db, zStmt);
75226
75227    /* Fill the index with data and reparse the schema. Code an OP_Expire
75228    ** to invalidate all pre-compiled statements.
75229    */
75230    if( pTblName ){
75231      sqlite3RefillIndex(pParse, pIndex, iMem);
75232      sqlite3ChangeCookie(pParse, iDb);
75233      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
75234         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
75235      sqlite3VdbeAddOp1(v, OP_Expire, 0);
75236    }
75237  }
75238
75239  /* When adding an index to the list of indices for a table, make
75240  ** sure all indices labeled OE_Replace come after all those labeled
75241  ** OE_Ignore.  This is necessary for the correct constraint check
75242  ** processing (in sqlite3GenerateConstraintChecks()) as part of
75243  ** UPDATE and INSERT statements.
75244  */
75245  if( db->init.busy || pTblName==0 ){
75246    if( onError!=OE_Replace || pTab->pIndex==0
75247         || pTab->pIndex->onError==OE_Replace){
75248      pIndex->pNext = pTab->pIndex;
75249      pTab->pIndex = pIndex;
75250    }else{
75251      Index *pOther = pTab->pIndex;
75252      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
75253        pOther = pOther->pNext;
75254      }
75255      pIndex->pNext = pOther->pNext;
75256      pOther->pNext = pIndex;
75257    }
75258    pRet = pIndex;
75259    pIndex = 0;
75260  }
75261
75262  /* Clean up before exiting */
75263exit_create_index:
75264  if( pIndex ){
75265    sqlite3_free(pIndex->zColAff);
75266    sqlite3DbFree(db, pIndex);
75267  }
75268  sqlite3ExprListDelete(db, pList);
75269  sqlite3SrcListDelete(db, pTblName);
75270  sqlite3DbFree(db, zName);
75271  return pRet;
75272}
75273
75274/*
75275** Fill the Index.aiRowEst[] array with default information - information
75276** to be used when we have not run the ANALYZE command.
75277**
75278** aiRowEst[0] is suppose to contain the number of elements in the index.
75279** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
75280** number of rows in the table that match any particular value of the
75281** first column of the index.  aiRowEst[2] is an estimate of the number
75282** of rows that match any particular combiniation of the first 2 columns
75283** of the index.  And so forth.  It must always be the case that
75284*
75285**           aiRowEst[N]<=aiRowEst[N-1]
75286**           aiRowEst[N]>=1
75287**
75288** Apart from that, we have little to go on besides intuition as to
75289** how aiRowEst[] should be initialized.  The numbers generated here
75290** are based on typical values found in actual indices.
75291*/
75292SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
75293  unsigned *a = pIdx->aiRowEst;
75294  int i;
75295  assert( a!=0 );
75296  a[0] = 1000000;
75297  for(i=pIdx->nColumn; i>=5; i--){
75298    a[i] = 5;
75299  }
75300  while( i>=1 ){
75301    a[i] = 11 - i;
75302    i--;
75303  }
75304  if( pIdx->onError!=OE_None ){
75305    a[pIdx->nColumn] = 1;
75306  }
75307}
75308
75309/*
75310** This routine will drop an existing named index.  This routine
75311** implements the DROP INDEX statement.
75312*/
75313SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
75314  Index *pIndex;
75315  Vdbe *v;
75316  sqlite3 *db = pParse->db;
75317  int iDb;
75318
75319  assert( pParse->nErr==0 );   /* Never called with prior errors */
75320  if( db->mallocFailed ){
75321    goto exit_drop_index;
75322  }
75323  assert( pName->nSrc==1 );
75324  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75325    goto exit_drop_index;
75326  }
75327  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
75328  if( pIndex==0 ){
75329    if( !ifExists ){
75330      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
75331    }
75332    pParse->checkSchema = 1;
75333    goto exit_drop_index;
75334  }
75335  if( pIndex->autoIndex ){
75336    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
75337      "or PRIMARY KEY constraint cannot be dropped", 0);
75338    goto exit_drop_index;
75339  }
75340  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
75341#ifndef SQLITE_OMIT_AUTHORIZATION
75342  {
75343    int code = SQLITE_DROP_INDEX;
75344    Table *pTab = pIndex->pTable;
75345    const char *zDb = db->aDb[iDb].zName;
75346    const char *zTab = SCHEMA_TABLE(iDb);
75347    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
75348      goto exit_drop_index;
75349    }
75350    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
75351    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
75352      goto exit_drop_index;
75353    }
75354  }
75355#endif
75356
75357  /* Generate code to remove the index and from the master table */
75358  v = sqlite3GetVdbe(pParse);
75359  if( v ){
75360    sqlite3BeginWriteOperation(pParse, 1, iDb);
75361    sqlite3NestedParse(pParse,
75362       "DELETE FROM %Q.%s WHERE name=%Q",
75363       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75364       pIndex->zName
75365    );
75366    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
75367      sqlite3NestedParse(pParse,
75368        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
75369        db->aDb[iDb].zName, pIndex->zName
75370      );
75371    }
75372    sqlite3ChangeCookie(pParse, iDb);
75373    destroyRootPage(pParse, pIndex->tnum, iDb);
75374    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
75375  }
75376
75377exit_drop_index:
75378  sqlite3SrcListDelete(db, pName);
75379}
75380
75381/*
75382** pArray is a pointer to an array of objects.  Each object in the
75383** array is szEntry bytes in size.  This routine allocates a new
75384** object on the end of the array.
75385**
75386** *pnEntry is the number of entries already in use.  *pnAlloc is
75387** the previously allocated size of the array.  initSize is the
75388** suggested initial array size allocation.
75389**
75390** The index of the new entry is returned in *pIdx.
75391**
75392** This routine returns a pointer to the array of objects.  This
75393** might be the same as the pArray parameter or it might be a different
75394** pointer if the array was resized.
75395*/
75396SQLITE_PRIVATE void *sqlite3ArrayAllocate(
75397  sqlite3 *db,      /* Connection to notify of malloc failures */
75398  void *pArray,     /* Array of objects.  Might be reallocated */
75399  int szEntry,      /* Size of each object in the array */
75400  int initSize,     /* Suggested initial allocation, in elements */
75401  int *pnEntry,     /* Number of objects currently in use */
75402  int *pnAlloc,     /* Current size of the allocation, in elements */
75403  int *pIdx         /* Write the index of a new slot here */
75404){
75405  char *z;
75406  if( *pnEntry >= *pnAlloc ){
75407    void *pNew;
75408    int newSize;
75409    newSize = (*pnAlloc)*2 + initSize;
75410    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
75411    if( pNew==0 ){
75412      *pIdx = -1;
75413      return pArray;
75414    }
75415    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
75416    pArray = pNew;
75417  }
75418  z = (char*)pArray;
75419  memset(&z[*pnEntry * szEntry], 0, szEntry);
75420  *pIdx = *pnEntry;
75421  ++*pnEntry;
75422  return pArray;
75423}
75424
75425/*
75426** Append a new element to the given IdList.  Create a new IdList if
75427** need be.
75428**
75429** A new IdList is returned, or NULL if malloc() fails.
75430*/
75431SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
75432  int i;
75433  if( pList==0 ){
75434    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
75435    if( pList==0 ) return 0;
75436    pList->nAlloc = 0;
75437  }
75438  pList->a = sqlite3ArrayAllocate(
75439      db,
75440      pList->a,
75441      sizeof(pList->a[0]),
75442      5,
75443      &pList->nId,
75444      &pList->nAlloc,
75445      &i
75446  );
75447  if( i<0 ){
75448    sqlite3IdListDelete(db, pList);
75449    return 0;
75450  }
75451  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
75452  return pList;
75453}
75454
75455/*
75456** Delete an IdList.
75457*/
75458SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
75459  int i;
75460  if( pList==0 ) return;
75461  for(i=0; i<pList->nId; i++){
75462    sqlite3DbFree(db, pList->a[i].zName);
75463  }
75464  sqlite3DbFree(db, pList->a);
75465  sqlite3DbFree(db, pList);
75466}
75467
75468/*
75469** Return the index in pList of the identifier named zId.  Return -1
75470** if not found.
75471*/
75472SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
75473  int i;
75474  if( pList==0 ) return -1;
75475  for(i=0; i<pList->nId; i++){
75476    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
75477  }
75478  return -1;
75479}
75480
75481/*
75482** Expand the space allocated for the given SrcList object by
75483** creating nExtra new slots beginning at iStart.  iStart is zero based.
75484** New slots are zeroed.
75485**
75486** For example, suppose a SrcList initially contains two entries: A,B.
75487** To append 3 new entries onto the end, do this:
75488**
75489**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
75490**
75491** After the call above it would contain:  A, B, nil, nil, nil.
75492** If the iStart argument had been 1 instead of 2, then the result
75493** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
75494** the iStart value would be 0.  The result then would
75495** be: nil, nil, nil, A, B.
75496**
75497** If a memory allocation fails the SrcList is unchanged.  The
75498** db->mallocFailed flag will be set to true.
75499*/
75500SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
75501  sqlite3 *db,       /* Database connection to notify of OOM errors */
75502  SrcList *pSrc,     /* The SrcList to be enlarged */
75503  int nExtra,        /* Number of new slots to add to pSrc->a[] */
75504  int iStart         /* Index in pSrc->a[] of first new slot */
75505){
75506  int i;
75507
75508  /* Sanity checking on calling parameters */
75509  assert( iStart>=0 );
75510  assert( nExtra>=1 );
75511  assert( pSrc!=0 );
75512  assert( iStart<=pSrc->nSrc );
75513
75514  /* Allocate additional space if needed */
75515  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
75516    SrcList *pNew;
75517    int nAlloc = pSrc->nSrc+nExtra;
75518    int nGot;
75519    pNew = sqlite3DbRealloc(db, pSrc,
75520               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
75521    if( pNew==0 ){
75522      assert( db->mallocFailed );
75523      return pSrc;
75524    }
75525    pSrc = pNew;
75526    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
75527    pSrc->nAlloc = (u16)nGot;
75528  }
75529
75530  /* Move existing slots that come after the newly inserted slots
75531  ** out of the way */
75532  for(i=pSrc->nSrc-1; i>=iStart; i--){
75533    pSrc->a[i+nExtra] = pSrc->a[i];
75534  }
75535  pSrc->nSrc += (i16)nExtra;
75536
75537  /* Zero the newly allocated slots */
75538  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
75539  for(i=iStart; i<iStart+nExtra; i++){
75540    pSrc->a[i].iCursor = -1;
75541  }
75542
75543  /* Return a pointer to the enlarged SrcList */
75544  return pSrc;
75545}
75546
75547
75548/*
75549** Append a new table name to the given SrcList.  Create a new SrcList if
75550** need be.  A new entry is created in the SrcList even if pTable is NULL.
75551**
75552** A SrcList is returned, or NULL if there is an OOM error.  The returned
75553** SrcList might be the same as the SrcList that was input or it might be
75554** a new one.  If an OOM error does occurs, then the prior value of pList
75555** that is input to this routine is automatically freed.
75556**
75557** If pDatabase is not null, it means that the table has an optional
75558** database name prefix.  Like this:  "database.table".  The pDatabase
75559** points to the table name and the pTable points to the database name.
75560** The SrcList.a[].zName field is filled with the table name which might
75561** come from pTable (if pDatabase is NULL) or from pDatabase.
75562** SrcList.a[].zDatabase is filled with the database name from pTable,
75563** or with NULL if no database is specified.
75564**
75565** In other words, if call like this:
75566**
75567**         sqlite3SrcListAppend(D,A,B,0);
75568**
75569** Then B is a table name and the database name is unspecified.  If called
75570** like this:
75571**
75572**         sqlite3SrcListAppend(D,A,B,C);
75573**
75574** Then C is the table name and B is the database name.  If C is defined
75575** then so is B.  In other words, we never have a case where:
75576**
75577**         sqlite3SrcListAppend(D,A,0,C);
75578**
75579** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
75580** before being added to the SrcList.
75581*/
75582SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
75583  sqlite3 *db,        /* Connection to notify of malloc failures */
75584  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
75585  Token *pTable,      /* Table to append */
75586  Token *pDatabase    /* Database of the table */
75587){
75588  struct SrcList_item *pItem;
75589  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
75590  if( pList==0 ){
75591    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
75592    if( pList==0 ) return 0;
75593    pList->nAlloc = 1;
75594  }
75595  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
75596  if( db->mallocFailed ){
75597    sqlite3SrcListDelete(db, pList);
75598    return 0;
75599  }
75600  pItem = &pList->a[pList->nSrc-1];
75601  if( pDatabase && pDatabase->z==0 ){
75602    pDatabase = 0;
75603  }
75604  if( pDatabase ){
75605    Token *pTemp = pDatabase;
75606    pDatabase = pTable;
75607    pTable = pTemp;
75608  }
75609  pItem->zName = sqlite3NameFromToken(db, pTable);
75610  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
75611  return pList;
75612}
75613
75614/*
75615** Assign VdbeCursor index numbers to all tables in a SrcList
75616*/
75617SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
75618  int i;
75619  struct SrcList_item *pItem;
75620  assert(pList || pParse->db->mallocFailed );
75621  if( pList ){
75622    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
75623      if( pItem->iCursor>=0 ) break;
75624      pItem->iCursor = pParse->nTab++;
75625      if( pItem->pSelect ){
75626        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
75627      }
75628    }
75629  }
75630}
75631
75632/*
75633** Delete an entire SrcList including all its substructure.
75634*/
75635SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
75636  int i;
75637  struct SrcList_item *pItem;
75638  if( pList==0 ) return;
75639  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
75640    sqlite3DbFree(db, pItem->zDatabase);
75641    sqlite3DbFree(db, pItem->zName);
75642    sqlite3DbFree(db, pItem->zAlias);
75643    sqlite3DbFree(db, pItem->zIndex);
75644    sqlite3DeleteTable(pItem->pTab);
75645    sqlite3SelectDelete(db, pItem->pSelect);
75646    sqlite3ExprDelete(db, pItem->pOn);
75647    sqlite3IdListDelete(db, pItem->pUsing);
75648  }
75649  sqlite3DbFree(db, pList);
75650}
75651
75652/*
75653** This routine is called by the parser to add a new term to the
75654** end of a growing FROM clause.  The "p" parameter is the part of
75655** the FROM clause that has already been constructed.  "p" is NULL
75656** if this is the first term of the FROM clause.  pTable and pDatabase
75657** are the name of the table and database named in the FROM clause term.
75658** pDatabase is NULL if the database name qualifier is missing - the
75659** usual case.  If the term has a alias, then pAlias points to the
75660** alias token.  If the term is a subquery, then pSubquery is the
75661** SELECT statement that the subquery encodes.  The pTable and
75662** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
75663** parameters are the content of the ON and USING clauses.
75664**
75665** Return a new SrcList which encodes is the FROM with the new
75666** term added.
75667*/
75668SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
75669  Parse *pParse,          /* Parsing context */
75670  SrcList *p,             /* The left part of the FROM clause already seen */
75671  Token *pTable,          /* Name of the table to add to the FROM clause */
75672  Token *pDatabase,       /* Name of the database containing pTable */
75673  Token *pAlias,          /* The right-hand side of the AS subexpression */
75674  Select *pSubquery,      /* A subquery used in place of a table name */
75675  Expr *pOn,              /* The ON clause of a join */
75676  IdList *pUsing          /* The USING clause of a join */
75677){
75678  struct SrcList_item *pItem;
75679  sqlite3 *db = pParse->db;
75680  if( !p && (pOn || pUsing) ){
75681    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
75682      (pOn ? "ON" : "USING")
75683    );
75684    goto append_from_error;
75685  }
75686  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
75687  if( p==0 || NEVER(p->nSrc==0) ){
75688    goto append_from_error;
75689  }
75690  pItem = &p->a[p->nSrc-1];
75691  assert( pAlias!=0 );
75692  if( pAlias->n ){
75693    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
75694  }
75695  pItem->pSelect = pSubquery;
75696  pItem->pOn = pOn;
75697  pItem->pUsing = pUsing;
75698  return p;
75699
75700 append_from_error:
75701  assert( p==0 );
75702  sqlite3ExprDelete(db, pOn);
75703  sqlite3IdListDelete(db, pUsing);
75704  sqlite3SelectDelete(db, pSubquery);
75705  return 0;
75706}
75707
75708/*
75709** Add an INDEXED BY or NOT INDEXED clause to the most recently added
75710** element of the source-list passed as the second argument.
75711*/
75712SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
75713  assert( pIndexedBy!=0 );
75714  if( p && ALWAYS(p->nSrc>0) ){
75715    struct SrcList_item *pItem = &p->a[p->nSrc-1];
75716    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
75717    if( pIndexedBy->n==1 && !pIndexedBy->z ){
75718      /* A "NOT INDEXED" clause was supplied. See parse.y
75719      ** construct "indexed_opt" for details. */
75720      pItem->notIndexed = 1;
75721    }else{
75722      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
75723    }
75724  }
75725}
75726
75727/*
75728** When building up a FROM clause in the parser, the join operator
75729** is initially attached to the left operand.  But the code generator
75730** expects the join operator to be on the right operand.  This routine
75731** Shifts all join operators from left to right for an entire FROM
75732** clause.
75733**
75734** Example: Suppose the join is like this:
75735**
75736**           A natural cross join B
75737**
75738** The operator is "natural cross join".  The A and B operands are stored
75739** in p->a[0] and p->a[1], respectively.  The parser initially stores the
75740** operator with A.  This routine shifts that operator over to B.
75741*/
75742SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
75743  if( p && p->a ){
75744    int i;
75745    for(i=p->nSrc-1; i>0; i--){
75746      p->a[i].jointype = p->a[i-1].jointype;
75747    }
75748    p->a[0].jointype = 0;
75749  }
75750}
75751
75752/*
75753** Begin a transaction
75754*/
75755SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
75756  sqlite3 *db;
75757  Vdbe *v;
75758  int i;
75759
75760  assert( pParse!=0 );
75761  db = pParse->db;
75762  assert( db!=0 );
75763/*  if( db->aDb[0].pBt==0 ) return; */
75764  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
75765    return;
75766  }
75767  v = sqlite3GetVdbe(pParse);
75768  if( !v ) return;
75769  if( type!=TK_DEFERRED ){
75770    for(i=0; i<db->nDb; i++){
75771      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
75772      sqlite3VdbeUsesBtree(v, i);
75773    }
75774  }
75775  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
75776}
75777
75778/*
75779** Commit a transaction
75780*/
75781SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
75782  sqlite3 *db;
75783  Vdbe *v;
75784
75785  assert( pParse!=0 );
75786  db = pParse->db;
75787  assert( db!=0 );
75788/*  if( db->aDb[0].pBt==0 ) return; */
75789  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
75790    return;
75791  }
75792  v = sqlite3GetVdbe(pParse);
75793  if( v ){
75794    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
75795  }
75796}
75797
75798/*
75799** Rollback a transaction
75800*/
75801SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
75802  sqlite3 *db;
75803  Vdbe *v;
75804
75805  assert( pParse!=0 );
75806  db = pParse->db;
75807  assert( db!=0 );
75808/*  if( db->aDb[0].pBt==0 ) return; */
75809  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
75810    return;
75811  }
75812  v = sqlite3GetVdbe(pParse);
75813  if( v ){
75814    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
75815  }
75816}
75817
75818/*
75819** This function is called by the parser when it parses a command to create,
75820** release or rollback an SQL savepoint.
75821*/
75822SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
75823  char *zName = sqlite3NameFromToken(pParse->db, pName);
75824  if( zName ){
75825    Vdbe *v = sqlite3GetVdbe(pParse);
75826#ifndef SQLITE_OMIT_AUTHORIZATION
75827    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
75828    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
75829#endif
75830    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
75831      sqlite3DbFree(pParse->db, zName);
75832      return;
75833    }
75834    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
75835  }
75836}
75837
75838/*
75839** Make sure the TEMP database is open and available for use.  Return
75840** the number of errors.  Leave any error messages in the pParse structure.
75841*/
75842SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
75843  sqlite3 *db = pParse->db;
75844  if( db->aDb[1].pBt==0 && !pParse->explain ){
75845    int rc;
75846    Btree *pBt;
75847    static const int flags =
75848          SQLITE_OPEN_READWRITE |
75849          SQLITE_OPEN_CREATE |
75850          SQLITE_OPEN_EXCLUSIVE |
75851          SQLITE_OPEN_DELETEONCLOSE |
75852          SQLITE_OPEN_TEMP_DB;
75853
75854    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
75855    if( rc!=SQLITE_OK ){
75856      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
75857        "file for storing temporary tables");
75858      pParse->rc = rc;
75859      return 1;
75860    }
75861    db->aDb[1].pBt = pBt;
75862    assert( db->aDb[1].pSchema );
75863    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
75864      db->mallocFailed = 1;
75865      return 1;
75866    }
75867    sqlite3PagerSetJournalMode(sqlite3BtreePager(pBt), db->dfltJournalMode);
75868  }
75869  return 0;
75870}
75871
75872/*
75873** Generate VDBE code that will verify the schema cookie and start
75874** a read-transaction for all named database files.
75875**
75876** It is important that all schema cookies be verified and all
75877** read transactions be started before anything else happens in
75878** the VDBE program.  But this routine can be called after much other
75879** code has been generated.  So here is what we do:
75880**
75881** The first time this routine is called, we code an OP_Goto that
75882** will jump to a subroutine at the end of the program.  Then we
75883** record every database that needs its schema verified in the
75884** pParse->cookieMask field.  Later, after all other code has been
75885** generated, the subroutine that does the cookie verifications and
75886** starts the transactions will be coded and the OP_Goto P2 value
75887** will be made to point to that subroutine.  The generation of the
75888** cookie verification subroutine code happens in sqlite3FinishCoding().
75889**
75890** If iDb<0 then code the OP_Goto only - don't set flag to verify the
75891** schema on any databases.  This can be used to position the OP_Goto
75892** early in the code, before we know if any database tables will be used.
75893*/
75894SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
75895  Parse *pToplevel = sqlite3ParseToplevel(pParse);
75896
75897  if( pToplevel->cookieGoto==0 ){
75898    Vdbe *v = sqlite3GetVdbe(pToplevel);
75899    if( v==0 ) return;  /* This only happens if there was a prior error */
75900    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
75901  }
75902  if( iDb>=0 ){
75903    sqlite3 *db = pToplevel->db;
75904    int mask;
75905
75906    assert( iDb<db->nDb );
75907    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
75908    assert( iDb<SQLITE_MAX_ATTACHED+2 );
75909    mask = 1<<iDb;
75910    if( (pToplevel->cookieMask & mask)==0 ){
75911      pToplevel->cookieMask |= mask;
75912      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
75913      if( !OMIT_TEMPDB && iDb==1 ){
75914        sqlite3OpenTempDatabase(pToplevel);
75915      }
75916    }
75917  }
75918}
75919
75920/*
75921** Generate VDBE code that prepares for doing an operation that
75922** might change the database.
75923**
75924** This routine starts a new transaction if we are not already within
75925** a transaction.  If we are already within a transaction, then a checkpoint
75926** is set if the setStatement parameter is true.  A checkpoint should
75927** be set for operations that might fail (due to a constraint) part of
75928** the way through and which will need to undo some writes without having to
75929** rollback the whole transaction.  For operations where all constraints
75930** can be checked before any changes are made to the database, it is never
75931** necessary to undo a write and the checkpoint should not be set.
75932*/
75933SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
75934  Parse *pToplevel = sqlite3ParseToplevel(pParse);
75935  sqlite3CodeVerifySchema(pParse, iDb);
75936  pToplevel->writeMask |= 1<<iDb;
75937  pToplevel->isMultiWrite |= setStatement;
75938}
75939
75940/*
75941** Indicate that the statement currently under construction might write
75942** more than one entry (example: deleting one row then inserting another,
75943** inserting multiple rows in a table, or inserting a row and index entries.)
75944** If an abort occurs after some of these writes have completed, then it will
75945** be necessary to undo the completed writes.
75946*/
75947SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
75948  Parse *pToplevel = sqlite3ParseToplevel(pParse);
75949  pToplevel->isMultiWrite = 1;
75950}
75951
75952/*
75953** The code generator calls this routine if is discovers that it is
75954** possible to abort a statement prior to completion.  In order to
75955** perform this abort without corrupting the database, we need to make
75956** sure that the statement is protected by a statement transaction.
75957**
75958** Technically, we only need to set the mayAbort flag if the
75959** isMultiWrite flag was previously set.  There is a time dependency
75960** such that the abort must occur after the multiwrite.  This makes
75961** some statements involving the REPLACE conflict resolution algorithm
75962** go a little faster.  But taking advantage of this time dependency
75963** makes it more difficult to prove that the code is correct (in
75964** particular, it prevents us from writing an effective
75965** implementation of sqlite3AssertMayAbort()) and so we have chosen
75966** to take the safe route and skip the optimization.
75967*/
75968SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
75969  Parse *pToplevel = sqlite3ParseToplevel(pParse);
75970  pToplevel->mayAbort = 1;
75971}
75972
75973/*
75974** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
75975** error. The onError parameter determines which (if any) of the statement
75976** and/or current transaction is rolled back.
75977*/
75978SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
75979  Vdbe *v = sqlite3GetVdbe(pParse);
75980  if( onError==OE_Abort ){
75981    sqlite3MayAbort(pParse);
75982  }
75983  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
75984}
75985
75986/*
75987** Check to see if pIndex uses the collating sequence pColl.  Return
75988** true if it does and false if it does not.
75989*/
75990#ifndef SQLITE_OMIT_REINDEX
75991static int collationMatch(const char *zColl, Index *pIndex){
75992  int i;
75993  assert( zColl!=0 );
75994  for(i=0; i<pIndex->nColumn; i++){
75995    const char *z = pIndex->azColl[i];
75996    assert( z!=0 );
75997    if( 0==sqlite3StrICmp(z, zColl) ){
75998      return 1;
75999    }
76000  }
76001  return 0;
76002}
76003#endif
76004
76005/*
76006** Recompute all indices of pTab that use the collating sequence pColl.
76007** If pColl==0 then recompute all indices of pTab.
76008*/
76009#ifndef SQLITE_OMIT_REINDEX
76010static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
76011  Index *pIndex;              /* An index associated with pTab */
76012
76013  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
76014    if( zColl==0 || collationMatch(zColl, pIndex) ){
76015      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76016      sqlite3BeginWriteOperation(pParse, 0, iDb);
76017      sqlite3RefillIndex(pParse, pIndex, -1);
76018    }
76019  }
76020}
76021#endif
76022
76023/*
76024** Recompute all indices of all tables in all databases where the
76025** indices use the collating sequence pColl.  If pColl==0 then recompute
76026** all indices everywhere.
76027*/
76028#ifndef SQLITE_OMIT_REINDEX
76029static void reindexDatabases(Parse *pParse, char const *zColl){
76030  Db *pDb;                    /* A single database */
76031  int iDb;                    /* The database index number */
76032  sqlite3 *db = pParse->db;   /* The database connection */
76033  HashElem *k;                /* For looping over tables in pDb */
76034  Table *pTab;                /* A table in the database */
76035
76036  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
76037    assert( pDb!=0 );
76038    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
76039      pTab = (Table*)sqliteHashData(k);
76040      reindexTable(pParse, pTab, zColl);
76041    }
76042  }
76043}
76044#endif
76045
76046/*
76047** Generate code for the REINDEX command.
76048**
76049**        REINDEX                            -- 1
76050**        REINDEX  <collation>               -- 2
76051**        REINDEX  ?<database>.?<tablename>  -- 3
76052**        REINDEX  ?<database>.?<indexname>  -- 4
76053**
76054** Form 1 causes all indices in all attached databases to be rebuilt.
76055** Form 2 rebuilds all indices in all databases that use the named
76056** collating function.  Forms 3 and 4 rebuild the named index or all
76057** indices associated with the named table.
76058*/
76059#ifndef SQLITE_OMIT_REINDEX
76060SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
76061  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
76062  char *z;                    /* Name of a table or index */
76063  const char *zDb;            /* Name of the database */
76064  Table *pTab;                /* A table in the database */
76065  Index *pIndex;              /* An index associated with pTab */
76066  int iDb;                    /* The database index number */
76067  sqlite3 *db = pParse->db;   /* The database connection */
76068  Token *pObjName;            /* Name of the table or index to be reindexed */
76069
76070  /* Read the database schema. If an error occurs, leave an error message
76071  ** and code in pParse and return NULL. */
76072  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76073    return;
76074  }
76075
76076  if( pName1==0 ){
76077    reindexDatabases(pParse, 0);
76078    return;
76079  }else if( NEVER(pName2==0) || pName2->z==0 ){
76080    char *zColl;
76081    assert( pName1->z );
76082    zColl = sqlite3NameFromToken(pParse->db, pName1);
76083    if( !zColl ) return;
76084    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
76085    if( pColl ){
76086      reindexDatabases(pParse, zColl);
76087      sqlite3DbFree(db, zColl);
76088      return;
76089    }
76090    sqlite3DbFree(db, zColl);
76091  }
76092  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
76093  if( iDb<0 ) return;
76094  z = sqlite3NameFromToken(db, pObjName);
76095  if( z==0 ) return;
76096  zDb = db->aDb[iDb].zName;
76097  pTab = sqlite3FindTable(db, z, zDb);
76098  if( pTab ){
76099    reindexTable(pParse, pTab, 0);
76100    sqlite3DbFree(db, z);
76101    return;
76102  }
76103  pIndex = sqlite3FindIndex(db, z, zDb);
76104  sqlite3DbFree(db, z);
76105  if( pIndex ){
76106    sqlite3BeginWriteOperation(pParse, 0, iDb);
76107    sqlite3RefillIndex(pParse, pIndex, -1);
76108    return;
76109  }
76110  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
76111}
76112#endif
76113
76114/*
76115** Return a dynamicly allocated KeyInfo structure that can be used
76116** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
76117**
76118** If successful, a pointer to the new structure is returned. In this case
76119** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
76120** pointer. If an error occurs (out of memory or missing collation
76121** sequence), NULL is returned and the state of pParse updated to reflect
76122** the error.
76123*/
76124SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
76125  int i;
76126  int nCol = pIdx->nColumn;
76127  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
76128  sqlite3 *db = pParse->db;
76129  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
76130
76131  if( pKey ){
76132    pKey->db = pParse->db;
76133    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
76134    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
76135    for(i=0; i<nCol; i++){
76136      char *zColl = pIdx->azColl[i];
76137      assert( zColl );
76138      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
76139      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
76140    }
76141    pKey->nField = (u16)nCol;
76142  }
76143
76144  if( pParse->nErr ){
76145    sqlite3DbFree(db, pKey);
76146    pKey = 0;
76147  }
76148  return pKey;
76149}
76150
76151/************** End of build.c ***********************************************/
76152/************** Begin file callback.c ****************************************/
76153/*
76154** 2005 May 23
76155**
76156** The author disclaims copyright to this source code.  In place of
76157** a legal notice, here is a blessing:
76158**
76159**    May you do good and not evil.
76160**    May you find forgiveness for yourself and forgive others.
76161**    May you share freely, never taking more than you give.
76162**
76163*************************************************************************
76164**
76165** This file contains functions used to access the internal hash tables
76166** of user defined functions and collation sequences.
76167*/
76168
76169
76170/*
76171** Invoke the 'collation needed' callback to request a collation sequence
76172** in the encoding enc of name zName, length nName.
76173*/
76174static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
76175  assert( !db->xCollNeeded || !db->xCollNeeded16 );
76176  if( db->xCollNeeded ){
76177    char *zExternal = sqlite3DbStrDup(db, zName);
76178    if( !zExternal ) return;
76179    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
76180    sqlite3DbFree(db, zExternal);
76181  }
76182#ifndef SQLITE_OMIT_UTF16
76183  if( db->xCollNeeded16 ){
76184    char const *zExternal;
76185    sqlite3_value *pTmp = sqlite3ValueNew(db);
76186    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
76187    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
76188    if( zExternal ){
76189      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
76190    }
76191    sqlite3ValueFree(pTmp);
76192  }
76193#endif
76194}
76195
76196/*
76197** This routine is called if the collation factory fails to deliver a
76198** collation function in the best encoding but there may be other versions
76199** of this collation function (for other text encodings) available. Use one
76200** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
76201** possible.
76202*/
76203static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
76204  CollSeq *pColl2;
76205  char *z = pColl->zName;
76206  int i;
76207  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
76208  for(i=0; i<3; i++){
76209    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
76210    if( pColl2->xCmp!=0 ){
76211      memcpy(pColl, pColl2, sizeof(CollSeq));
76212      pColl->xDel = 0;         /* Do not copy the destructor */
76213      return SQLITE_OK;
76214    }
76215  }
76216  return SQLITE_ERROR;
76217}
76218
76219/*
76220** This function is responsible for invoking the collation factory callback
76221** or substituting a collation sequence of a different encoding when the
76222** requested collation sequence is not available in the desired encoding.
76223**
76224** If it is not NULL, then pColl must point to the database native encoding
76225** collation sequence with name zName, length nName.
76226**
76227** The return value is either the collation sequence to be used in database
76228** db for collation type name zName, length nName, or NULL, if no collation
76229** sequence can be found.
76230**
76231** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
76232*/
76233SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
76234  sqlite3* db,          /* The database connection */
76235  u8 enc,               /* The desired encoding for the collating sequence */
76236  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
76237  const char *zName     /* Collating sequence name */
76238){
76239  CollSeq *p;
76240
76241  p = pColl;
76242  if( !p ){
76243    p = sqlite3FindCollSeq(db, enc, zName, 0);
76244  }
76245  if( !p || !p->xCmp ){
76246    /* No collation sequence of this type for this encoding is registered.
76247    ** Call the collation factory to see if it can supply us with one.
76248    */
76249    callCollNeeded(db, enc, zName);
76250    p = sqlite3FindCollSeq(db, enc, zName, 0);
76251  }
76252  if( p && !p->xCmp && synthCollSeq(db, p) ){
76253    p = 0;
76254  }
76255  assert( !p || p->xCmp );
76256  return p;
76257}
76258
76259/*
76260** This routine is called on a collation sequence before it is used to
76261** check that it is defined. An undefined collation sequence exists when
76262** a database is loaded that contains references to collation sequences
76263** that have not been defined by sqlite3_create_collation() etc.
76264**
76265** If required, this routine calls the 'collation needed' callback to
76266** request a definition of the collating sequence. If this doesn't work,
76267** an equivalent collating sequence that uses a text encoding different
76268** from the main database is substituted, if one is available.
76269*/
76270SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
76271  if( pColl ){
76272    const char *zName = pColl->zName;
76273    sqlite3 *db = pParse->db;
76274    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
76275    if( !p ){
76276      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
76277      pParse->nErr++;
76278      return SQLITE_ERROR;
76279    }
76280    assert( p==pColl );
76281  }
76282  return SQLITE_OK;
76283}
76284
76285
76286
76287/*
76288** Locate and return an entry from the db.aCollSeq hash table. If the entry
76289** specified by zName and nName is not found and parameter 'create' is
76290** true, then create a new entry. Otherwise return NULL.
76291**
76292** Each pointer stored in the sqlite3.aCollSeq hash table contains an
76293** array of three CollSeq structures. The first is the collation sequence
76294** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
76295**
76296** Stored immediately after the three collation sequences is a copy of
76297** the collation sequence name. A pointer to this string is stored in
76298** each collation sequence structure.
76299*/
76300static CollSeq *findCollSeqEntry(
76301  sqlite3 *db,          /* Database connection */
76302  const char *zName,    /* Name of the collating sequence */
76303  int create            /* Create a new entry if true */
76304){
76305  CollSeq *pColl;
76306  int nName = sqlite3Strlen30(zName);
76307  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
76308
76309  if( 0==pColl && create ){
76310    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
76311    if( pColl ){
76312      CollSeq *pDel = 0;
76313      pColl[0].zName = (char*)&pColl[3];
76314      pColl[0].enc = SQLITE_UTF8;
76315      pColl[1].zName = (char*)&pColl[3];
76316      pColl[1].enc = SQLITE_UTF16LE;
76317      pColl[2].zName = (char*)&pColl[3];
76318      pColl[2].enc = SQLITE_UTF16BE;
76319      memcpy(pColl[0].zName, zName, nName);
76320      pColl[0].zName[nName] = 0;
76321      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
76322
76323      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
76324      ** return the pColl pointer to be deleted (because it wasn't added
76325      ** to the hash table).
76326      */
76327      assert( pDel==0 || pDel==pColl );
76328      if( pDel!=0 ){
76329        db->mallocFailed = 1;
76330        sqlite3DbFree(db, pDel);
76331        pColl = 0;
76332      }
76333    }
76334  }
76335  return pColl;
76336}
76337
76338/*
76339** Parameter zName points to a UTF-8 encoded string nName bytes long.
76340** Return the CollSeq* pointer for the collation sequence named zName
76341** for the encoding 'enc' from the database 'db'.
76342**
76343** If the entry specified is not found and 'create' is true, then create a
76344** new entry.  Otherwise return NULL.
76345**
76346** A separate function sqlite3LocateCollSeq() is a wrapper around
76347** this routine.  sqlite3LocateCollSeq() invokes the collation factory
76348** if necessary and generates an error message if the collating sequence
76349** cannot be found.
76350**
76351** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
76352*/
76353SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
76354  sqlite3 *db,
76355  u8 enc,
76356  const char *zName,
76357  int create
76358){
76359  CollSeq *pColl;
76360  if( zName ){
76361    pColl = findCollSeqEntry(db, zName, create);
76362  }else{
76363    pColl = db->pDfltColl;
76364  }
76365  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
76366  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
76367  if( pColl ) pColl += enc-1;
76368  return pColl;
76369}
76370
76371/* During the search for the best function definition, this procedure
76372** is called to test how well the function passed as the first argument
76373** matches the request for a function with nArg arguments in a system
76374** that uses encoding enc. The value returned indicates how well the
76375** request is matched. A higher value indicates a better match.
76376**
76377** The returned value is always between 0 and 6, as follows:
76378**
76379** 0: Not a match, or if nArg<0 and the function is has no implementation.
76380** 1: A variable arguments function that prefers UTF-8 when a UTF-16
76381**    encoding is requested, or vice versa.
76382** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
76383**    requested, or vice versa.
76384** 3: A variable arguments function using the same text encoding.
76385** 4: A function with the exact number of arguments requested that
76386**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
76387** 5: A function with the exact number of arguments requested that
76388**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
76389** 6: An exact match.
76390**
76391*/
76392static int matchQuality(FuncDef *p, int nArg, u8 enc){
76393  int match = 0;
76394  if( p->nArg==-1 || p->nArg==nArg
76395   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
76396  ){
76397    match = 1;
76398    if( p->nArg==nArg || nArg==-1 ){
76399      match = 4;
76400    }
76401    if( enc==p->iPrefEnc ){
76402      match += 2;
76403    }
76404    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
76405             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
76406      match += 1;
76407    }
76408  }
76409  return match;
76410}
76411
76412/*
76413** Search a FuncDefHash for a function with the given name.  Return
76414** a pointer to the matching FuncDef if found, or 0 if there is no match.
76415*/
76416static FuncDef *functionSearch(
76417  FuncDefHash *pHash,  /* Hash table to search */
76418  int h,               /* Hash of the name */
76419  const char *zFunc,   /* Name of function */
76420  int nFunc            /* Number of bytes in zFunc */
76421){
76422  FuncDef *p;
76423  for(p=pHash->a[h]; p; p=p->pHash){
76424    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
76425      return p;
76426    }
76427  }
76428  return 0;
76429}
76430
76431/*
76432** Insert a new FuncDef into a FuncDefHash hash table.
76433*/
76434SQLITE_PRIVATE void sqlite3FuncDefInsert(
76435  FuncDefHash *pHash,  /* The hash table into which to insert */
76436  FuncDef *pDef        /* The function definition to insert */
76437){
76438  FuncDef *pOther;
76439  int nName = sqlite3Strlen30(pDef->zName);
76440  u8 c1 = (u8)pDef->zName[0];
76441  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
76442  pOther = functionSearch(pHash, h, pDef->zName, nName);
76443  if( pOther ){
76444    assert( pOther!=pDef && pOther->pNext!=pDef );
76445    pDef->pNext = pOther->pNext;
76446    pOther->pNext = pDef;
76447  }else{
76448    pDef->pNext = 0;
76449    pDef->pHash = pHash->a[h];
76450    pHash->a[h] = pDef;
76451  }
76452}
76453
76454
76455
76456/*
76457** Locate a user function given a name, a number of arguments and a flag
76458** indicating whether the function prefers UTF-16 over UTF-8.  Return a
76459** pointer to the FuncDef structure that defines that function, or return
76460** NULL if the function does not exist.
76461**
76462** If the createFlag argument is true, then a new (blank) FuncDef
76463** structure is created and liked into the "db" structure if a
76464** no matching function previously existed.  When createFlag is true
76465** and the nArg parameter is -1, then only a function that accepts
76466** any number of arguments will be returned.
76467**
76468** If createFlag is false and nArg is -1, then the first valid
76469** function found is returned.  A function is valid if either xFunc
76470** or xStep is non-zero.
76471**
76472** If createFlag is false, then a function with the required name and
76473** number of arguments may be returned even if the eTextRep flag does not
76474** match that requested.
76475*/
76476SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
76477  sqlite3 *db,       /* An open database */
76478  const char *zName, /* Name of the function.  Not null-terminated */
76479  int nName,         /* Number of characters in the name */
76480  int nArg,          /* Number of arguments.  -1 means any number */
76481  u8 enc,            /* Preferred text encoding */
76482  int createFlag     /* Create new entry if true and does not otherwise exist */
76483){
76484  FuncDef *p;         /* Iterator variable */
76485  FuncDef *pBest = 0; /* Best match found so far */
76486  int bestScore = 0;  /* Score of best match */
76487  int h;              /* Hash value */
76488
76489
76490  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
76491  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
76492
76493  /* First search for a match amongst the application-defined functions.
76494  */
76495  p = functionSearch(&db->aFunc, h, zName, nName);
76496  while( p ){
76497    int score = matchQuality(p, nArg, enc);
76498    if( score>bestScore ){
76499      pBest = p;
76500      bestScore = score;
76501    }
76502    p = p->pNext;
76503  }
76504
76505  /* If no match is found, search the built-in functions.
76506  **
76507  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
76508  ** functions even if a prior app-defined function was found.  And give
76509  ** priority to built-in functions.
76510  **
76511  ** Except, if createFlag is true, that means that we are trying to
76512  ** install a new function.  Whatever FuncDef structure is returned will
76513  ** have fields overwritten with new information appropriate for the
76514  ** new function.  But the FuncDefs for built-in functions are read-only.
76515  ** So we must not search for built-ins when creating a new function.
76516  */
76517  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
76518    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
76519    bestScore = 0;
76520    p = functionSearch(pHash, h, zName, nName);
76521    while( p ){
76522      int score = matchQuality(p, nArg, enc);
76523      if( score>bestScore ){
76524        pBest = p;
76525        bestScore = score;
76526      }
76527      p = p->pNext;
76528    }
76529  }
76530
76531  /* If the createFlag parameter is true and the search did not reveal an
76532  ** exact match for the name, number of arguments and encoding, then add a
76533  ** new entry to the hash table and return it.
76534  */
76535  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
76536      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
76537    pBest->zName = (char *)&pBest[1];
76538    pBest->nArg = (u16)nArg;
76539    pBest->iPrefEnc = enc;
76540    memcpy(pBest->zName, zName, nName);
76541    pBest->zName[nName] = 0;
76542    sqlite3FuncDefInsert(&db->aFunc, pBest);
76543  }
76544
76545  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
76546    return pBest;
76547  }
76548  return 0;
76549}
76550
76551/*
76552** Free all resources held by the schema structure. The void* argument points
76553** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
76554** pointer itself, it just cleans up subsiduary resources (i.e. the contents
76555** of the schema hash tables).
76556**
76557** The Schema.cache_size variable is not cleared.
76558*/
76559SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
76560  Hash temp1;
76561  Hash temp2;
76562  HashElem *pElem;
76563  Schema *pSchema = (Schema *)p;
76564
76565  temp1 = pSchema->tblHash;
76566  temp2 = pSchema->trigHash;
76567  sqlite3HashInit(&pSchema->trigHash);
76568  sqlite3HashClear(&pSchema->idxHash);
76569  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
76570    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
76571  }
76572  sqlite3HashClear(&temp2);
76573  sqlite3HashInit(&pSchema->tblHash);
76574  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
76575    Table *pTab = sqliteHashData(pElem);
76576    assert( pTab->dbMem==0 );
76577    sqlite3DeleteTable(pTab);
76578  }
76579  sqlite3HashClear(&temp1);
76580  sqlite3HashClear(&pSchema->fkeyHash);
76581  pSchema->pSeqTab = 0;
76582  pSchema->flags &= ~DB_SchemaLoaded;
76583}
76584
76585/*
76586** Find and return the schema associated with a BTree.  Create
76587** a new one if necessary.
76588*/
76589SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
76590  Schema * p;
76591  if( pBt ){
76592    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
76593  }else{
76594    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
76595  }
76596  if( !p ){
76597    db->mallocFailed = 1;
76598  }else if ( 0==p->file_format ){
76599    sqlite3HashInit(&p->tblHash);
76600    sqlite3HashInit(&p->idxHash);
76601    sqlite3HashInit(&p->trigHash);
76602    sqlite3HashInit(&p->fkeyHash);
76603    p->enc = SQLITE_UTF8;
76604  }
76605  return p;
76606}
76607
76608/************** End of callback.c ********************************************/
76609/************** Begin file delete.c ******************************************/
76610/*
76611** 2001 September 15
76612**
76613** The author disclaims copyright to this source code.  In place of
76614** a legal notice, here is a blessing:
76615**
76616**    May you do good and not evil.
76617**    May you find forgiveness for yourself and forgive others.
76618**    May you share freely, never taking more than you give.
76619**
76620*************************************************************************
76621** This file contains C code routines that are called by the parser
76622** in order to generate code for DELETE FROM statements.
76623*/
76624
76625/*
76626** Look up every table that is named in pSrc.  If any table is not found,
76627** add an error message to pParse->zErrMsg and return NULL.  If all tables
76628** are found, return a pointer to the last table.
76629*/
76630SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
76631  struct SrcList_item *pItem = pSrc->a;
76632  Table *pTab;
76633  assert( pItem && pSrc->nSrc==1 );
76634  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
76635  sqlite3DeleteTable(pItem->pTab);
76636  pItem->pTab = pTab;
76637  if( pTab ){
76638    pTab->nRef++;
76639  }
76640  if( sqlite3IndexedByLookup(pParse, pItem) ){
76641    pTab = 0;
76642  }
76643  return pTab;
76644}
76645
76646/*
76647** Check to make sure the given table is writable.  If it is not
76648** writable, generate an error message and return 1.  If it is
76649** writable return 0;
76650*/
76651SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
76652  /* A table is not writable under the following circumstances:
76653  **
76654  **   1) It is a virtual table and no implementation of the xUpdate method
76655  **      has been provided, or
76656  **   2) It is a system table (i.e. sqlite_master), this call is not
76657  **      part of a nested parse and writable_schema pragma has not
76658  **      been specified.
76659  **
76660  ** In either case leave an error message in pParse and return non-zero.
76661  */
76662  if( ( IsVirtual(pTab)
76663     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
76664   || ( (pTab->tabFlags & TF_Readonly)!=0
76665     && (pParse->db->flags & SQLITE_WriteSchema)==0
76666     && pParse->nested==0 )
76667  ){
76668    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
76669    return 1;
76670  }
76671
76672#ifndef SQLITE_OMIT_VIEW
76673  if( !viewOk && pTab->pSelect ){
76674    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
76675    return 1;
76676  }
76677#endif
76678  return 0;
76679}
76680
76681
76682#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
76683/*
76684** Evaluate a view and store its result in an ephemeral table.  The
76685** pWhere argument is an optional WHERE clause that restricts the
76686** set of rows in the view that are to be added to the ephemeral table.
76687*/
76688SQLITE_PRIVATE void sqlite3MaterializeView(
76689  Parse *pParse,       /* Parsing context */
76690  Table *pView,        /* View definition */
76691  Expr *pWhere,        /* Optional WHERE clause to be added */
76692  int iCur             /* Cursor number for ephemerial table */
76693){
76694  SelectDest dest;
76695  Select *pDup;
76696  sqlite3 *db = pParse->db;
76697
76698  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
76699  if( pWhere ){
76700    SrcList *pFrom;
76701
76702    pWhere = sqlite3ExprDup(db, pWhere, 0);
76703    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
76704    if( pFrom ){
76705      assert( pFrom->nSrc==1 );
76706      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
76707      pFrom->a[0].pSelect = pDup;
76708      assert( pFrom->a[0].pOn==0 );
76709      assert( pFrom->a[0].pUsing==0 );
76710    }else{
76711      sqlite3SelectDelete(db, pDup);
76712    }
76713    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
76714  }
76715  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
76716  sqlite3Select(pParse, pDup, &dest);
76717  sqlite3SelectDelete(db, pDup);
76718}
76719#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
76720
76721#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
76722/*
76723** Generate an expression tree to implement the WHERE, ORDER BY,
76724** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
76725**
76726**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
76727**                            \__________________________/
76728**                               pLimitWhere (pInClause)
76729*/
76730SQLITE_PRIVATE Expr *sqlite3LimitWhere(
76731  Parse *pParse,               /* The parser context */
76732  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
76733  Expr *pWhere,                /* The WHERE clause.  May be null */
76734  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
76735  Expr *pLimit,                /* The LIMIT clause.  May be null */
76736  Expr *pOffset,               /* The OFFSET clause.  May be null */
76737  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
76738){
76739  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
76740  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
76741  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
76742  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
76743  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
76744  Select *pSelect = NULL;      /* Complete SELECT tree */
76745
76746  /* Check that there isn't an ORDER BY without a LIMIT clause.
76747  */
76748  if( pOrderBy && (pLimit == 0) ) {
76749    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
76750    pParse->parseError = 1;
76751    goto limit_where_cleanup_2;
76752  }
76753
76754  /* We only need to generate a select expression if there
76755  ** is a limit/offset term to enforce.
76756  */
76757  if( pLimit == 0 ) {
76758    /* if pLimit is null, pOffset will always be null as well. */
76759    assert( pOffset == 0 );
76760    return pWhere;
76761  }
76762
76763  /* Generate a select expression tree to enforce the limit/offset
76764  ** term for the DELETE or UPDATE statement.  For example:
76765  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
76766  ** becomes:
76767  **   DELETE FROM table_a WHERE rowid IN (
76768  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
76769  **   );
76770  */
76771
76772  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
76773  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
76774  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
76775  if( pEList == 0 ) goto limit_where_cleanup_2;
76776
76777  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
76778  ** and the SELECT subtree. */
76779  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
76780  if( pSelectSrc == 0 ) {
76781    sqlite3ExprListDelete(pParse->db, pEList);
76782    goto limit_where_cleanup_2;
76783  }
76784
76785  /* generate the SELECT expression tree. */
76786  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
76787                             pOrderBy,0,pLimit,pOffset);
76788  if( pSelect == 0 ) return 0;
76789
76790  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
76791  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
76792  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
76793  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
76794  if( pInClause == 0 ) goto limit_where_cleanup_1;
76795
76796  pInClause->x.pSelect = pSelect;
76797  pInClause->flags |= EP_xIsSelect;
76798  sqlite3ExprSetHeight(pParse, pInClause);
76799  return pInClause;
76800
76801  /* something went wrong. clean up anything allocated. */
76802limit_where_cleanup_1:
76803  sqlite3SelectDelete(pParse->db, pSelect);
76804  return 0;
76805
76806limit_where_cleanup_2:
76807  sqlite3ExprDelete(pParse->db, pWhere);
76808  sqlite3ExprListDelete(pParse->db, pOrderBy);
76809  sqlite3ExprDelete(pParse->db, pLimit);
76810  sqlite3ExprDelete(pParse->db, pOffset);
76811  return 0;
76812}
76813#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
76814
76815/*
76816** Generate code for a DELETE FROM statement.
76817**
76818**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
76819**                 \________/       \________________/
76820**                  pTabList              pWhere
76821*/
76822SQLITE_PRIVATE void sqlite3DeleteFrom(
76823  Parse *pParse,         /* The parser context */
76824  SrcList *pTabList,     /* The table from which we should delete things */
76825  Expr *pWhere           /* The WHERE clause.  May be null */
76826){
76827  Vdbe *v;               /* The virtual database engine */
76828  Table *pTab;           /* The table from which records will be deleted */
76829  const char *zDb;       /* Name of database holding pTab */
76830  int end, addr = 0;     /* A couple addresses of generated code */
76831  int i;                 /* Loop counter */
76832  WhereInfo *pWInfo;     /* Information about the WHERE clause */
76833  Index *pIdx;           /* For looping over indices of the table */
76834  int iCur;              /* VDBE Cursor number for pTab */
76835  sqlite3 *db;           /* Main database structure */
76836  AuthContext sContext;  /* Authorization context */
76837  NameContext sNC;       /* Name context to resolve expressions in */
76838  int iDb;               /* Database number */
76839  int memCnt = -1;       /* Memory cell used for change counting */
76840  int rcauth;            /* Value returned by authorization callback */
76841
76842#ifndef SQLITE_OMIT_TRIGGER
76843  int isView;                  /* True if attempting to delete from a view */
76844  Trigger *pTrigger;           /* List of table triggers, if required */
76845#endif
76846
76847  memset(&sContext, 0, sizeof(sContext));
76848  db = pParse->db;
76849  if( pParse->nErr || db->mallocFailed ){
76850    goto delete_from_cleanup;
76851  }
76852  assert( pTabList->nSrc==1 );
76853
76854  /* Locate the table which we want to delete.  This table has to be
76855  ** put in an SrcList structure because some of the subroutines we
76856  ** will be calling are designed to work with multiple tables and expect
76857  ** an SrcList* parameter instead of just a Table* parameter.
76858  */
76859  pTab = sqlite3SrcListLookup(pParse, pTabList);
76860  if( pTab==0 )  goto delete_from_cleanup;
76861
76862  /* Figure out if we have any triggers and if the table being
76863  ** deleted from is a view
76864  */
76865#ifndef SQLITE_OMIT_TRIGGER
76866  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
76867  isView = pTab->pSelect!=0;
76868#else
76869# define pTrigger 0
76870# define isView 0
76871#endif
76872#ifdef SQLITE_OMIT_VIEW
76873# undef isView
76874# define isView 0
76875#endif
76876
76877  /* If pTab is really a view, make sure it has been initialized.
76878  */
76879  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
76880    goto delete_from_cleanup;
76881  }
76882
76883  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
76884    goto delete_from_cleanup;
76885  }
76886  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76887  assert( iDb<db->nDb );
76888  zDb = db->aDb[iDb].zName;
76889  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
76890  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
76891  if( rcauth==SQLITE_DENY ){
76892    goto delete_from_cleanup;
76893  }
76894  assert(!isView || pTrigger);
76895
76896  /* Assign  cursor number to the table and all its indices.
76897  */
76898  assert( pTabList->nSrc==1 );
76899  iCur = pTabList->a[0].iCursor = pParse->nTab++;
76900  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76901    pParse->nTab++;
76902  }
76903
76904  /* Start the view context
76905  */
76906  if( isView ){
76907    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
76908  }
76909
76910  /* Begin generating code.
76911  */
76912  v = sqlite3GetVdbe(pParse);
76913  if( v==0 ){
76914    goto delete_from_cleanup;
76915  }
76916  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
76917  sqlite3BeginWriteOperation(pParse, 1, iDb);
76918
76919  /* If we are trying to delete from a view, realize that view into
76920  ** a ephemeral table.
76921  */
76922#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
76923  if( isView ){
76924    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
76925  }
76926#endif
76927
76928  /* Resolve the column names in the WHERE clause.
76929  */
76930  memset(&sNC, 0, sizeof(sNC));
76931  sNC.pParse = pParse;
76932  sNC.pSrcList = pTabList;
76933  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
76934    goto delete_from_cleanup;
76935  }
76936
76937  /* Initialize the counter of the number of rows deleted, if
76938  ** we are counting rows.
76939  */
76940  if( db->flags & SQLITE_CountRows ){
76941    memCnt = ++pParse->nMem;
76942    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
76943  }
76944
76945#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
76946  /* Special case: A DELETE without a WHERE clause deletes everything.
76947  ** It is easier just to erase the whole table. Prior to version 3.6.5,
76948  ** this optimization caused the row change count (the value returned by
76949  ** API function sqlite3_count_changes) to be set incorrectly.  */
76950  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
76951   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
76952  ){
76953    assert( !isView );
76954    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
76955                      pTab->zName, P4_STATIC);
76956    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76957      assert( pIdx->pSchema==pTab->pSchema );
76958      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
76959    }
76960  }else
76961#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
76962  /* The usual case: There is a WHERE clause so we have to scan through
76963  ** the table and pick which records to delete.
76964  */
76965  {
76966    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
76967    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
76968    int regRowid;                   /* Actual register containing rowids */
76969
76970    /* Collect rowids of every row to be deleted.
76971    */
76972    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
76973    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
76974    if( pWInfo==0 ) goto delete_from_cleanup;
76975    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
76976    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
76977    if( db->flags & SQLITE_CountRows ){
76978      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
76979    }
76980    sqlite3WhereEnd(pWInfo);
76981
76982    /* Delete every item whose key was written to the list during the
76983    ** database scan.  We have to delete items after the scan is complete
76984    ** because deleting an item can change the scan order.  */
76985    end = sqlite3VdbeMakeLabel(v);
76986
76987    /* Unless this is a view, open cursors for the table we are
76988    ** deleting from and all its indices. If this is a view, then the
76989    ** only effect this statement has is to fire the INSTEAD OF
76990    ** triggers.  */
76991    if( !isView ){
76992      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
76993    }
76994
76995    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
76996
76997    /* Delete the row */
76998#ifndef SQLITE_OMIT_VIRTUALTABLE
76999    if( IsVirtual(pTab) ){
77000      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
77001      sqlite3VtabMakeWritable(pParse, pTab);
77002      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
77003      sqlite3MayAbort(pParse);
77004    }else
77005#endif
77006    {
77007      int count = (pParse->nested==0);    /* True to count changes */
77008      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
77009    }
77010
77011    /* End of the delete loop */
77012    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
77013    sqlite3VdbeResolveLabel(v, end);
77014
77015    /* Close the cursors open on the table and its indexes. */
77016    if( !isView && !IsVirtual(pTab) ){
77017      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77018        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
77019      }
77020      sqlite3VdbeAddOp1(v, OP_Close, iCur);
77021    }
77022  }
77023
77024  /* Update the sqlite_sequence table by storing the content of the
77025  ** maximum rowid counter values recorded while inserting into
77026  ** autoincrement tables.
77027  */
77028  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
77029    sqlite3AutoincrementEnd(pParse);
77030  }
77031
77032  /* Return the number of rows that were deleted. If this routine is
77033  ** generating code because of a call to sqlite3NestedParse(), do not
77034  ** invoke the callback function.
77035  */
77036  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
77037    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
77038    sqlite3VdbeSetNumCols(v, 1);
77039    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
77040  }
77041
77042delete_from_cleanup:
77043  sqlite3AuthContextPop(&sContext);
77044  sqlite3SrcListDelete(db, pTabList);
77045  sqlite3ExprDelete(db, pWhere);
77046  return;
77047}
77048/* Make sure "isView" and other macros defined above are undefined. Otherwise
77049** thely may interfere with compilation of other functions in this file
77050** (or in another file, if this file becomes part of the amalgamation).  */
77051#ifdef isView
77052 #undef isView
77053#endif
77054#ifdef pTrigger
77055 #undef pTrigger
77056#endif
77057
77058/*
77059** This routine generates VDBE code that causes a single row of a
77060** single table to be deleted.
77061**
77062** The VDBE must be in a particular state when this routine is called.
77063** These are the requirements:
77064**
77065**   1.  A read/write cursor pointing to pTab, the table containing the row
77066**       to be deleted, must be opened as cursor number $iCur.
77067**
77068**   2.  Read/write cursors for all indices of pTab must be open as
77069**       cursor number base+i for the i-th index.
77070**
77071**   3.  The record number of the row to be deleted must be stored in
77072**       memory cell iRowid.
77073**
77074** This routine generates code to remove both the table record and all
77075** index entries that point to that record.
77076*/
77077SQLITE_PRIVATE void sqlite3GenerateRowDelete(
77078  Parse *pParse,     /* Parsing context */
77079  Table *pTab,       /* Table containing the row to be deleted */
77080  int iCur,          /* Cursor number for the table */
77081  int iRowid,        /* Memory cell that contains the rowid to delete */
77082  int count,         /* If non-zero, increment the row change counter */
77083  Trigger *pTrigger, /* List of triggers to (potentially) fire */
77084  int onconf         /* Default ON CONFLICT policy for triggers */
77085){
77086  Vdbe *v = pParse->pVdbe;        /* Vdbe */
77087  int iOld = 0;                   /* First register in OLD.* array */
77088  int iLabel;                     /* Label resolved to end of generated code */
77089
77090  /* Vdbe is guaranteed to have been allocated by this stage. */
77091  assert( v );
77092
77093  /* Seek cursor iCur to the row to delete. If this row no longer exists
77094  ** (this can happen if a trigger program has already deleted it), do
77095  ** not attempt to delete it or fire any DELETE triggers.  */
77096  iLabel = sqlite3VdbeMakeLabel(v);
77097  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77098
77099  /* If there are any triggers to fire, allocate a range of registers to
77100  ** use for the old.* references in the triggers.  */
77101  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
77102    u32 mask;                     /* Mask of OLD.* columns in use */
77103    int iCol;                     /* Iterator used while populating OLD.* */
77104
77105    /* TODO: Could use temporary registers here. Also could attempt to
77106    ** avoid copying the contents of the rowid register.  */
77107    mask = sqlite3TriggerColmask(
77108        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
77109    );
77110    mask |= sqlite3FkOldmask(pParse, pTab);
77111    iOld = pParse->nMem+1;
77112    pParse->nMem += (1 + pTab->nCol);
77113
77114    /* Populate the OLD.* pseudo-table register array. These values will be
77115    ** used by any BEFORE and AFTER triggers that exist.  */
77116    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
77117    for(iCol=0; iCol<pTab->nCol; iCol++){
77118      if( mask==0xffffffff || mask&(1<<iCol) ){
77119        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
77120      }
77121    }
77122
77123    /* Invoke BEFORE DELETE trigger programs. */
77124    sqlite3CodeRowTrigger(pParse, pTrigger,
77125        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
77126    );
77127
77128    /* Seek the cursor to the row to be deleted again. It may be that
77129    ** the BEFORE triggers coded above have already removed the row
77130    ** being deleted. Do not attempt to delete the row a second time, and
77131    ** do not fire AFTER triggers.  */
77132    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77133
77134    /* Do FK processing. This call checks that any FK constraints that
77135    ** refer to this table (i.e. constraints attached to other tables)
77136    ** are not violated by deleting this row.  */
77137    sqlite3FkCheck(pParse, pTab, iOld, 0);
77138  }
77139
77140  /* Delete the index and table entries. Skip this step if pTab is really
77141  ** a view (in which case the only effect of the DELETE statement is to
77142  ** fire the INSTEAD OF triggers).  */
77143  if( pTab->pSelect==0 ){
77144    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
77145    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
77146    if( count ){
77147      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
77148    }
77149  }
77150
77151  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
77152  ** handle rows (possibly in other tables) that refer via a foreign key
77153  ** to the row just deleted. */
77154  sqlite3FkActions(pParse, pTab, 0, iOld);
77155
77156  /* Invoke AFTER DELETE trigger programs. */
77157  sqlite3CodeRowTrigger(pParse, pTrigger,
77158      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
77159  );
77160
77161  /* Jump here if the row had already been deleted before any BEFORE
77162  ** trigger programs were invoked. Or if a trigger program throws a
77163  ** RAISE(IGNORE) exception.  */
77164  sqlite3VdbeResolveLabel(v, iLabel);
77165}
77166
77167/*
77168** This routine generates VDBE code that causes the deletion of all
77169** index entries associated with a single row of a single table.
77170**
77171** The VDBE must be in a particular state when this routine is called.
77172** These are the requirements:
77173**
77174**   1.  A read/write cursor pointing to pTab, the table containing the row
77175**       to be deleted, must be opened as cursor number "iCur".
77176**
77177**   2.  Read/write cursors for all indices of pTab must be open as
77178**       cursor number iCur+i for the i-th index.
77179**
77180**   3.  The "iCur" cursor must be pointing to the row that is to be
77181**       deleted.
77182*/
77183SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
77184  Parse *pParse,     /* Parsing and code generating context */
77185  Table *pTab,       /* Table containing the row to be deleted */
77186  int iCur,          /* Cursor number for the table */
77187  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
77188){
77189  int i;
77190  Index *pIdx;
77191  int r1;
77192
77193  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77194    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
77195    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
77196    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
77197  }
77198}
77199
77200/*
77201** Generate code that will assemble an index key and put it in register
77202** regOut.  The key with be for index pIdx which is an index on pTab.
77203** iCur is the index of a cursor open on the pTab table and pointing to
77204** the entry that needs indexing.
77205**
77206** Return a register number which is the first in a block of
77207** registers that holds the elements of the index key.  The
77208** block of registers has already been deallocated by the time
77209** this routine returns.
77210*/
77211SQLITE_PRIVATE int sqlite3GenerateIndexKey(
77212  Parse *pParse,     /* Parsing context */
77213  Index *pIdx,       /* The index for which to generate a key */
77214  int iCur,          /* Cursor number for the pIdx->pTable table */
77215  int regOut,        /* Write the new index key to this register */
77216  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
77217){
77218  Vdbe *v = pParse->pVdbe;
77219  int j;
77220  Table *pTab = pIdx->pTable;
77221  int regBase;
77222  int nCol;
77223
77224  nCol = pIdx->nColumn;
77225  regBase = sqlite3GetTempRange(pParse, nCol+1);
77226  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
77227  for(j=0; j<nCol; j++){
77228    int idx = pIdx->aiColumn[j];
77229    if( idx==pTab->iPKey ){
77230      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
77231    }else{
77232      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
77233      sqlite3ColumnDefault(v, pTab, idx, -1);
77234    }
77235  }
77236  if( doMakeRec ){
77237    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
77238    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
77239  }
77240  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
77241  return regBase;
77242}
77243
77244/************** End of delete.c **********************************************/
77245/************** Begin file func.c ********************************************/
77246/*
77247** 2002 February 23
77248**
77249** The author disclaims copyright to this source code.  In place of
77250** a legal notice, here is a blessing:
77251**
77252**    May you do good and not evil.
77253**    May you find forgiveness for yourself and forgive others.
77254**    May you share freely, never taking more than you give.
77255**
77256*************************************************************************
77257** This file contains the C functions that implement various SQL
77258** functions of SQLite.
77259**
77260** There is only one exported symbol in this file - the function
77261** sqliteRegisterBuildinFunctions() found at the bottom of the file.
77262** All other code has file scope.
77263*/
77264
77265/*
77266** Return the collating function associated with a function.
77267*/
77268static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
77269  return context->pColl;
77270}
77271
77272/*
77273** Implementation of the non-aggregate min() and max() functions
77274*/
77275static void minmaxFunc(
77276  sqlite3_context *context,
77277  int argc,
77278  sqlite3_value **argv
77279){
77280  int i;
77281  int mask;    /* 0 for min() or 0xffffffff for max() */
77282  int iBest;
77283  CollSeq *pColl;
77284
77285  assert( argc>1 );
77286  mask = sqlite3_user_data(context)==0 ? 0 : -1;
77287  pColl = sqlite3GetFuncCollSeq(context);
77288  assert( pColl );
77289  assert( mask==-1 || mask==0 );
77290  iBest = 0;
77291  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77292  for(i=1; i<argc; i++){
77293    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
77294    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
77295      testcase( mask==0 );
77296      iBest = i;
77297    }
77298  }
77299  sqlite3_result_value(context, argv[iBest]);
77300}
77301
77302/*
77303** Return the type of the argument.
77304*/
77305static void typeofFunc(
77306  sqlite3_context *context,
77307  int NotUsed,
77308  sqlite3_value **argv
77309){
77310  const char *z = 0;
77311  UNUSED_PARAMETER(NotUsed);
77312  switch( sqlite3_value_type(argv[0]) ){
77313    case SQLITE_INTEGER: z = "integer"; break;
77314    case SQLITE_TEXT:    z = "text";    break;
77315    case SQLITE_FLOAT:   z = "real";    break;
77316    case SQLITE_BLOB:    z = "blob";    break;
77317    default:             z = "null";    break;
77318  }
77319  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
77320}
77321
77322
77323/*
77324** Implementation of the length() function
77325*/
77326static void lengthFunc(
77327  sqlite3_context *context,
77328  int argc,
77329  sqlite3_value **argv
77330){
77331  int len;
77332
77333  assert( argc==1 );
77334  UNUSED_PARAMETER(argc);
77335  switch( sqlite3_value_type(argv[0]) ){
77336    case SQLITE_BLOB:
77337    case SQLITE_INTEGER:
77338    case SQLITE_FLOAT: {
77339      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
77340      break;
77341    }
77342    case SQLITE_TEXT: {
77343      const unsigned char *z = sqlite3_value_text(argv[0]);
77344      if( z==0 ) return;
77345      len = 0;
77346      while( *z ){
77347        len++;
77348        SQLITE_SKIP_UTF8(z);
77349      }
77350      sqlite3_result_int(context, len);
77351      break;
77352    }
77353    default: {
77354      sqlite3_result_null(context);
77355      break;
77356    }
77357  }
77358}
77359
77360/*
77361** Implementation of the abs() function.
77362**
77363** IMP: R-23979-26855 The abs(X) function returns the absolute value of
77364** the numeric argument X.
77365*/
77366static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77367  assert( argc==1 );
77368  UNUSED_PARAMETER(argc);
77369  switch( sqlite3_value_type(argv[0]) ){
77370    case SQLITE_INTEGER: {
77371      i64 iVal = sqlite3_value_int64(argv[0]);
77372      if( iVal<0 ){
77373        if( (iVal<<1)==0 ){
77374          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
77375          ** abs(X) throws an integer overflow error since there is no
77376          ** equivalent positive 64-bit two complement value. */
77377          sqlite3_result_error(context, "integer overflow", -1);
77378          return;
77379        }
77380        iVal = -iVal;
77381      }
77382      sqlite3_result_int64(context, iVal);
77383      break;
77384    }
77385    case SQLITE_NULL: {
77386      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
77387      sqlite3_result_null(context);
77388      break;
77389    }
77390    default: {
77391      /* Because sqlite3_value_double() returns 0.0 if the argument is not
77392      ** something that can be converted into a number, we have:
77393      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
77394      ** cannot be converted to a numeric value.
77395      */
77396      double rVal = sqlite3_value_double(argv[0]);
77397      if( rVal<0 ) rVal = -rVal;
77398      sqlite3_result_double(context, rVal);
77399      break;
77400    }
77401  }
77402}
77403
77404/*
77405** Implementation of the substr() function.
77406**
77407** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
77408** p1 is 1-indexed.  So substr(x,1,1) returns the first character
77409** of x.  If x is text, then we actually count UTF-8 characters.
77410** If x is a blob, then we count bytes.
77411**
77412** If p1 is negative, then we begin abs(p1) from the end of x[].
77413**
77414** If p2 is negative, return the p2 characters preceeding p1.
77415*/
77416static void substrFunc(
77417  sqlite3_context *context,
77418  int argc,
77419  sqlite3_value **argv
77420){
77421  const unsigned char *z;
77422  const unsigned char *z2;
77423  int len;
77424  int p0type;
77425  i64 p1, p2;
77426  int negP2 = 0;
77427
77428  assert( argc==3 || argc==2 );
77429  if( sqlite3_value_type(argv[1])==SQLITE_NULL
77430   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
77431  ){
77432    return;
77433  }
77434  p0type = sqlite3_value_type(argv[0]);
77435  p1 = sqlite3_value_int(argv[1]);
77436  if( p0type==SQLITE_BLOB ){
77437    len = sqlite3_value_bytes(argv[0]);
77438    z = sqlite3_value_blob(argv[0]);
77439    if( z==0 ) return;
77440    assert( len==sqlite3_value_bytes(argv[0]) );
77441  }else{
77442    z = sqlite3_value_text(argv[0]);
77443    if( z==0 ) return;
77444    len = 0;
77445    if( p1<0 ){
77446      for(z2=z; *z2; len++){
77447        SQLITE_SKIP_UTF8(z2);
77448      }
77449    }
77450  }
77451  if( argc==3 ){
77452    p2 = sqlite3_value_int(argv[2]);
77453    if( p2<0 ){
77454      p2 = -p2;
77455      negP2 = 1;
77456    }
77457  }else{
77458    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
77459  }
77460  if( p1<0 ){
77461    p1 += len;
77462    if( p1<0 ){
77463      p2 += p1;
77464      if( p2<0 ) p2 = 0;
77465      p1 = 0;
77466    }
77467  }else if( p1>0 ){
77468    p1--;
77469  }else if( p2>0 ){
77470    p2--;
77471  }
77472  if( negP2 ){
77473    p1 -= p2;
77474    if( p1<0 ){
77475      p2 += p1;
77476      p1 = 0;
77477    }
77478  }
77479  assert( p1>=0 && p2>=0 );
77480  if( p0type!=SQLITE_BLOB ){
77481    while( *z && p1 ){
77482      SQLITE_SKIP_UTF8(z);
77483      p1--;
77484    }
77485    for(z2=z; *z2 && p2; p2--){
77486      SQLITE_SKIP_UTF8(z2);
77487    }
77488    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
77489  }else{
77490    if( p1+p2>len ){
77491      p2 = len-p1;
77492      if( p2<0 ) p2 = 0;
77493    }
77494    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
77495  }
77496}
77497
77498/*
77499** Implementation of the round() function
77500*/
77501#ifndef SQLITE_OMIT_FLOATING_POINT
77502static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77503  int n = 0;
77504  double r;
77505  char *zBuf;
77506  assert( argc==1 || argc==2 );
77507  if( argc==2 ){
77508    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
77509    n = sqlite3_value_int(argv[1]);
77510    if( n>30 ) n = 30;
77511    if( n<0 ) n = 0;
77512  }
77513  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77514  r = sqlite3_value_double(argv[0]);
77515  /* If Y==0 and X will fit in a 64-bit int,
77516  ** handle the rounding directly,
77517  ** otherwise use printf.
77518  */
77519  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
77520    r = (double)((sqlite_int64)(r+0.5));
77521  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
77522    r = -(double)((sqlite_int64)((-r)+0.5));
77523  }else{
77524    zBuf = sqlite3_mprintf("%.*f",n,r);
77525    if( zBuf==0 ){
77526      sqlite3_result_error_nomem(context);
77527      return;
77528    }
77529    sqlite3AtoF(zBuf, &r);
77530    sqlite3_free(zBuf);
77531  }
77532  sqlite3_result_double(context, r);
77533}
77534#endif
77535
77536/*
77537** Allocate nByte bytes of space using sqlite3_malloc(). If the
77538** allocation fails, call sqlite3_result_error_nomem() to notify
77539** the database handle that malloc() has failed and return NULL.
77540** If nByte is larger than the maximum string or blob length, then
77541** raise an SQLITE_TOOBIG exception and return NULL.
77542*/
77543static void *contextMalloc(sqlite3_context *context, i64 nByte){
77544  char *z;
77545  sqlite3 *db = sqlite3_context_db_handle(context);
77546  assert( nByte>0 );
77547  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
77548  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
77549  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77550    sqlite3_result_error_toobig(context);
77551    z = 0;
77552  }else{
77553    z = sqlite3Malloc((int)nByte);
77554    if( !z ){
77555      sqlite3_result_error_nomem(context);
77556    }
77557  }
77558  return z;
77559}
77560
77561/*
77562** Implementation of the upper() and lower() SQL functions.
77563*/
77564static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77565  char *z1;
77566  const char *z2;
77567  int i, n;
77568  UNUSED_PARAMETER(argc);
77569  z2 = (char*)sqlite3_value_text(argv[0]);
77570  n = sqlite3_value_bytes(argv[0]);
77571  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77572  assert( z2==(char*)sqlite3_value_text(argv[0]) );
77573  if( z2 ){
77574    z1 = contextMalloc(context, ((i64)n)+1);
77575    if( z1 ){
77576      memcpy(z1, z2, n+1);
77577      for(i=0; z1[i]; i++){
77578        z1[i] = (char)sqlite3Toupper(z1[i]);
77579      }
77580      sqlite3_result_text(context, z1, -1, sqlite3_free);
77581    }
77582  }
77583}
77584static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77585  u8 *z1;
77586  const char *z2;
77587  int i, n;
77588  UNUSED_PARAMETER(argc);
77589  z2 = (char*)sqlite3_value_text(argv[0]);
77590  n = sqlite3_value_bytes(argv[0]);
77591  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77592  assert( z2==(char*)sqlite3_value_text(argv[0]) );
77593  if( z2 ){
77594    z1 = contextMalloc(context, ((i64)n)+1);
77595    if( z1 ){
77596      memcpy(z1, z2, n+1);
77597      for(i=0; z1[i]; i++){
77598        z1[i] = sqlite3Tolower(z1[i]);
77599      }
77600      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
77601    }
77602  }
77603}
77604
77605
77606#if 0  /* This function is never used. */
77607/*
77608** The COALESCE() and IFNULL() functions used to be implemented as shown
77609** here.  But now they are implemented as VDBE code so that unused arguments
77610** do not have to be computed.  This legacy implementation is retained as
77611** comment.
77612*/
77613/*
77614** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
77615** All three do the same thing.  They return the first non-NULL
77616** argument.
77617*/
77618static void ifnullFunc(
77619  sqlite3_context *context,
77620  int argc,
77621  sqlite3_value **argv
77622){
77623  int i;
77624  for(i=0; i<argc; i++){
77625    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
77626      sqlite3_result_value(context, argv[i]);
77627      break;
77628    }
77629  }
77630}
77631#endif /* NOT USED */
77632#define ifnullFunc versionFunc   /* Substitute function - never called */
77633
77634/*
77635** Implementation of random().  Return a random integer.
77636*/
77637static void randomFunc(
77638  sqlite3_context *context,
77639  int NotUsed,
77640  sqlite3_value **NotUsed2
77641){
77642  sqlite_int64 r;
77643  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77644  sqlite3_randomness(sizeof(r), &r);
77645  if( r<0 ){
77646    /* We need to prevent a random number of 0x8000000000000000
77647    ** (or -9223372036854775808) since when you do abs() of that
77648    ** number of you get the same value back again.  To do this
77649    ** in a way that is testable, mask the sign bit off of negative
77650    ** values, resulting in a positive value.  Then take the
77651    ** 2s complement of that positive value.  The end result can
77652    ** therefore be no less than -9223372036854775807.
77653    */
77654    r = -(r ^ (((sqlite3_int64)1)<<63));
77655  }
77656  sqlite3_result_int64(context, r);
77657}
77658
77659/*
77660** Implementation of randomblob(N).  Return a random blob
77661** that is N bytes long.
77662*/
77663static void randomBlob(
77664  sqlite3_context *context,
77665  int argc,
77666  sqlite3_value **argv
77667){
77668  int n;
77669  unsigned char *p;
77670  assert( argc==1 );
77671  UNUSED_PARAMETER(argc);
77672  n = sqlite3_value_int(argv[0]);
77673  if( n<1 ){
77674    n = 1;
77675  }
77676  p = contextMalloc(context, n);
77677  if( p ){
77678    sqlite3_randomness(n, p);
77679    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
77680  }
77681}
77682
77683/*
77684** Implementation of the last_insert_rowid() SQL function.  The return
77685** value is the same as the sqlite3_last_insert_rowid() API function.
77686*/
77687static void last_insert_rowid(
77688  sqlite3_context *context,
77689  int NotUsed,
77690  sqlite3_value **NotUsed2
77691){
77692  sqlite3 *db = sqlite3_context_db_handle(context);
77693  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77694  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
77695  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
77696  ** function. */
77697  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
77698}
77699
77700/*
77701** Implementation of the changes() SQL function.
77702**
77703** IMP: R-62073-11209 The changes() SQL function is a wrapper
77704** around the sqlite3_changes() C/C++ function and hence follows the same
77705** rules for counting changes.
77706*/
77707static void changes(
77708  sqlite3_context *context,
77709  int NotUsed,
77710  sqlite3_value **NotUsed2
77711){
77712  sqlite3 *db = sqlite3_context_db_handle(context);
77713  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77714  sqlite3_result_int(context, sqlite3_changes(db));
77715}
77716
77717/*
77718** Implementation of the total_changes() SQL function.  The return value is
77719** the same as the sqlite3_total_changes() API function.
77720*/
77721static void total_changes(
77722  sqlite3_context *context,
77723  int NotUsed,
77724  sqlite3_value **NotUsed2
77725){
77726  sqlite3 *db = sqlite3_context_db_handle(context);
77727  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77728  /* IMP: R-52756-41993 This function is a wrapper around the
77729  ** sqlite3_total_changes() C/C++ interface. */
77730  sqlite3_result_int(context, sqlite3_total_changes(db));
77731}
77732
77733/*
77734** A structure defining how to do GLOB-style comparisons.
77735*/
77736struct compareInfo {
77737  u8 matchAll;
77738  u8 matchOne;
77739  u8 matchSet;
77740  u8 noCase;
77741};
77742
77743/*
77744** For LIKE and GLOB matching on EBCDIC machines, assume that every
77745** character is exactly one byte in size.  Also, all characters are
77746** able to participate in upper-case-to-lower-case mappings in EBCDIC
77747** whereas only characters less than 0x80 do in ASCII.
77748*/
77749#if defined(SQLITE_EBCDIC)
77750# define sqlite3Utf8Read(A,C)    (*(A++))
77751# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
77752#else
77753# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
77754#endif
77755
77756static const struct compareInfo globInfo = { '*', '?', '[', 0 };
77757/* The correct SQL-92 behavior is for the LIKE operator to ignore
77758** case.  Thus  'a' LIKE 'A' would be true. */
77759static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
77760/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
77761** is case sensitive causing 'a' LIKE 'A' to be false */
77762static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
77763
77764/*
77765** Compare two UTF-8 strings for equality where the first string can
77766** potentially be a "glob" expression.  Return true (1) if they
77767** are the same and false (0) if they are different.
77768**
77769** Globbing rules:
77770**
77771**      '*'       Matches any sequence of zero or more characters.
77772**
77773**      '?'       Matches exactly one character.
77774**
77775**     [...]      Matches one character from the enclosed list of
77776**                characters.
77777**
77778**     [^...]     Matches one character not in the enclosed list.
77779**
77780** With the [...] and [^...] matching, a ']' character can be included
77781** in the list by making it the first character after '[' or '^'.  A
77782** range of characters can be specified using '-'.  Example:
77783** "[a-z]" matches any single lower-case letter.  To match a '-', make
77784** it the last character in the list.
77785**
77786** This routine is usually quick, but can be N**2 in the worst case.
77787**
77788** Hints: to match '*' or '?', put them in "[]".  Like this:
77789**
77790**         abc[*]xyz        Matches "abc*xyz" only
77791*/
77792static int patternCompare(
77793  const u8 *zPattern,              /* The glob pattern */
77794  const u8 *zString,               /* The string to compare against the glob */
77795  const struct compareInfo *pInfo, /* Information about how to do the compare */
77796  const int esc                    /* The escape character */
77797){
77798  int c, c2;
77799  int invert;
77800  int seen;
77801  u8 matchOne = pInfo->matchOne;
77802  u8 matchAll = pInfo->matchAll;
77803  u8 matchSet = pInfo->matchSet;
77804  u8 noCase = pInfo->noCase;
77805  int prevEscape = 0;     /* True if the previous character was 'escape' */
77806
77807  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
77808    if( !prevEscape && c==matchAll ){
77809      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
77810               || c == matchOne ){
77811        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
77812          return 0;
77813        }
77814      }
77815      if( c==0 ){
77816        return 1;
77817      }else if( c==esc ){
77818        c = sqlite3Utf8Read(zPattern, &zPattern);
77819        if( c==0 ){
77820          return 0;
77821        }
77822      }else if( c==matchSet ){
77823        assert( esc==0 );         /* This is GLOB, not LIKE */
77824        assert( matchSet<0x80 );  /* '[' is a single-byte character */
77825        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
77826          SQLITE_SKIP_UTF8(zString);
77827        }
77828        return *zString!=0;
77829      }
77830      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
77831        if( noCase ){
77832          GlogUpperToLower(c2);
77833          GlogUpperToLower(c);
77834          while( c2 != 0 && c2 != c ){
77835            c2 = sqlite3Utf8Read(zString, &zString);
77836            GlogUpperToLower(c2);
77837          }
77838        }else{
77839          while( c2 != 0 && c2 != c ){
77840            c2 = sqlite3Utf8Read(zString, &zString);
77841          }
77842        }
77843        if( c2==0 ) return 0;
77844        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
77845      }
77846      return 0;
77847    }else if( !prevEscape && c==matchOne ){
77848      if( sqlite3Utf8Read(zString, &zString)==0 ){
77849        return 0;
77850      }
77851    }else if( c==matchSet ){
77852      int prior_c = 0;
77853      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
77854      seen = 0;
77855      invert = 0;
77856      c = sqlite3Utf8Read(zString, &zString);
77857      if( c==0 ) return 0;
77858      c2 = sqlite3Utf8Read(zPattern, &zPattern);
77859      if( c2=='^' ){
77860        invert = 1;
77861        c2 = sqlite3Utf8Read(zPattern, &zPattern);
77862      }
77863      if( c2==']' ){
77864        if( c==']' ) seen = 1;
77865        c2 = sqlite3Utf8Read(zPattern, &zPattern);
77866      }
77867      while( c2 && c2!=']' ){
77868        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
77869          c2 = sqlite3Utf8Read(zPattern, &zPattern);
77870          if( c>=prior_c && c<=c2 ) seen = 1;
77871          prior_c = 0;
77872        }else{
77873          if( c==c2 ){
77874            seen = 1;
77875          }
77876          prior_c = c2;
77877        }
77878        c2 = sqlite3Utf8Read(zPattern, &zPattern);
77879      }
77880      if( c2==0 || (seen ^ invert)==0 ){
77881        return 0;
77882      }
77883    }else if( esc==c && !prevEscape ){
77884      prevEscape = 1;
77885    }else{
77886      c2 = sqlite3Utf8Read(zString, &zString);
77887      if( noCase ){
77888        GlogUpperToLower(c);
77889        GlogUpperToLower(c2);
77890      }
77891      if( c!=c2 ){
77892        return 0;
77893      }
77894      prevEscape = 0;
77895    }
77896  }
77897  return *zString==0;
77898}
77899
77900/*
77901** Count the number of times that the LIKE operator (or GLOB which is
77902** just a variation of LIKE) gets called.  This is used for testing
77903** only.
77904*/
77905#ifdef SQLITE_TEST
77906SQLITE_API int sqlite3_like_count = 0;
77907#endif
77908
77909
77910/*
77911** Implementation of the like() SQL function.  This function implements
77912** the build-in LIKE operator.  The first argument to the function is the
77913** pattern and the second argument is the string.  So, the SQL statements:
77914**
77915**       A LIKE B
77916**
77917** is implemented as like(B,A).
77918**
77919** This same function (with a different compareInfo structure) computes
77920** the GLOB operator.
77921*/
77922static void likeFunc(
77923  sqlite3_context *context,
77924  int argc,
77925  sqlite3_value **argv
77926){
77927  const unsigned char *zA, *zB;
77928  int escape = 0;
77929  int nPat;
77930  sqlite3 *db = sqlite3_context_db_handle(context);
77931
77932  zB = sqlite3_value_text(argv[0]);
77933  zA = sqlite3_value_text(argv[1]);
77934
77935  /* Limit the length of the LIKE or GLOB pattern to avoid problems
77936  ** of deep recursion and N*N behavior in patternCompare().
77937  */
77938  nPat = sqlite3_value_bytes(argv[0]);
77939  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
77940  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
77941  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
77942    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
77943    return;
77944  }
77945  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
77946
77947  if( argc==3 ){
77948    /* The escape character string must consist of a single UTF-8 character.
77949    ** Otherwise, return an error.
77950    */
77951    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
77952    if( zEsc==0 ) return;
77953    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
77954      sqlite3_result_error(context,
77955          "ESCAPE expression must be a single character", -1);
77956      return;
77957    }
77958    escape = sqlite3Utf8Read(zEsc, &zEsc);
77959  }
77960  if( zA && zB ){
77961    struct compareInfo *pInfo = sqlite3_user_data(context);
77962#ifdef SQLITE_TEST
77963    sqlite3_like_count++;
77964#endif
77965
77966    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
77967  }
77968}
77969
77970/*
77971** Implementation of the NULLIF(x,y) function.  The result is the first
77972** argument if the arguments are different.  The result is NULL if the
77973** arguments are equal to each other.
77974*/
77975static void nullifFunc(
77976  sqlite3_context *context,
77977  int NotUsed,
77978  sqlite3_value **argv
77979){
77980  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
77981  UNUSED_PARAMETER(NotUsed);
77982  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
77983    sqlite3_result_value(context, argv[0]);
77984  }
77985}
77986
77987/*
77988** Implementation of the sqlite_version() function.  The result is the version
77989** of the SQLite library that is running.
77990*/
77991static void versionFunc(
77992  sqlite3_context *context,
77993  int NotUsed,
77994  sqlite3_value **NotUsed2
77995){
77996  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77997  /* IMP: R-48699-48617 This function is an SQL wrapper around the
77998  ** sqlite3_libversion() C-interface. */
77999  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
78000}
78001
78002/*
78003** Implementation of the sqlite_source_id() function. The result is a string
78004** that identifies the particular version of the source code used to build
78005** SQLite.
78006*/
78007static void sourceidFunc(
78008  sqlite3_context *context,
78009  int NotUsed,
78010  sqlite3_value **NotUsed2
78011){
78012  UNUSED_PARAMETER2(NotUsed, NotUsed2);
78013  /* IMP: R-24470-31136 This function is an SQL wrapper around the
78014  ** sqlite3_sourceid() C interface. */
78015  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
78016}
78017
78018/*
78019** Implementation of the sqlite_compileoption_used() function.
78020** The result is an integer that identifies if the compiler option
78021** was used to build SQLite.
78022*/
78023#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78024static void compileoptionusedFunc(
78025  sqlite3_context *context,
78026  int argc,
78027  sqlite3_value **argv
78028){
78029  const char *zOptName;
78030  assert( argc==1 );
78031  UNUSED_PARAMETER(argc);
78032  /* IMP: R-xxxx This function is an SQL wrapper around the
78033  ** sqlite3_compileoption_used() C interface. */
78034  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
78035    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
78036  }
78037}
78038#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78039
78040/*
78041** Implementation of the sqlite_compileoption_get() function.
78042** The result is a string that identifies the compiler options
78043** used to build SQLite.
78044*/
78045#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78046static void compileoptiongetFunc(
78047  sqlite3_context *context,
78048  int argc,
78049  sqlite3_value **argv
78050){
78051  int n;
78052  assert( argc==1 );
78053  UNUSED_PARAMETER(argc);
78054  /* IMP: R-xxxx This function is an SQL wrapper around the
78055  ** sqlite3_compileoption_get() C interface. */
78056  n = sqlite3_value_int(argv[0]);
78057  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
78058}
78059#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78060
78061/* Array for converting from half-bytes (nybbles) into ASCII hex
78062** digits. */
78063static const char hexdigits[] = {
78064  '0', '1', '2', '3', '4', '5', '6', '7',
78065  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
78066};
78067
78068/*
78069** EXPERIMENTAL - This is not an official function.  The interface may
78070** change.  This function may disappear.  Do not write code that depends
78071** on this function.
78072**
78073** Implementation of the QUOTE() function.  This function takes a single
78074** argument.  If the argument is numeric, the return value is the same as
78075** the argument.  If the argument is NULL, the return value is the string
78076** "NULL".  Otherwise, the argument is enclosed in single quotes with
78077** single-quote escapes.
78078*/
78079static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78080  assert( argc==1 );
78081  UNUSED_PARAMETER(argc);
78082  switch( sqlite3_value_type(argv[0]) ){
78083    case SQLITE_INTEGER:
78084    case SQLITE_FLOAT: {
78085      sqlite3_result_value(context, argv[0]);
78086      break;
78087    }
78088    case SQLITE_BLOB: {
78089      char *zText = 0;
78090      char const *zBlob = sqlite3_value_blob(argv[0]);
78091      int nBlob = sqlite3_value_bytes(argv[0]);
78092      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
78093      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
78094      if( zText ){
78095        int i;
78096        for(i=0; i<nBlob; i++){
78097          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
78098          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
78099        }
78100        zText[(nBlob*2)+2] = '\'';
78101        zText[(nBlob*2)+3] = '\0';
78102        zText[0] = 'X';
78103        zText[1] = '\'';
78104        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
78105        sqlite3_free(zText);
78106      }
78107      break;
78108    }
78109    case SQLITE_TEXT: {
78110      int i,j;
78111      u64 n;
78112      const unsigned char *zArg = sqlite3_value_text(argv[0]);
78113      char *z;
78114
78115      if( zArg==0 ) return;
78116      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
78117      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
78118      if( z ){
78119        z[0] = '\'';
78120        for(i=0, j=1; zArg[i]; i++){
78121          z[j++] = zArg[i];
78122          if( zArg[i]=='\'' ){
78123            z[j++] = '\'';
78124          }
78125        }
78126        z[j++] = '\'';
78127        z[j] = 0;
78128        sqlite3_result_text(context, z, j, sqlite3_free);
78129      }
78130      break;
78131    }
78132    default: {
78133      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
78134      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
78135      break;
78136    }
78137  }
78138}
78139
78140/*
78141** The hex() function.  Interpret the argument as a blob.  Return
78142** a hexadecimal rendering as text.
78143*/
78144static void hexFunc(
78145  sqlite3_context *context,
78146  int argc,
78147  sqlite3_value **argv
78148){
78149  int i, n;
78150  const unsigned char *pBlob;
78151  char *zHex, *z;
78152  assert( argc==1 );
78153  UNUSED_PARAMETER(argc);
78154  pBlob = sqlite3_value_blob(argv[0]);
78155  n = sqlite3_value_bytes(argv[0]);
78156  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
78157  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
78158  if( zHex ){
78159    for(i=0; i<n; i++, pBlob++){
78160      unsigned char c = *pBlob;
78161      *(z++) = hexdigits[(c>>4)&0xf];
78162      *(z++) = hexdigits[c&0xf];
78163    }
78164    *z = 0;
78165    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
78166  }
78167}
78168
78169/*
78170** The zeroblob(N) function returns a zero-filled blob of size N bytes.
78171*/
78172static void zeroblobFunc(
78173  sqlite3_context *context,
78174  int argc,
78175  sqlite3_value **argv
78176){
78177  i64 n;
78178  sqlite3 *db = sqlite3_context_db_handle(context);
78179  assert( argc==1 );
78180  UNUSED_PARAMETER(argc);
78181  n = sqlite3_value_int64(argv[0]);
78182  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
78183  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
78184  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78185    sqlite3_result_error_toobig(context);
78186  }else{
78187    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
78188  }
78189}
78190
78191/*
78192** The replace() function.  Three arguments are all strings: call
78193** them A, B, and C. The result is also a string which is derived
78194** from A by replacing every occurance of B with C.  The match
78195** must be exact.  Collating sequences are not used.
78196*/
78197static void replaceFunc(
78198  sqlite3_context *context,
78199  int argc,
78200  sqlite3_value **argv
78201){
78202  const unsigned char *zStr;        /* The input string A */
78203  const unsigned char *zPattern;    /* The pattern string B */
78204  const unsigned char *zRep;        /* The replacement string C */
78205  unsigned char *zOut;              /* The output */
78206  int nStr;                /* Size of zStr */
78207  int nPattern;            /* Size of zPattern */
78208  int nRep;                /* Size of zRep */
78209  i64 nOut;                /* Maximum size of zOut */
78210  int loopLimit;           /* Last zStr[] that might match zPattern[] */
78211  int i, j;                /* Loop counters */
78212
78213  assert( argc==3 );
78214  UNUSED_PARAMETER(argc);
78215  zStr = sqlite3_value_text(argv[0]);
78216  if( zStr==0 ) return;
78217  nStr = sqlite3_value_bytes(argv[0]);
78218  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
78219  zPattern = sqlite3_value_text(argv[1]);
78220  if( zPattern==0 ){
78221    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
78222            || sqlite3_context_db_handle(context)->mallocFailed );
78223    return;
78224  }
78225  if( zPattern[0]==0 ){
78226    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
78227    sqlite3_result_value(context, argv[0]);
78228    return;
78229  }
78230  nPattern = sqlite3_value_bytes(argv[1]);
78231  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
78232  zRep = sqlite3_value_text(argv[2]);
78233  if( zRep==0 ) return;
78234  nRep = sqlite3_value_bytes(argv[2]);
78235  assert( zRep==sqlite3_value_text(argv[2]) );
78236  nOut = nStr + 1;
78237  assert( nOut<SQLITE_MAX_LENGTH );
78238  zOut = contextMalloc(context, (i64)nOut);
78239  if( zOut==0 ){
78240    return;
78241  }
78242  loopLimit = nStr - nPattern;
78243  for(i=j=0; i<=loopLimit; i++){
78244    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
78245      zOut[j++] = zStr[i];
78246    }else{
78247      u8 *zOld;
78248      sqlite3 *db = sqlite3_context_db_handle(context);
78249      nOut += nRep - nPattern;
78250      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
78251      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
78252      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78253        sqlite3_result_error_toobig(context);
78254        sqlite3DbFree(db, zOut);
78255        return;
78256      }
78257      zOld = zOut;
78258      zOut = sqlite3_realloc(zOut, (int)nOut);
78259      if( zOut==0 ){
78260        sqlite3_result_error_nomem(context);
78261        sqlite3DbFree(db, zOld);
78262        return;
78263      }
78264      memcpy(&zOut[j], zRep, nRep);
78265      j += nRep;
78266      i += nPattern-1;
78267    }
78268  }
78269  assert( j+nStr-i+1==nOut );
78270  memcpy(&zOut[j], &zStr[i], nStr-i);
78271  j += nStr - i;
78272  assert( j<=nOut );
78273  zOut[j] = 0;
78274  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
78275}
78276
78277/*
78278** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
78279** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
78280*/
78281static void trimFunc(
78282  sqlite3_context *context,
78283  int argc,
78284  sqlite3_value **argv
78285){
78286  const unsigned char *zIn;         /* Input string */
78287  const unsigned char *zCharSet;    /* Set of characters to trim */
78288  int nIn;                          /* Number of bytes in input */
78289  int flags;                        /* 1: trimleft  2: trimright  3: trim */
78290  int i;                            /* Loop counter */
78291  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
78292  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
78293  int nChar;                        /* Number of characters in zCharSet */
78294
78295  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
78296    return;
78297  }
78298  zIn = sqlite3_value_text(argv[0]);
78299  if( zIn==0 ) return;
78300  nIn = sqlite3_value_bytes(argv[0]);
78301  assert( zIn==sqlite3_value_text(argv[0]) );
78302  if( argc==1 ){
78303    static const unsigned char lenOne[] = { 1 };
78304    static unsigned char * const azOne[] = { (u8*)" " };
78305    nChar = 1;
78306    aLen = (u8*)lenOne;
78307    azChar = (unsigned char **)azOne;
78308    zCharSet = 0;
78309  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
78310    return;
78311  }else{
78312    const unsigned char *z;
78313    for(z=zCharSet, nChar=0; *z; nChar++){
78314      SQLITE_SKIP_UTF8(z);
78315    }
78316    if( nChar>0 ){
78317      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
78318      if( azChar==0 ){
78319        return;
78320      }
78321      aLen = (unsigned char*)&azChar[nChar];
78322      for(z=zCharSet, nChar=0; *z; nChar++){
78323        azChar[nChar] = (unsigned char *)z;
78324        SQLITE_SKIP_UTF8(z);
78325        aLen[nChar] = (u8)(z - azChar[nChar]);
78326      }
78327    }
78328  }
78329  if( nChar>0 ){
78330    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
78331    if( flags & 1 ){
78332      while( nIn>0 ){
78333        int len = 0;
78334        for(i=0; i<nChar; i++){
78335          len = aLen[i];
78336          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
78337        }
78338        if( i>=nChar ) break;
78339        zIn += len;
78340        nIn -= len;
78341      }
78342    }
78343    if( flags & 2 ){
78344      while( nIn>0 ){
78345        int len = 0;
78346        for(i=0; i<nChar; i++){
78347          len = aLen[i];
78348          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
78349        }
78350        if( i>=nChar ) break;
78351        nIn -= len;
78352      }
78353    }
78354    if( zCharSet ){
78355      sqlite3_free(azChar);
78356    }
78357  }
78358  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
78359}
78360
78361
78362/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
78363** is only available if the SQLITE_SOUNDEX compile-time option is used
78364** when SQLite is built.
78365*/
78366#ifdef SQLITE_SOUNDEX
78367/*
78368** Compute the soundex encoding of a word.
78369**
78370** IMP: R-59782-00072 The soundex(X) function returns a string that is the
78371** soundex encoding of the string X.
78372*/
78373static void soundexFunc(
78374  sqlite3_context *context,
78375  int argc,
78376  sqlite3_value **argv
78377){
78378  char zResult[8];
78379  const u8 *zIn;
78380  int i, j;
78381  static const unsigned char iCode[] = {
78382    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78383    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78384    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78385    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78386    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78387    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78388    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78389    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78390  };
78391  assert( argc==1 );
78392  zIn = (u8*)sqlite3_value_text(argv[0]);
78393  if( zIn==0 ) zIn = (u8*)"";
78394  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
78395  if( zIn[i] ){
78396    u8 prevcode = iCode[zIn[i]&0x7f];
78397    zResult[0] = sqlite3Toupper(zIn[i]);
78398    for(j=1; j<4 && zIn[i]; i++){
78399      int code = iCode[zIn[i]&0x7f];
78400      if( code>0 ){
78401        if( code!=prevcode ){
78402          prevcode = code;
78403          zResult[j++] = code + '0';
78404        }
78405      }else{
78406        prevcode = 0;
78407      }
78408    }
78409    while( j<4 ){
78410      zResult[j++] = '0';
78411    }
78412    zResult[j] = 0;
78413    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
78414  }else{
78415    /* IMP: R-64894-50321 The string "?000" is returned if the argument
78416    ** is NULL or contains no ASCII alphabetic characters. */
78417    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
78418  }
78419}
78420#endif /* SQLITE_SOUNDEX */
78421
78422#ifndef SQLITE_OMIT_LOAD_EXTENSION
78423/*
78424** A function that loads a shared-library extension then returns NULL.
78425*/
78426static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
78427  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
78428  const char *zProc;
78429  sqlite3 *db = sqlite3_context_db_handle(context);
78430  char *zErrMsg = 0;
78431
78432  if( argc==2 ){
78433    zProc = (const char *)sqlite3_value_text(argv[1]);
78434  }else{
78435    zProc = 0;
78436  }
78437  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
78438    sqlite3_result_error(context, zErrMsg, -1);
78439    sqlite3_free(zErrMsg);
78440  }
78441}
78442#endif
78443
78444
78445/*
78446** An instance of the following structure holds the context of a
78447** sum() or avg() aggregate computation.
78448*/
78449typedef struct SumCtx SumCtx;
78450struct SumCtx {
78451  double rSum;      /* Floating point sum */
78452  i64 iSum;         /* Integer sum */
78453  i64 cnt;          /* Number of elements summed */
78454  u8 overflow;      /* True if integer overflow seen */
78455  u8 approx;        /* True if non-integer value was input to the sum */
78456};
78457
78458/*
78459** Routines used to compute the sum, average, and total.
78460**
78461** The SUM() function follows the (broken) SQL standard which means
78462** that it returns NULL if it sums over no inputs.  TOTAL returns
78463** 0.0 in that case.  In addition, TOTAL always returns a float where
78464** SUM might return an integer if it never encounters a floating point
78465** value.  TOTAL never fails, but SUM might through an exception if
78466** it overflows an integer.
78467*/
78468static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78469  SumCtx *p;
78470  int type;
78471  assert( argc==1 );
78472  UNUSED_PARAMETER(argc);
78473  p = sqlite3_aggregate_context(context, sizeof(*p));
78474  type = sqlite3_value_numeric_type(argv[0]);
78475  if( p && type!=SQLITE_NULL ){
78476    p->cnt++;
78477    if( type==SQLITE_INTEGER ){
78478      i64 v = sqlite3_value_int64(argv[0]);
78479      p->rSum += v;
78480      if( (p->approx|p->overflow)==0 ){
78481        i64 iNewSum = p->iSum + v;
78482        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
78483        int s2 = (int)(v       >> (sizeof(i64)*8-1));
78484        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
78485        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
78486        p->iSum = iNewSum;
78487      }
78488    }else{
78489      p->rSum += sqlite3_value_double(argv[0]);
78490      p->approx = 1;
78491    }
78492  }
78493}
78494static void sumFinalize(sqlite3_context *context){
78495  SumCtx *p;
78496  p = sqlite3_aggregate_context(context, 0);
78497  if( p && p->cnt>0 ){
78498    if( p->overflow ){
78499      sqlite3_result_error(context,"integer overflow",-1);
78500    }else if( p->approx ){
78501      sqlite3_result_double(context, p->rSum);
78502    }else{
78503      sqlite3_result_int64(context, p->iSum);
78504    }
78505  }
78506}
78507static void avgFinalize(sqlite3_context *context){
78508  SumCtx *p;
78509  p = sqlite3_aggregate_context(context, 0);
78510  if( p && p->cnt>0 ){
78511    sqlite3_result_double(context, p->rSum/(double)p->cnt);
78512  }
78513}
78514static void totalFinalize(sqlite3_context *context){
78515  SumCtx *p;
78516  p = sqlite3_aggregate_context(context, 0);
78517  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78518  sqlite3_result_double(context, p ? p->rSum : (double)0);
78519}
78520
78521/*
78522** The following structure keeps track of state information for the
78523** count() aggregate function.
78524*/
78525typedef struct CountCtx CountCtx;
78526struct CountCtx {
78527  i64 n;
78528};
78529
78530/*
78531** Routines to implement the count() aggregate function.
78532*/
78533static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78534  CountCtx *p;
78535  p = sqlite3_aggregate_context(context, sizeof(*p));
78536  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
78537    p->n++;
78538  }
78539
78540#ifndef SQLITE_OMIT_DEPRECATED
78541  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
78542  ** sure it still operates correctly, verify that its count agrees with our
78543  ** internal count when using count(*) and when the total count can be
78544  ** expressed as a 32-bit integer. */
78545  assert( argc==1 || p==0 || p->n>0x7fffffff
78546          || p->n==sqlite3_aggregate_count(context) );
78547#endif
78548}
78549static void countFinalize(sqlite3_context *context){
78550  CountCtx *p;
78551  p = sqlite3_aggregate_context(context, 0);
78552  sqlite3_result_int64(context, p ? p->n : 0);
78553}
78554
78555/*
78556** Routines to implement min() and max() aggregate functions.
78557*/
78558static void minmaxStep(
78559  sqlite3_context *context,
78560  int NotUsed,
78561  sqlite3_value **argv
78562){
78563  Mem *pArg  = (Mem *)argv[0];
78564  Mem *pBest;
78565  UNUSED_PARAMETER(NotUsed);
78566
78567  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78568  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
78569  if( !pBest ) return;
78570
78571  if( pBest->flags ){
78572    int max;
78573    int cmp;
78574    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
78575    /* This step function is used for both the min() and max() aggregates,
78576    ** the only difference between the two being that the sense of the
78577    ** comparison is inverted. For the max() aggregate, the
78578    ** sqlite3_user_data() function returns (void *)-1. For min() it
78579    ** returns (void *)db, where db is the sqlite3* database pointer.
78580    ** Therefore the next statement sets variable 'max' to 1 for the max()
78581    ** aggregate, or 0 for min().
78582    */
78583    max = sqlite3_user_data(context)!=0;
78584    cmp = sqlite3MemCompare(pBest, pArg, pColl);
78585    if( (max && cmp<0) || (!max && cmp>0) ){
78586      sqlite3VdbeMemCopy(pBest, pArg);
78587    }
78588  }else{
78589    sqlite3VdbeMemCopy(pBest, pArg);
78590  }
78591}
78592static void minMaxFinalize(sqlite3_context *context){
78593  sqlite3_value *pRes;
78594  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
78595  if( pRes ){
78596    if( ALWAYS(pRes->flags) ){
78597      sqlite3_result_value(context, pRes);
78598    }
78599    sqlite3VdbeMemRelease(pRes);
78600  }
78601}
78602
78603/*
78604** group_concat(EXPR, ?SEPARATOR?)
78605*/
78606static void groupConcatStep(
78607  sqlite3_context *context,
78608  int argc,
78609  sqlite3_value **argv
78610){
78611  const char *zVal;
78612  StrAccum *pAccum;
78613  const char *zSep;
78614  int nVal, nSep;
78615  assert( argc==1 || argc==2 );
78616  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78617  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
78618
78619  if( pAccum ){
78620    sqlite3 *db = sqlite3_context_db_handle(context);
78621    int firstTerm = pAccum->useMalloc==0;
78622    pAccum->useMalloc = 1;
78623    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
78624    if( !firstTerm ){
78625      if( argc==2 ){
78626        zSep = (char*)sqlite3_value_text(argv[1]);
78627        nSep = sqlite3_value_bytes(argv[1]);
78628      }else{
78629        zSep = ",";
78630        nSep = 1;
78631      }
78632      sqlite3StrAccumAppend(pAccum, zSep, nSep);
78633    }
78634    zVal = (char*)sqlite3_value_text(argv[0]);
78635    nVal = sqlite3_value_bytes(argv[0]);
78636    sqlite3StrAccumAppend(pAccum, zVal, nVal);
78637  }
78638}
78639static void groupConcatFinalize(sqlite3_context *context){
78640  StrAccum *pAccum;
78641  pAccum = sqlite3_aggregate_context(context, 0);
78642  if( pAccum ){
78643    if( pAccum->tooBig ){
78644      sqlite3_result_error_toobig(context);
78645    }else if( pAccum->mallocFailed ){
78646      sqlite3_result_error_nomem(context);
78647    }else{
78648      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
78649                          sqlite3_free);
78650    }
78651  }
78652}
78653
78654/*
78655** This routine does per-connection function registration.  Most
78656** of the built-in functions above are part of the global function set.
78657** This routine only deals with those that are not global.
78658*/
78659SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
78660  int rc = sqlite3_overload_function(db, "MATCH", 2);
78661  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
78662  if( rc==SQLITE_NOMEM ){
78663    db->mallocFailed = 1;
78664  }
78665}
78666
78667/*
78668** Set the LIKEOPT flag on the 2-argument function with the given name.
78669*/
78670static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
78671  FuncDef *pDef;
78672  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
78673                             2, SQLITE_UTF8, 0);
78674  if( ALWAYS(pDef) ){
78675    pDef->flags = flagVal;
78676  }
78677}
78678
78679/*
78680** Register the built-in LIKE and GLOB functions.  The caseSensitive
78681** parameter determines whether or not the LIKE operator is case
78682** sensitive.  GLOB is always case sensitive.
78683*/
78684SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
78685  struct compareInfo *pInfo;
78686  if( caseSensitive ){
78687    pInfo = (struct compareInfo*)&likeInfoAlt;
78688  }else{
78689    pInfo = (struct compareInfo*)&likeInfoNorm;
78690  }
78691  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
78692  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
78693  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
78694      (struct compareInfo*)&globInfo, likeFunc, 0,0);
78695  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
78696  setLikeOptFlag(db, "like",
78697      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
78698}
78699
78700/*
78701** pExpr points to an expression which implements a function.  If
78702** it is appropriate to apply the LIKE optimization to that function
78703** then set aWc[0] through aWc[2] to the wildcard characters and
78704** return TRUE.  If the function is not a LIKE-style function then
78705** return FALSE.
78706*/
78707SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
78708  FuncDef *pDef;
78709  if( pExpr->op!=TK_FUNCTION
78710   || !pExpr->x.pList
78711   || pExpr->x.pList->nExpr!=2
78712  ){
78713    return 0;
78714  }
78715  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78716  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
78717                             sqlite3Strlen30(pExpr->u.zToken),
78718                             2, SQLITE_UTF8, 0);
78719  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
78720    return 0;
78721  }
78722
78723  /* The memcpy() statement assumes that the wildcard characters are
78724  ** the first three statements in the compareInfo structure.  The
78725  ** asserts() that follow verify that assumption
78726  */
78727  memcpy(aWc, pDef->pUserData, 3);
78728  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
78729  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
78730  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
78731  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
78732  return 1;
78733}
78734
78735/*
78736** All all of the FuncDef structures in the aBuiltinFunc[] array above
78737** to the global function hash table.  This occurs at start-time (as
78738** a consequence of calling sqlite3_initialize()).
78739**
78740** After this routine runs
78741*/
78742SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
78743  /*
78744  ** The following array holds FuncDef structures for all of the functions
78745  ** defined in this file.
78746  **
78747  ** The array cannot be constant since changes are made to the
78748  ** FuncDef.pHash elements at start-time.  The elements of this array
78749  ** are read-only after initialization is complete.
78750  */
78751  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
78752    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
78753    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
78754    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
78755    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
78756    FUNCTION(trim,               1, 3, 0, trimFunc         ),
78757    FUNCTION(trim,               2, 3, 0, trimFunc         ),
78758    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
78759    FUNCTION(min,                0, 0, 1, 0                ),
78760    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
78761    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
78762    FUNCTION(max,                0, 1, 1, 0                ),
78763    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
78764    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
78765    FUNCTION(length,             1, 0, 0, lengthFunc       ),
78766    FUNCTION(substr,             2, 0, 0, substrFunc       ),
78767    FUNCTION(substr,             3, 0, 0, substrFunc       ),
78768    FUNCTION(abs,                1, 0, 0, absFunc          ),
78769#ifndef SQLITE_OMIT_FLOATING_POINT
78770    FUNCTION(round,              1, 0, 0, roundFunc        ),
78771    FUNCTION(round,              2, 0, 0, roundFunc        ),
78772#endif
78773    FUNCTION(upper,              1, 0, 0, upperFunc        ),
78774    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
78775    FUNCTION(coalesce,           1, 0, 0, 0                ),
78776    FUNCTION(coalesce,           0, 0, 0, 0                ),
78777/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
78778    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
78779    FUNCTION(hex,                1, 0, 0, hexFunc          ),
78780/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
78781    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
78782    FUNCTION(random,             0, 0, 0, randomFunc       ),
78783    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
78784    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
78785    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
78786    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
78787#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78788    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
78789    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
78790#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78791    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
78792    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
78793    FUNCTION(changes,            0, 0, 0, changes          ),
78794    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
78795    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
78796    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
78797  #ifdef SQLITE_SOUNDEX
78798    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
78799  #endif
78800  #ifndef SQLITE_OMIT_LOAD_EXTENSION
78801    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
78802    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
78803  #endif
78804    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
78805    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
78806    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
78807 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
78808    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
78809    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
78810    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
78811    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
78812
78813    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
78814  #ifdef SQLITE_CASE_SENSITIVE_LIKE
78815    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
78816    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
78817  #else
78818    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
78819    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
78820  #endif
78821  };
78822
78823  int i;
78824  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78825  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
78826
78827  for(i=0; i<ArraySize(aBuiltinFunc); i++){
78828    sqlite3FuncDefInsert(pHash, &aFunc[i]);
78829  }
78830  sqlite3RegisterDateTimeFunctions();
78831#ifndef SQLITE_OMIT_ALTERTABLE
78832  sqlite3AlterFunctions();
78833#endif
78834}
78835
78836/************** End of func.c ************************************************/
78837/************** Begin file fkey.c ********************************************/
78838/*
78839**
78840** The author disclaims copyright to this source code.  In place of
78841** a legal notice, here is a blessing:
78842**
78843**    May you do good and not evil.
78844**    May you find forgiveness for yourself and forgive others.
78845**    May you share freely, never taking more than you give.
78846**
78847*************************************************************************
78848** This file contains code used by the compiler to add foreign key
78849** support to compiled SQL statements.
78850*/
78851
78852#ifndef SQLITE_OMIT_FOREIGN_KEY
78853#ifndef SQLITE_OMIT_TRIGGER
78854
78855/*
78856** Deferred and Immediate FKs
78857** --------------------------
78858**
78859** Foreign keys in SQLite come in two flavours: deferred and immediate.
78860** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
78861** is returned and the current statement transaction rolled back. If a
78862** deferred foreign key constraint is violated, no action is taken
78863** immediately. However if the application attempts to commit the
78864** transaction before fixing the constraint violation, the attempt fails.
78865**
78866** Deferred constraints are implemented using a simple counter associated
78867** with the database handle. The counter is set to zero each time a
78868** database transaction is opened. Each time a statement is executed
78869** that causes a foreign key violation, the counter is incremented. Each
78870** time a statement is executed that removes an existing violation from
78871** the database, the counter is decremented. When the transaction is
78872** committed, the commit fails if the current value of the counter is
78873** greater than zero. This scheme has two big drawbacks:
78874**
78875**   * When a commit fails due to a deferred foreign key constraint,
78876**     there is no way to tell which foreign constraint is not satisfied,
78877**     or which row it is not satisfied for.
78878**
78879**   * If the database contains foreign key violations when the
78880**     transaction is opened, this may cause the mechanism to malfunction.
78881**
78882** Despite these problems, this approach is adopted as it seems simpler
78883** than the alternatives.
78884**
78885** INSERT operations:
78886**
78887**   I.1) For each FK for which the table is the child table, search
78888**        the parent table for a match. If none is found increment the
78889**        constraint counter.
78890**
78891**   I.2) For each FK for which the table is the parent table,
78892**        search the child table for rows that correspond to the new
78893**        row in the parent table. Decrement the counter for each row
78894**        found (as the constraint is now satisfied).
78895**
78896** DELETE operations:
78897**
78898**   D.1) For each FK for which the table is the child table,
78899**        search the parent table for a row that corresponds to the
78900**        deleted row in the child table. If such a row is not found,
78901**        decrement the counter.
78902**
78903**   D.2) For each FK for which the table is the parent table, search
78904**        the child table for rows that correspond to the deleted row
78905**        in the parent table. For each found increment the counter.
78906**
78907** UPDATE operations:
78908**
78909**   An UPDATE command requires that all 4 steps above are taken, but only
78910**   for FK constraints for which the affected columns are actually
78911**   modified (values must be compared at runtime).
78912**
78913** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
78914** This simplifies the implementation a bit.
78915**
78916** For the purposes of immediate FK constraints, the OR REPLACE conflict
78917** resolution is considered to delete rows before the new row is inserted.
78918** If a delete caused by OR REPLACE violates an FK constraint, an exception
78919** is thrown, even if the FK constraint would be satisfied after the new
78920** row is inserted.
78921**
78922** Immediate constraints are usually handled similarly. The only difference
78923** is that the counter used is stored as part of each individual statement
78924** object (struct Vdbe). If, after the statement has run, its immediate
78925** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
78926** and the statement transaction is rolled back. An exception is an INSERT
78927** statement that inserts a single row only (no triggers). In this case,
78928** instead of using a counter, an exception is thrown immediately if the
78929** INSERT violates a foreign key constraint. This is necessary as such
78930** an INSERT does not open a statement transaction.
78931**
78932** TODO: How should dropping a table be handled? How should renaming a
78933** table be handled?
78934**
78935**
78936** Query API Notes
78937** ---------------
78938**
78939** Before coding an UPDATE or DELETE row operation, the code-generator
78940** for those two operations needs to know whether or not the operation
78941** requires any FK processing and, if so, which columns of the original
78942** row are required by the FK processing VDBE code (i.e. if FKs were
78943** implemented using triggers, which of the old.* columns would be
78944** accessed). No information is required by the code-generator before
78945** coding an INSERT operation. The functions used by the UPDATE/DELETE
78946** generation code to query for this information are:
78947**
78948**   sqlite3FkRequired() - Test to see if FK processing is required.
78949**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
78950**
78951**
78952** Externally accessible module functions
78953** --------------------------------------
78954**
78955**   sqlite3FkCheck()    - Check for foreign key violations.
78956**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
78957**   sqlite3FkDelete()   - Delete an FKey structure.
78958*/
78959
78960/*
78961** VDBE Calling Convention
78962** -----------------------
78963**
78964** Example:
78965**
78966**   For the following INSERT statement:
78967**
78968**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
78969**     INSERT INTO t1 VALUES(1, 2, 3.1);
78970**
78971**   Register (x):        2    (type integer)
78972**   Register (x+1):      1    (type integer)
78973**   Register (x+2):      NULL (type NULL)
78974**   Register (x+3):      3.1  (type real)
78975*/
78976
78977/*
78978** A foreign key constraint requires that the key columns in the parent
78979** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
78980** Given that pParent is the parent table for foreign key constraint pFKey,
78981** search the schema a unique index on the parent key columns.
78982**
78983** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
78984** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
78985** is set to point to the unique index.
78986**
78987** If the parent key consists of a single column (the foreign key constraint
78988** is not a composite foreign key), output variable *paiCol is set to NULL.
78989** Otherwise, it is set to point to an allocated array of size N, where
78990** N is the number of columns in the parent key. The first element of the
78991** array is the index of the child table column that is mapped by the FK
78992** constraint to the parent table column stored in the left-most column
78993** of index *ppIdx. The second element of the array is the index of the
78994** child table column that corresponds to the second left-most column of
78995** *ppIdx, and so on.
78996**
78997** If the required index cannot be found, either because:
78998**
78999**   1) The named parent key columns do not exist, or
79000**
79001**   2) The named parent key columns do exist, but are not subject to a
79002**      UNIQUE or PRIMARY KEY constraint, or
79003**
79004**   3) No parent key columns were provided explicitly as part of the
79005**      foreign key definition, and the parent table does not have a
79006**      PRIMARY KEY, or
79007**
79008**   4) No parent key columns were provided explicitly as part of the
79009**      foreign key definition, and the PRIMARY KEY of the parent table
79010**      consists of a a different number of columns to the child key in
79011**      the child table.
79012**
79013** then non-zero is returned, and a "foreign key mismatch" error loaded
79014** into pParse. If an OOM error occurs, non-zero is returned and the
79015** pParse->db->mallocFailed flag is set.
79016*/
79017static int locateFkeyIndex(
79018  Parse *pParse,                  /* Parse context to store any error in */
79019  Table *pParent,                 /* Parent table of FK constraint pFKey */
79020  FKey *pFKey,                    /* Foreign key to find index for */
79021  Index **ppIdx,                  /* OUT: Unique index on parent table */
79022  int **paiCol                    /* OUT: Map of index columns in pFKey */
79023){
79024  Index *pIdx = 0;                    /* Value to return via *ppIdx */
79025  int *aiCol = 0;                     /* Value to return via *paiCol */
79026  int nCol = pFKey->nCol;             /* Number of columns in parent key */
79027  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
79028
79029  /* The caller is responsible for zeroing output parameters. */
79030  assert( ppIdx && *ppIdx==0 );
79031  assert( !paiCol || *paiCol==0 );
79032  assert( pParse );
79033
79034  /* If this is a non-composite (single column) foreign key, check if it
79035  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
79036  ** and *paiCol set to zero and return early.
79037  **
79038  ** Otherwise, for a composite foreign key (more than one column), allocate
79039  ** space for the aiCol array (returned via output parameter *paiCol).
79040  ** Non-composite foreign keys do not require the aiCol array.
79041  */
79042  if( nCol==1 ){
79043    /* The FK maps to the IPK if any of the following are true:
79044    **
79045    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
79046    **      mapped to the primary key of table pParent, or
79047    **   2) The FK is explicitly mapped to a column declared as INTEGER
79048    **      PRIMARY KEY.
79049    */
79050    if( pParent->iPKey>=0 ){
79051      if( !zKey ) return 0;
79052      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
79053    }
79054  }else if( paiCol ){
79055    assert( nCol>1 );
79056    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
79057    if( !aiCol ) return 1;
79058    *paiCol = aiCol;
79059  }
79060
79061  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
79062    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
79063      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
79064      ** of columns. If each indexed column corresponds to a foreign key
79065      ** column of pFKey, then this index is a winner.  */
79066
79067      if( zKey==0 ){
79068        /* If zKey is NULL, then this foreign key is implicitly mapped to
79069        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
79070        ** identified by the test (Index.autoIndex==2).  */
79071        if( pIdx->autoIndex==2 ){
79072          if( aiCol ){
79073            int i;
79074            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
79075          }
79076          break;
79077        }
79078      }else{
79079        /* If zKey is non-NULL, then this foreign key was declared to
79080        ** map to an explicit list of columns in table pParent. Check if this
79081        ** index matches those columns. Also, check that the index uses
79082        ** the default collation sequences for each column. */
79083        int i, j;
79084        for(i=0; i<nCol; i++){
79085          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
79086          char *zDfltColl;                  /* Def. collation for column */
79087          char *zIdxCol;                    /* Name of indexed column */
79088
79089          /* If the index uses a collation sequence that is different from
79090          ** the default collation sequence for the column, this index is
79091          ** unusable. Bail out early in this case.  */
79092          zDfltColl = pParent->aCol[iCol].zColl;
79093          if( !zDfltColl ){
79094            zDfltColl = "BINARY";
79095          }
79096          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
79097
79098          zIdxCol = pParent->aCol[iCol].zName;
79099          for(j=0; j<nCol; j++){
79100            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
79101              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
79102              break;
79103            }
79104          }
79105          if( j==nCol ) break;
79106        }
79107        if( i==nCol ) break;      /* pIdx is usable */
79108      }
79109    }
79110  }
79111
79112  if( !pIdx ){
79113    if( !pParse->disableTriggers ){
79114      sqlite3ErrorMsg(pParse, "foreign key mismatch");
79115    }
79116    sqlite3DbFree(pParse->db, aiCol);
79117    return 1;
79118  }
79119
79120  *ppIdx = pIdx;
79121  return 0;
79122}
79123
79124/*
79125** This function is called when a row is inserted into or deleted from the
79126** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
79127** on the child table of pFKey, this function is invoked twice for each row
79128** affected - once to "delete" the old row, and then again to "insert" the
79129** new row.
79130**
79131** Each time it is called, this function generates VDBE code to locate the
79132** row in the parent table that corresponds to the row being inserted into
79133** or deleted from the child table. If the parent row can be found, no
79134** special action is taken. Otherwise, if the parent row can *not* be
79135** found in the parent table:
79136**
79137**   Operation | FK type   | Action taken
79138**   --------------------------------------------------------------------------
79139**   INSERT      immediate   Increment the "immediate constraint counter".
79140**
79141**   DELETE      immediate   Decrement the "immediate constraint counter".
79142**
79143**   INSERT      deferred    Increment the "deferred constraint counter".
79144**
79145**   DELETE      deferred    Decrement the "deferred constraint counter".
79146**
79147** These operations are identified in the comment at the top of this file
79148** (fkey.c) as "I.1" and "D.1".
79149*/
79150static void fkLookupParent(
79151  Parse *pParse,        /* Parse context */
79152  int iDb,              /* Index of database housing pTab */
79153  Table *pTab,          /* Parent table of FK pFKey */
79154  Index *pIdx,          /* Unique index on parent key columns in pTab */
79155  FKey *pFKey,          /* Foreign key constraint */
79156  int *aiCol,           /* Map from parent key columns to child table columns */
79157  int regData,          /* Address of array containing child table row */
79158  int nIncr,            /* Increment constraint counter by this */
79159  int isIgnore          /* If true, pretend pTab contains all NULL values */
79160){
79161  int i;                                    /* Iterator variable */
79162  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
79163  int iCur = pParse->nTab - 1;              /* Cursor number to use */
79164  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
79165
79166  /* If nIncr is less than zero, then check at runtime if there are any
79167  ** outstanding constraints to resolve. If there are not, there is no need
79168  ** to check if deleting this row resolves any outstanding violations.
79169  **
79170  ** Check if any of the key columns in the child table row are NULL. If
79171  ** any are, then the constraint is considered satisfied. No need to
79172  ** search for a matching row in the parent table.  */
79173  if( nIncr<0 ){
79174    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
79175  }
79176  for(i=0; i<pFKey->nCol; i++){
79177    int iReg = aiCol[i] + regData + 1;
79178    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
79179  }
79180
79181  if( isIgnore==0 ){
79182    if( pIdx==0 ){
79183      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
79184      ** column of the parent table (table pTab).  */
79185      int iMustBeInt;               /* Address of MustBeInt instruction */
79186      int regTemp = sqlite3GetTempReg(pParse);
79187
79188      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
79189      ** apply the affinity of the parent key). If this fails, then there
79190      ** is no matching parent key. Before using MustBeInt, make a copy of
79191      ** the value. Otherwise, the value inserted into the child key column
79192      ** will have INTEGER affinity applied to it, which may not be correct.  */
79193      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
79194      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
79195
79196      /* If the parent table is the same as the child table, and we are about
79197      ** to increment the constraint-counter (i.e. this is an INSERT operation),
79198      ** then check if the row being inserted matches itself. If so, do not
79199      ** increment the constraint-counter.  */
79200      if( pTab==pFKey->pFrom && nIncr==1 ){
79201        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
79202      }
79203
79204      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
79205      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
79206      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79207      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
79208      sqlite3VdbeJumpHere(v, iMustBeInt);
79209      sqlite3ReleaseTempReg(pParse, regTemp);
79210    }else{
79211      int nCol = pFKey->nCol;
79212      int regTemp = sqlite3GetTempRange(pParse, nCol);
79213      int regRec = sqlite3GetTempReg(pParse);
79214      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79215
79216      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
79217      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
79218      for(i=0; i<nCol; i++){
79219        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
79220      }
79221
79222      /* If the parent table is the same as the child table, and we are about
79223      ** to increment the constraint-counter (i.e. this is an INSERT operation),
79224      ** then check if the row being inserted matches itself. If so, do not
79225      ** increment the constraint-counter.  */
79226      if( pTab==pFKey->pFrom && nIncr==1 ){
79227        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
79228        for(i=0; i<nCol; i++){
79229          int iChild = aiCol[i]+1+regData;
79230          int iParent = pIdx->aiColumn[i]+1+regData;
79231          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
79232        }
79233        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79234      }
79235
79236      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
79237      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79238      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
79239
79240      sqlite3ReleaseTempReg(pParse, regRec);
79241      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
79242    }
79243  }
79244
79245  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79246    /* Special case: If this is an INSERT statement that will insert exactly
79247    ** one row into the table, raise a constraint immediately instead of
79248    ** incrementing a counter. This is necessary as the VM code is being
79249    ** generated for will not open a statement transaction.  */
79250    assert( nIncr==1 );
79251    sqlite3HaltConstraint(
79252        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79253    );
79254  }else{
79255    if( nIncr>0 && pFKey->isDeferred==0 ){
79256      sqlite3ParseToplevel(pParse)->mayAbort = 1;
79257    }
79258    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79259  }
79260
79261  sqlite3VdbeResolveLabel(v, iOk);
79262  sqlite3VdbeAddOp1(v, OP_Close, iCur);
79263}
79264
79265/*
79266** This function is called to generate code executed when a row is deleted
79267** from the parent table of foreign key constraint pFKey and, if pFKey is
79268** deferred, when a row is inserted into the same table. When generating
79269** code for an SQL UPDATE operation, this function may be called twice -
79270** once to "delete" the old row and once to "insert" the new row.
79271**
79272** The code generated by this function scans through the rows in the child
79273** table that correspond to the parent table row being deleted or inserted.
79274** For each child row found, one of the following actions is taken:
79275**
79276**   Operation | FK type   | Action taken
79277**   --------------------------------------------------------------------------
79278**   DELETE      immediate   Increment the "immediate constraint counter".
79279**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79280**                           throw a "foreign key constraint failed" exception.
79281**
79282**   INSERT      immediate   Decrement the "immediate constraint counter".
79283**
79284**   DELETE      deferred    Increment the "deferred constraint counter".
79285**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79286**                           throw a "foreign key constraint failed" exception.
79287**
79288**   INSERT      deferred    Decrement the "deferred constraint counter".
79289**
79290** These operations are identified in the comment at the top of this file
79291** (fkey.c) as "I.2" and "D.2".
79292*/
79293static void fkScanChildren(
79294  Parse *pParse,                  /* Parse context */
79295  SrcList *pSrc,                  /* SrcList containing the table to scan */
79296  Table *pTab,
79297  Index *pIdx,                    /* Foreign key index */
79298  FKey *pFKey,                    /* Foreign key relationship */
79299  int *aiCol,                     /* Map from pIdx cols to child table cols */
79300  int regData,                    /* Referenced table data starts here */
79301  int nIncr                       /* Amount to increment deferred counter by */
79302){
79303  sqlite3 *db = pParse->db;       /* Database handle */
79304  int i;                          /* Iterator variable */
79305  Expr *pWhere = 0;               /* WHERE clause to scan with */
79306  NameContext sNameContext;       /* Context used to resolve WHERE clause */
79307  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
79308  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
79309  Vdbe *v = sqlite3GetVdbe(pParse);
79310
79311  assert( !pIdx || pIdx->pTable==pTab );
79312
79313  if( nIncr<0 ){
79314    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
79315  }
79316
79317  /* Create an Expr object representing an SQL expression like:
79318  **
79319  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
79320  **
79321  ** The collation sequence used for the comparison should be that of
79322  ** the parent key columns. The affinity of the parent key column should
79323  ** be applied to each child key value before the comparison takes place.
79324  */
79325  for(i=0; i<pFKey->nCol; i++){
79326    Expr *pLeft;                  /* Value from parent table row */
79327    Expr *pRight;                 /* Column ref to child table */
79328    Expr *pEq;                    /* Expression (pLeft = pRight) */
79329    int iCol;                     /* Index of column in child table */
79330    const char *zCol;             /* Name of column in child table */
79331
79332    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79333    if( pLeft ){
79334      /* Set the collation sequence and affinity of the LHS of each TK_EQ
79335      ** expression to the parent key column defaults.  */
79336      if( pIdx ){
79337        Column *pCol;
79338        iCol = pIdx->aiColumn[i];
79339        pCol = &pIdx->pTable->aCol[iCol];
79340        pLeft->iTable = regData+iCol+1;
79341        pLeft->affinity = pCol->affinity;
79342        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
79343      }else{
79344        pLeft->iTable = regData;
79345        pLeft->affinity = SQLITE_AFF_INTEGER;
79346      }
79347    }
79348    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
79349    assert( iCol>=0 );
79350    zCol = pFKey->pFrom->aCol[iCol].zName;
79351    pRight = sqlite3Expr(db, TK_ID, zCol);
79352    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
79353    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79354  }
79355
79356  /* If the child table is the same as the parent table, and this scan
79357  ** is taking place as part of a DELETE operation (operation D.2), omit the
79358  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
79359  ** clause, where $rowid is the rowid of the row being deleted.  */
79360  if( pTab==pFKey->pFrom && nIncr>0 ){
79361    Expr *pEq;                    /* Expression (pLeft = pRight) */
79362    Expr *pLeft;                  /* Value from parent table row */
79363    Expr *pRight;                 /* Column ref to child table */
79364    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79365    pRight = sqlite3Expr(db, TK_COLUMN, 0);
79366    if( pLeft && pRight ){
79367      pLeft->iTable = regData;
79368      pLeft->affinity = SQLITE_AFF_INTEGER;
79369      pRight->iTable = pSrc->a[0].iCursor;
79370      pRight->iColumn = -1;
79371    }
79372    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
79373    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79374  }
79375
79376  /* Resolve the references in the WHERE clause. */
79377  memset(&sNameContext, 0, sizeof(NameContext));
79378  sNameContext.pSrcList = pSrc;
79379  sNameContext.pParse = pParse;
79380  sqlite3ResolveExprNames(&sNameContext, pWhere);
79381
79382  /* Create VDBE to loop through the entries in pSrc that match the WHERE
79383  ** clause. If the constraint is not deferred, throw an exception for
79384  ** each row found. Otherwise, for deferred constraints, increment the
79385  ** deferred constraint counter by nIncr for each row selected.  */
79386  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
79387  if( nIncr>0 && pFKey->isDeferred==0 ){
79388    sqlite3ParseToplevel(pParse)->mayAbort = 1;
79389  }
79390  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79391  if( pWInfo ){
79392    sqlite3WhereEnd(pWInfo);
79393  }
79394
79395  /* Clean up the WHERE clause constructed above. */
79396  sqlite3ExprDelete(db, pWhere);
79397  if( iFkIfZero ){
79398    sqlite3VdbeJumpHere(v, iFkIfZero);
79399  }
79400}
79401
79402/*
79403** This function returns a pointer to the head of a linked list of FK
79404** constraints for which table pTab is the parent table. For example,
79405** given the following schema:
79406**
79407**   CREATE TABLE t1(a PRIMARY KEY);
79408**   CREATE TABLE t2(b REFERENCES t1(a);
79409**
79410** Calling this function with table "t1" as an argument returns a pointer
79411** to the FKey structure representing the foreign key constraint on table
79412** "t2". Calling this function with "t2" as the argument would return a
79413** NULL pointer (as there are no FK constraints for which t2 is the parent
79414** table).
79415*/
79416SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
79417  int nName = sqlite3Strlen30(pTab->zName);
79418  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
79419}
79420
79421/*
79422** The second argument is a Trigger structure allocated by the
79423** fkActionTrigger() routine. This function deletes the Trigger structure
79424** and all of its sub-components.
79425**
79426** The Trigger structure or any of its sub-components may be allocated from
79427** the lookaside buffer belonging to database handle dbMem.
79428*/
79429static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
79430  if( p ){
79431    TriggerStep *pStep = p->step_list;
79432    sqlite3ExprDelete(dbMem, pStep->pWhere);
79433    sqlite3ExprListDelete(dbMem, pStep->pExprList);
79434    sqlite3SelectDelete(dbMem, pStep->pSelect);
79435    sqlite3ExprDelete(dbMem, p->pWhen);
79436    sqlite3DbFree(dbMem, p);
79437  }
79438}
79439
79440/*
79441** This function is called to generate code that runs when table pTab is
79442** being dropped from the database. The SrcList passed as the second argument
79443** to this function contains a single entry guaranteed to resolve to
79444** table pTab.
79445**
79446** Normally, no code is required. However, if either
79447**
79448**   (a) The table is the parent table of a FK constraint, or
79449**   (b) The table is the child table of a deferred FK constraint and it is
79450**       determined at runtime that there are outstanding deferred FK
79451**       constraint violations in the database,
79452**
79453** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
79454** the table from the database. Triggers are disabled while running this
79455** DELETE, but foreign key actions are not.
79456*/
79457SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
79458  sqlite3 *db = pParse->db;
79459  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
79460    int iSkip = 0;
79461    Vdbe *v = sqlite3GetVdbe(pParse);
79462
79463    assert( v );                  /* VDBE has already been allocated */
79464    if( sqlite3FkReferences(pTab)==0 ){
79465      /* Search for a deferred foreign key constraint for which this table
79466      ** is the child table. If one cannot be found, return without
79467      ** generating any VDBE code. If one can be found, then jump over
79468      ** the entire DELETE if there are no outstanding deferred constraints
79469      ** when this statement is run.  */
79470      FKey *p;
79471      for(p=pTab->pFKey; p; p=p->pNextFrom){
79472        if( p->isDeferred ) break;
79473      }
79474      if( !p ) return;
79475      iSkip = sqlite3VdbeMakeLabel(v);
79476      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
79477    }
79478
79479    pParse->disableTriggers = 1;
79480    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
79481    pParse->disableTriggers = 0;
79482
79483    /* If the DELETE has generated immediate foreign key constraint
79484    ** violations, halt the VDBE and return an error at this point, before
79485    ** any modifications to the schema are made. This is because statement
79486    ** transactions are not able to rollback schema changes.  */
79487    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
79488    sqlite3HaltConstraint(
79489        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79490    );
79491
79492    if( iSkip ){
79493      sqlite3VdbeResolveLabel(v, iSkip);
79494    }
79495  }
79496}
79497
79498/*
79499** This function is called when inserting, deleting or updating a row of
79500** table pTab to generate VDBE code to perform foreign key constraint
79501** processing for the operation.
79502**
79503** For a DELETE operation, parameter regOld is passed the index of the
79504** first register in an array of (pTab->nCol+1) registers containing the
79505** rowid of the row being deleted, followed by each of the column values
79506** of the row being deleted, from left to right. Parameter regNew is passed
79507** zero in this case.
79508**
79509** For an INSERT operation, regOld is passed zero and regNew is passed the
79510** first register of an array of (pTab->nCol+1) registers containing the new
79511** row data.
79512**
79513** For an UPDATE operation, this function is called twice. Once before
79514** the original record is deleted from the table using the calling convention
79515** described for DELETE. Then again after the original record is deleted
79516** but before the new record is inserted using the INSERT convention.
79517*/
79518SQLITE_PRIVATE void sqlite3FkCheck(
79519  Parse *pParse,                  /* Parse context */
79520  Table *pTab,                    /* Row is being deleted from this table */
79521  int regOld,                     /* Previous row data is stored here */
79522  int regNew                      /* New row data is stored here */
79523){
79524  sqlite3 *db = pParse->db;       /* Database handle */
79525  Vdbe *v;                        /* VM to write code to */
79526  FKey *pFKey;                    /* Used to iterate through FKs */
79527  int iDb;                        /* Index of database containing pTab */
79528  const char *zDb;                /* Name of database containing pTab */
79529  int isIgnoreErrors = pParse->disableTriggers;
79530
79531  /* Exactly one of regOld and regNew should be non-zero. */
79532  assert( (regOld==0)!=(regNew==0) );
79533
79534  /* If foreign-keys are disabled, this function is a no-op. */
79535  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
79536
79537  v = sqlite3GetVdbe(pParse);
79538  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79539  zDb = db->aDb[iDb].zName;
79540
79541  /* Loop through all the foreign key constraints for which pTab is the
79542  ** child table (the table that the foreign key definition is part of).  */
79543  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
79544    Table *pTo;                   /* Parent table of foreign key pFKey */
79545    Index *pIdx = 0;              /* Index on key columns in pTo */
79546    int *aiFree = 0;
79547    int *aiCol;
79548    int iCol;
79549    int i;
79550    int isIgnore = 0;
79551
79552    /* Find the parent table of this foreign key. Also find a unique index
79553    ** on the parent key columns in the parent table. If either of these
79554    ** schema items cannot be located, set an error in pParse and return
79555    ** early.  */
79556    if( pParse->disableTriggers ){
79557      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
79558    }else{
79559      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
79560    }
79561    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
79562      if( !isIgnoreErrors || db->mallocFailed ) return;
79563      continue;
79564    }
79565    assert( pFKey->nCol==1 || (aiFree && pIdx) );
79566
79567    if( aiFree ){
79568      aiCol = aiFree;
79569    }else{
79570      iCol = pFKey->aCol[0].iFrom;
79571      aiCol = &iCol;
79572    }
79573    for(i=0; i<pFKey->nCol; i++){
79574      if( aiCol[i]==pTab->iPKey ){
79575        aiCol[i] = -1;
79576      }
79577#ifndef SQLITE_OMIT_AUTHORIZATION
79578      /* Request permission to read the parent key columns. If the
79579      ** authorization callback returns SQLITE_IGNORE, behave as if any
79580      ** values read from the parent table are NULL. */
79581      if( db->xAuth ){
79582        int rcauth;
79583        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
79584        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
79585        isIgnore = (rcauth==SQLITE_IGNORE);
79586      }
79587#endif
79588    }
79589
79590    /* Take a shared-cache advisory read-lock on the parent table. Allocate
79591    ** a cursor to use to search the unique index on the parent key columns
79592    ** in the parent table.  */
79593    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
79594    pParse->nTab++;
79595
79596    if( regOld!=0 ){
79597      /* A row is being removed from the child table. Search for the parent.
79598      ** If the parent does not exist, removing the child row resolves an
79599      ** outstanding foreign key constraint violation. */
79600      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
79601    }
79602    if( regNew!=0 ){
79603      /* A row is being added to the child table. If a parent row cannot
79604      ** be found, adding the child row has violated the FK constraint. */
79605      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
79606    }
79607
79608    sqlite3DbFree(db, aiFree);
79609  }
79610
79611  /* Loop through all the foreign key constraints that refer to this table */
79612  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
79613    Index *pIdx = 0;              /* Foreign key index for pFKey */
79614    SrcList *pSrc;
79615    int *aiCol = 0;
79616
79617    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79618      assert( regOld==0 && regNew!=0 );
79619      /* Inserting a single row into a parent table cannot cause an immediate
79620      ** foreign key violation. So do nothing in this case.  */
79621      continue;
79622    }
79623
79624    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
79625      if( !isIgnoreErrors || db->mallocFailed ) return;
79626      continue;
79627    }
79628    assert( aiCol || pFKey->nCol==1 );
79629
79630    /* Create a SrcList structure containing a single table (the table
79631    ** the foreign key that refers to this table is attached to). This
79632    ** is required for the sqlite3WhereXXX() interface.  */
79633    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
79634    if( pSrc ){
79635      struct SrcList_item *pItem = pSrc->a;
79636      pItem->pTab = pFKey->pFrom;
79637      pItem->zName = pFKey->pFrom->zName;
79638      pItem->pTab->nRef++;
79639      pItem->iCursor = pParse->nTab++;
79640
79641      if( regNew!=0 ){
79642        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
79643      }
79644      if( regOld!=0 ){
79645        /* If there is a RESTRICT action configured for the current operation
79646        ** on the parent table of this FK, then throw an exception
79647        ** immediately if the FK constraint is violated, even if this is a
79648        ** deferred trigger. That's what RESTRICT means. To defer checking
79649        ** the constraint, the FK should specify NO ACTION (represented
79650        ** using OE_None). NO ACTION is the default.  */
79651        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
79652      }
79653      pItem->zName = 0;
79654      sqlite3SrcListDelete(db, pSrc);
79655    }
79656    sqlite3DbFree(db, aiCol);
79657  }
79658}
79659
79660#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
79661
79662/*
79663** This function is called before generating code to update or delete a
79664** row contained in table pTab.
79665*/
79666SQLITE_PRIVATE u32 sqlite3FkOldmask(
79667  Parse *pParse,                  /* Parse context */
79668  Table *pTab                     /* Table being modified */
79669){
79670  u32 mask = 0;
79671  if( pParse->db->flags&SQLITE_ForeignKeys ){
79672    FKey *p;
79673    int i;
79674    for(p=pTab->pFKey; p; p=p->pNextFrom){
79675      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
79676    }
79677    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79678      Index *pIdx = 0;
79679      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
79680      if( pIdx ){
79681        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
79682      }
79683    }
79684  }
79685  return mask;
79686}
79687
79688/*
79689** This function is called before generating code to update or delete a
79690** row contained in table pTab. If the operation is a DELETE, then
79691** parameter aChange is passed a NULL value. For an UPDATE, aChange points
79692** to an array of size N, where N is the number of columns in table pTab.
79693** If the i'th column is not modified by the UPDATE, then the corresponding
79694** entry in the aChange[] array is set to -1. If the column is modified,
79695** the value is 0 or greater. Parameter chngRowid is set to true if the
79696** UPDATE statement modifies the rowid fields of the table.
79697**
79698** If any foreign key processing will be required, this function returns
79699** true. If there is no foreign key related processing, this function
79700** returns false.
79701*/
79702SQLITE_PRIVATE int sqlite3FkRequired(
79703  Parse *pParse,                  /* Parse context */
79704  Table *pTab,                    /* Table being modified */
79705  int *aChange,                   /* Non-NULL for UPDATE operations */
79706  int chngRowid                   /* True for UPDATE that affects rowid */
79707){
79708  if( pParse->db->flags&SQLITE_ForeignKeys ){
79709    if( !aChange ){
79710      /* A DELETE operation. Foreign key processing is required if the
79711      ** table in question is either the child or parent table for any
79712      ** foreign key constraint.  */
79713      return (sqlite3FkReferences(pTab) || pTab->pFKey);
79714    }else{
79715      /* This is an UPDATE. Foreign key processing is only required if the
79716      ** operation modifies one or more child or parent key columns. */
79717      int i;
79718      FKey *p;
79719
79720      /* Check if any child key columns are being modified. */
79721      for(p=pTab->pFKey; p; p=p->pNextFrom){
79722        for(i=0; i<p->nCol; i++){
79723          int iChildKey = p->aCol[i].iFrom;
79724          if( aChange[iChildKey]>=0 ) return 1;
79725          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
79726        }
79727      }
79728
79729      /* Check if any parent key columns are being modified. */
79730      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79731        for(i=0; i<p->nCol; i++){
79732          char *zKey = p->aCol[i].zCol;
79733          int iKey;
79734          for(iKey=0; iKey<pTab->nCol; iKey++){
79735            Column *pCol = &pTab->aCol[iKey];
79736            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
79737              if( aChange[iKey]>=0 ) return 1;
79738              if( iKey==pTab->iPKey && chngRowid ) return 1;
79739            }
79740          }
79741        }
79742      }
79743    }
79744  }
79745  return 0;
79746}
79747
79748/*
79749** This function is called when an UPDATE or DELETE operation is being
79750** compiled on table pTab, which is the parent table of foreign-key pFKey.
79751** If the current operation is an UPDATE, then the pChanges parameter is
79752** passed a pointer to the list of columns being modified. If it is a
79753** DELETE, pChanges is passed a NULL pointer.
79754**
79755** It returns a pointer to a Trigger structure containing a trigger
79756** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
79757** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
79758** returned (these actions require no special handling by the triggers
79759** sub-system, code for them is created by fkScanChildren()).
79760**
79761** For example, if pFKey is the foreign key and pTab is table "p" in
79762** the following schema:
79763**
79764**   CREATE TABLE p(pk PRIMARY KEY);
79765**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
79766**
79767** then the returned trigger structure is equivalent to:
79768**
79769**   CREATE TRIGGER ... DELETE ON p BEGIN
79770**     DELETE FROM c WHERE ck = old.pk;
79771**   END;
79772**
79773** The returned pointer is cached as part of the foreign key object. It
79774** is eventually freed along with the rest of the foreign key object by
79775** sqlite3FkDelete().
79776*/
79777static Trigger *fkActionTrigger(
79778  Parse *pParse,                  /* Parse context */
79779  Table *pTab,                    /* Table being updated or deleted from */
79780  FKey *pFKey,                    /* Foreign key to get action for */
79781  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
79782){
79783  sqlite3 *db = pParse->db;       /* Database handle */
79784  int action;                     /* One of OE_None, OE_Cascade etc. */
79785  Trigger *pTrigger;              /* Trigger definition to return */
79786  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
79787
79788  action = pFKey->aAction[iAction];
79789  pTrigger = pFKey->apTrigger[iAction];
79790
79791  if( action!=OE_None && !pTrigger ){
79792    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
79793    char const *zFrom;            /* Name of child table */
79794    int nFrom;                    /* Length in bytes of zFrom */
79795    Index *pIdx = 0;              /* Parent key index for this FK */
79796    int *aiCol = 0;               /* child table cols -> parent key cols */
79797    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
79798    Expr *pWhere = 0;             /* WHERE clause of trigger step */
79799    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
79800    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
79801    int i;                        /* Iterator variable */
79802    Expr *pWhen = 0;              /* WHEN clause for the trigger */
79803
79804    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
79805    assert( aiCol || pFKey->nCol==1 );
79806
79807    for(i=0; i<pFKey->nCol; i++){
79808      Token tOld = { "old", 3 };  /* Literal "old" token */
79809      Token tNew = { "new", 3 };  /* Literal "new" token */
79810      Token tFromCol;             /* Name of column in child table */
79811      Token tToCol;               /* Name of column in parent table */
79812      int iFromCol;               /* Idx of column in child table */
79813      Expr *pEq;                  /* tFromCol = OLD.tToCol */
79814
79815      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
79816      assert( iFromCol>=0 );
79817      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
79818      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
79819
79820      tToCol.n = sqlite3Strlen30(tToCol.z);
79821      tFromCol.n = sqlite3Strlen30(tFromCol.z);
79822
79823      /* Create the expression "OLD.zToCol = zFromCol". It is important
79824      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
79825      ** that the affinity and collation sequence associated with the
79826      ** parent table are used for the comparison. */
79827      pEq = sqlite3PExpr(pParse, TK_EQ,
79828          sqlite3PExpr(pParse, TK_DOT,
79829            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
79830            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
79831          , 0),
79832          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
79833      , 0);
79834      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79835
79836      /* For ON UPDATE, construct the next term of the WHEN clause.
79837      ** The final WHEN clause will be like this:
79838      **
79839      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
79840      */
79841      if( pChanges ){
79842        pEq = sqlite3PExpr(pParse, TK_IS,
79843            sqlite3PExpr(pParse, TK_DOT,
79844              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
79845              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
79846              0),
79847            sqlite3PExpr(pParse, TK_DOT,
79848              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
79849              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
79850              0),
79851            0);
79852        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
79853      }
79854
79855      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
79856        Expr *pNew;
79857        if( action==OE_Cascade ){
79858          pNew = sqlite3PExpr(pParse, TK_DOT,
79859            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
79860            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
79861          , 0);
79862        }else if( action==OE_SetDflt ){
79863          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
79864          if( pDflt ){
79865            pNew = sqlite3ExprDup(db, pDflt, 0);
79866          }else{
79867            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
79868          }
79869        }else{
79870          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
79871        }
79872        pList = sqlite3ExprListAppend(pParse, pList, pNew);
79873        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
79874      }
79875    }
79876    sqlite3DbFree(db, aiCol);
79877
79878    zFrom = pFKey->pFrom->zName;
79879    nFrom = sqlite3Strlen30(zFrom);
79880
79881    if( action==OE_Restrict ){
79882      Token tFrom;
79883      Expr *pRaise;
79884
79885      tFrom.z = zFrom;
79886      tFrom.n = nFrom;
79887      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
79888      if( pRaise ){
79889        pRaise->affinity = OE_Abort;
79890      }
79891      pSelect = sqlite3SelectNew(pParse,
79892          sqlite3ExprListAppend(pParse, 0, pRaise),
79893          sqlite3SrcListAppend(db, 0, &tFrom, 0),
79894          pWhere,
79895          0, 0, 0, 0, 0, 0
79896      );
79897      pWhere = 0;
79898    }
79899
79900    /* In the current implementation, pTab->dbMem==0 for all tables except
79901    ** for temporary tables used to describe subqueries.  And temporary
79902    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
79903    ** should always be 0 there.
79904    */
79905    enableLookaside = db->lookaside.bEnabled;
79906    db->lookaside.bEnabled = 0;
79907
79908    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
79909        sizeof(Trigger) +         /* struct Trigger */
79910        sizeof(TriggerStep) +     /* Single step in trigger program */
79911        nFrom + 1                 /* Space for pStep->target.z */
79912    );
79913    if( pTrigger ){
79914      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
79915      pStep->target.z = (char *)&pStep[1];
79916      pStep->target.n = nFrom;
79917      memcpy((char *)pStep->target.z, zFrom, nFrom);
79918
79919      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
79920      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
79921      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
79922      if( pWhen ){
79923        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
79924        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
79925      }
79926    }
79927
79928    /* Re-enable the lookaside buffer, if it was disabled earlier. */
79929    db->lookaside.bEnabled = enableLookaside;
79930
79931    sqlite3ExprDelete(db, pWhere);
79932    sqlite3ExprDelete(db, pWhen);
79933    sqlite3ExprListDelete(db, pList);
79934    sqlite3SelectDelete(db, pSelect);
79935    if( db->mallocFailed==1 ){
79936      fkTriggerDelete(db, pTrigger);
79937      return 0;
79938    }
79939
79940    switch( action ){
79941      case OE_Restrict:
79942        pStep->op = TK_SELECT;
79943        break;
79944      case OE_Cascade:
79945        if( !pChanges ){
79946          pStep->op = TK_DELETE;
79947          break;
79948        }
79949      default:
79950        pStep->op = TK_UPDATE;
79951    }
79952    pStep->pTrig = pTrigger;
79953    pTrigger->pSchema = pTab->pSchema;
79954    pTrigger->pTabSchema = pTab->pSchema;
79955    pFKey->apTrigger[iAction] = pTrigger;
79956    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
79957  }
79958
79959  return pTrigger;
79960}
79961
79962/*
79963** This function is called when deleting or updating a row to implement
79964** any required CASCADE, SET NULL or SET DEFAULT actions.
79965*/
79966SQLITE_PRIVATE void sqlite3FkActions(
79967  Parse *pParse,                  /* Parse context */
79968  Table *pTab,                    /* Table being updated or deleted from */
79969  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
79970  int regOld                      /* Address of array containing old row */
79971){
79972  /* If foreign-key support is enabled, iterate through all FKs that
79973  ** refer to table pTab. If there is an action associated with the FK
79974  ** for this operation (either update or delete), invoke the associated
79975  ** trigger sub-program.  */
79976  if( pParse->db->flags&SQLITE_ForeignKeys ){
79977    FKey *pFKey;                  /* Iterator variable */
79978    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
79979      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
79980      if( pAction ){
79981        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
79982      }
79983    }
79984  }
79985}
79986
79987#endif /* ifndef SQLITE_OMIT_TRIGGER */
79988
79989/*
79990** Free all memory associated with foreign key definitions attached to
79991** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
79992** hash table.
79993*/
79994SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
79995  FKey *pFKey;                    /* Iterator variable */
79996  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
79997
79998  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
79999
80000    /* Remove the FK from the fkeyHash hash table. */
80001    if( pFKey->pPrevTo ){
80002      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
80003    }else{
80004      void *data = (void *)pFKey->pNextTo;
80005      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
80006      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
80007    }
80008    if( pFKey->pNextTo ){
80009      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
80010    }
80011
80012    /* Delete any triggers created to implement actions for this FK. */
80013#ifndef SQLITE_OMIT_TRIGGER
80014    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
80015    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
80016#endif
80017
80018    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
80019    ** classified as either immediate or deferred.
80020    */
80021    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
80022
80023    pNext = pFKey->pNextFrom;
80024    sqlite3DbFree(pTab->dbMem, pFKey);
80025  }
80026}
80027#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
80028
80029/************** End of fkey.c ************************************************/
80030/************** Begin file insert.c ******************************************/
80031/*
80032** 2001 September 15
80033**
80034** The author disclaims copyright to this source code.  In place of
80035** a legal notice, here is a blessing:
80036**
80037**    May you do good and not evil.
80038**    May you find forgiveness for yourself and forgive others.
80039**    May you share freely, never taking more than you give.
80040**
80041*************************************************************************
80042** This file contains C code routines that are called by the parser
80043** to handle INSERT statements in SQLite.
80044*/
80045
80046/*
80047** Generate code that will open a table for reading.
80048*/
80049SQLITE_PRIVATE void sqlite3OpenTable(
80050  Parse *p,       /* Generate code into this VDBE */
80051  int iCur,       /* The cursor number of the table */
80052  int iDb,        /* The database index in sqlite3.aDb[] */
80053  Table *pTab,    /* The table to be opened */
80054  int opcode      /* OP_OpenRead or OP_OpenWrite */
80055){
80056  Vdbe *v;
80057  if( IsVirtual(pTab) ) return;
80058  v = sqlite3GetVdbe(p);
80059  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
80060  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
80061  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
80062  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
80063  VdbeComment((v, "%s", pTab->zName));
80064}
80065
80066/*
80067** Return a pointer to the column affinity string associated with index
80068** pIdx. A column affinity string has one character for each column in
80069** the table, according to the affinity of the column:
80070**
80071**  Character      Column affinity
80072**  ------------------------------
80073**  'a'            TEXT
80074**  'b'            NONE
80075**  'c'            NUMERIC
80076**  'd'            INTEGER
80077**  'e'            REAL
80078**
80079** An extra 'b' is appended to the end of the string to cover the
80080** rowid that appears as the last column in every index.
80081**
80082** Memory for the buffer containing the column index affinity string
80083** is managed along with the rest of the Index structure. It will be
80084** released when sqlite3DeleteIndex() is called.
80085*/
80086SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
80087  if( !pIdx->zColAff ){
80088    /* The first time a column affinity string for a particular index is
80089    ** required, it is allocated and populated here. It is then stored as
80090    ** a member of the Index structure for subsequent use.
80091    **
80092    ** The column affinity string will eventually be deleted by
80093    ** sqliteDeleteIndex() when the Index structure itself is cleaned
80094    ** up.
80095    */
80096    int n;
80097    Table *pTab = pIdx->pTable;
80098    sqlite3 *db = sqlite3VdbeDb(v);
80099    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
80100    if( !pIdx->zColAff ){
80101      db->mallocFailed = 1;
80102      return 0;
80103    }
80104    for(n=0; n<pIdx->nColumn; n++){
80105      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
80106    }
80107    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
80108    pIdx->zColAff[n] = 0;
80109  }
80110
80111  return pIdx->zColAff;
80112}
80113
80114/*
80115** Set P4 of the most recently inserted opcode to a column affinity
80116** string for table pTab. A column affinity string has one character
80117** for each column indexed by the index, according to the affinity of the
80118** column:
80119**
80120**  Character      Column affinity
80121**  ------------------------------
80122**  'a'            TEXT
80123**  'b'            NONE
80124**  'c'            NUMERIC
80125**  'd'            INTEGER
80126**  'e'            REAL
80127*/
80128SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
80129  /* The first time a column affinity string for a particular table
80130  ** is required, it is allocated and populated here. It is then
80131  ** stored as a member of the Table structure for subsequent use.
80132  **
80133  ** The column affinity string will eventually be deleted by
80134  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
80135  */
80136  if( !pTab->zColAff ){
80137    char *zColAff;
80138    int i;
80139    sqlite3 *db = sqlite3VdbeDb(v);
80140
80141    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
80142    if( !zColAff ){
80143      db->mallocFailed = 1;
80144      return;
80145    }
80146
80147    for(i=0; i<pTab->nCol; i++){
80148      zColAff[i] = pTab->aCol[i].affinity;
80149    }
80150    zColAff[pTab->nCol] = '\0';
80151
80152    pTab->zColAff = zColAff;
80153  }
80154
80155  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
80156}
80157
80158/*
80159** Return non-zero if the table pTab in database iDb or any of its indices
80160** have been opened at any point in the VDBE program beginning at location
80161** iStartAddr throught the end of the program.  This is used to see if
80162** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
80163** run without using temporary table for the results of the SELECT.
80164*/
80165static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
80166  Vdbe *v = sqlite3GetVdbe(p);
80167  int i;
80168  int iEnd = sqlite3VdbeCurrentAddr(v);
80169#ifndef SQLITE_OMIT_VIRTUALTABLE
80170  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
80171#endif
80172
80173  for(i=iStartAddr; i<iEnd; i++){
80174    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
80175    assert( pOp!=0 );
80176    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
80177      Index *pIndex;
80178      int tnum = pOp->p2;
80179      if( tnum==pTab->tnum ){
80180        return 1;
80181      }
80182      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80183        if( tnum==pIndex->tnum ){
80184          return 1;
80185        }
80186      }
80187    }
80188#ifndef SQLITE_OMIT_VIRTUALTABLE
80189    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
80190      assert( pOp->p4.pVtab!=0 );
80191      assert( pOp->p4type==P4_VTAB );
80192      return 1;
80193    }
80194#endif
80195  }
80196  return 0;
80197}
80198
80199#ifndef SQLITE_OMIT_AUTOINCREMENT
80200/*
80201** Locate or create an AutoincInfo structure associated with table pTab
80202** which is in database iDb.  Return the register number for the register
80203** that holds the maximum rowid.
80204**
80205** There is at most one AutoincInfo structure per table even if the
80206** same table is autoincremented multiple times due to inserts within
80207** triggers.  A new AutoincInfo structure is created if this is the
80208** first use of table pTab.  On 2nd and subsequent uses, the original
80209** AutoincInfo structure is used.
80210**
80211** Three memory locations are allocated:
80212**
80213**   (1)  Register to hold the name of the pTab table.
80214**   (2)  Register to hold the maximum ROWID of pTab.
80215**   (3)  Register to hold the rowid in sqlite_sequence of pTab
80216**
80217** The 2nd register is the one that is returned.  That is all the
80218** insert routine needs to know about.
80219*/
80220static int autoIncBegin(
80221  Parse *pParse,      /* Parsing context */
80222  int iDb,            /* Index of the database holding pTab */
80223  Table *pTab         /* The table we are writing to */
80224){
80225  int memId = 0;      /* Register holding maximum rowid */
80226  if( pTab->tabFlags & TF_Autoincrement ){
80227    Parse *pToplevel = sqlite3ParseToplevel(pParse);
80228    AutoincInfo *pInfo;
80229
80230    pInfo = pToplevel->pAinc;
80231    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
80232    if( pInfo==0 ){
80233      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
80234      if( pInfo==0 ) return 0;
80235      pInfo->pNext = pToplevel->pAinc;
80236      pToplevel->pAinc = pInfo;
80237      pInfo->pTab = pTab;
80238      pInfo->iDb = iDb;
80239      pToplevel->nMem++;                  /* Register to hold name of table */
80240      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
80241      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
80242    }
80243    memId = pInfo->regCtr;
80244  }
80245  return memId;
80246}
80247
80248/*
80249** This routine generates code that will initialize all of the
80250** register used by the autoincrement tracker.
80251*/
80252SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
80253  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
80254  sqlite3 *db = pParse->db;  /* The database connection */
80255  Db *pDb;                   /* Database only autoinc table */
80256  int memId;                 /* Register holding max rowid */
80257  int addr;                  /* A VDBE address */
80258  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
80259
80260  /* This routine is never called during trigger-generation.  It is
80261  ** only called from the top-level */
80262  assert( pParse->pTriggerTab==0 );
80263  assert( pParse==sqlite3ParseToplevel(pParse) );
80264
80265  assert( v );   /* We failed long ago if this is not so */
80266  for(p = pParse->pAinc; p; p = p->pNext){
80267    pDb = &db->aDb[p->iDb];
80268    memId = p->regCtr;
80269    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
80270    addr = sqlite3VdbeCurrentAddr(v);
80271    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
80272    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
80273    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
80274    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
80275    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
80276    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80277    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
80278    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
80279    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
80280    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
80281    sqlite3VdbeAddOp0(v, OP_Close);
80282  }
80283}
80284
80285/*
80286** Update the maximum rowid for an autoincrement calculation.
80287**
80288** This routine should be called when the top of the stack holds a
80289** new rowid that is about to be inserted.  If that new rowid is
80290** larger than the maximum rowid in the memId memory cell, then the
80291** memory cell is updated.  The stack is unchanged.
80292*/
80293static void autoIncStep(Parse *pParse, int memId, int regRowid){
80294  if( memId>0 ){
80295    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
80296  }
80297}
80298
80299/*
80300** This routine generates the code needed to write autoincrement
80301** maximum rowid values back into the sqlite_sequence register.
80302** Every statement that might do an INSERT into an autoincrement
80303** table (either directly or through triggers) needs to call this
80304** routine just before the "exit" code.
80305*/
80306SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
80307  AutoincInfo *p;
80308  Vdbe *v = pParse->pVdbe;
80309  sqlite3 *db = pParse->db;
80310
80311  assert( v );
80312  for(p = pParse->pAinc; p; p = p->pNext){
80313    Db *pDb = &db->aDb[p->iDb];
80314    int j1, j2, j3, j4, j5;
80315    int iRec;
80316    int memId = p->regCtr;
80317
80318    iRec = sqlite3GetTempReg(pParse);
80319    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
80320    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
80321    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
80322    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
80323    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
80324    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
80325    sqlite3VdbeJumpHere(v, j2);
80326    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
80327    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
80328    sqlite3VdbeJumpHere(v, j4);
80329    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80330    sqlite3VdbeJumpHere(v, j1);
80331    sqlite3VdbeJumpHere(v, j5);
80332    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
80333    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
80334    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80335    sqlite3VdbeAddOp0(v, OP_Close);
80336    sqlite3ReleaseTempReg(pParse, iRec);
80337  }
80338}
80339#else
80340/*
80341** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
80342** above are all no-ops
80343*/
80344# define autoIncBegin(A,B,C) (0)
80345# define autoIncStep(A,B,C)
80346#endif /* SQLITE_OMIT_AUTOINCREMENT */
80347
80348
80349/* Forward declaration */
80350static int xferOptimization(
80351  Parse *pParse,        /* Parser context */
80352  Table *pDest,         /* The table we are inserting into */
80353  Select *pSelect,      /* A SELECT statement to use as the data source */
80354  int onError,          /* How to handle constraint errors */
80355  int iDbDest           /* The database of pDest */
80356);
80357
80358/*
80359** This routine is call to handle SQL of the following forms:
80360**
80361**    insert into TABLE (IDLIST) values(EXPRLIST)
80362**    insert into TABLE (IDLIST) select
80363**
80364** The IDLIST following the table name is always optional.  If omitted,
80365** then a list of all columns for the table is substituted.  The IDLIST
80366** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
80367**
80368** The pList parameter holds EXPRLIST in the first form of the INSERT
80369** statement above, and pSelect is NULL.  For the second form, pList is
80370** NULL and pSelect is a pointer to the select statement used to generate
80371** data for the insert.
80372**
80373** The code generated follows one of four templates.  For a simple
80374** select with data coming from a VALUES clause, the code executes
80375** once straight down through.  Pseudo-code follows (we call this
80376** the "1st template"):
80377**
80378**         open write cursor to <table> and its indices
80379**         puts VALUES clause expressions onto the stack
80380**         write the resulting record into <table>
80381**         cleanup
80382**
80383** The three remaining templates assume the statement is of the form
80384**
80385**   INSERT INTO <table> SELECT ...
80386**
80387** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
80388** in other words if the SELECT pulls all columns from a single table
80389** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
80390** if <table2> and <table1> are distinct tables but have identical
80391** schemas, including all the same indices, then a special optimization
80392** is invoked that copies raw records from <table2> over to <table1>.
80393** See the xferOptimization() function for the implementation of this
80394** template.  This is the 2nd template.
80395**
80396**         open a write cursor to <table>
80397**         open read cursor on <table2>
80398**         transfer all records in <table2> over to <table>
80399**         close cursors
80400**         foreach index on <table>
80401**           open a write cursor on the <table> index
80402**           open a read cursor on the corresponding <table2> index
80403**           transfer all records from the read to the write cursors
80404**           close cursors
80405**         end foreach
80406**
80407** The 3rd template is for when the second template does not apply
80408** and the SELECT clause does not read from <table> at any time.
80409** The generated code follows this template:
80410**
80411**         EOF <- 0
80412**         X <- A
80413**         goto B
80414**      A: setup for the SELECT
80415**         loop over the rows in the SELECT
80416**           load values into registers R..R+n
80417**           yield X
80418**         end loop
80419**         cleanup after the SELECT
80420**         EOF <- 1
80421**         yield X
80422**         goto A
80423**      B: open write cursor to <table> and its indices
80424**      C: yield X
80425**         if EOF goto D
80426**         insert the select result into <table> from R..R+n
80427**         goto C
80428**      D: cleanup
80429**
80430** The 4th template is used if the insert statement takes its
80431** values from a SELECT but the data is being inserted into a table
80432** that is also read as part of the SELECT.  In the third form,
80433** we have to use a intermediate table to store the results of
80434** the select.  The template is like this:
80435**
80436**         EOF <- 0
80437**         X <- A
80438**         goto B
80439**      A: setup for the SELECT
80440**         loop over the tables in the SELECT
80441**           load value into register R..R+n
80442**           yield X
80443**         end loop
80444**         cleanup after the SELECT
80445**         EOF <- 1
80446**         yield X
80447**         halt-error
80448**      B: open temp table
80449**      L: yield X
80450**         if EOF goto M
80451**         insert row from R..R+n into temp table
80452**         goto L
80453**      M: open write cursor to <table> and its indices
80454**         rewind temp table
80455**      C: loop over rows of intermediate table
80456**           transfer values form intermediate table into <table>
80457**         end loop
80458**      D: cleanup
80459*/
80460SQLITE_PRIVATE void sqlite3Insert(
80461  Parse *pParse,        /* Parser context */
80462  SrcList *pTabList,    /* Name of table into which we are inserting */
80463  ExprList *pList,      /* List of values to be inserted */
80464  Select *pSelect,      /* A SELECT statement to use as the data source */
80465  IdList *pColumn,      /* Column names corresponding to IDLIST. */
80466  int onError           /* How to handle constraint errors */
80467){
80468  sqlite3 *db;          /* The main database structure */
80469  Table *pTab;          /* The table to insert into.  aka TABLE */
80470  char *zTab;           /* Name of the table into which we are inserting */
80471  const char *zDb;      /* Name of the database holding this table */
80472  int i, j, idx;        /* Loop counters */
80473  Vdbe *v;              /* Generate code into this virtual machine */
80474  Index *pIdx;          /* For looping over indices of the table */
80475  int nColumn;          /* Number of columns in the data */
80476  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
80477  int baseCur = 0;      /* VDBE Cursor number for pTab */
80478  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
80479  int endOfLoop;        /* Label for the end of the insertion loop */
80480  int useTempTable = 0; /* Store SELECT results in intermediate table */
80481  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
80482  int addrInsTop = 0;   /* Jump to label "D" */
80483  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
80484  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
80485  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
80486  int iDb;              /* Index of database holding TABLE */
80487  Db *pDb;              /* The database containing table being inserted into */
80488  int appendFlag = 0;   /* True if the insert is likely to be an append */
80489
80490  /* Register allocations */
80491  int regFromSelect = 0;/* Base register for data coming from SELECT */
80492  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
80493  int regRowCount = 0;  /* Memory cell used for the row counter */
80494  int regIns;           /* Block of regs holding rowid+data being inserted */
80495  int regRowid;         /* registers holding insert rowid */
80496  int regData;          /* register holding first column to insert */
80497  int regRecord;        /* Holds the assemblied row record */
80498  int regEof = 0;       /* Register recording end of SELECT data */
80499  int *aRegIdx = 0;     /* One register allocated to each index */
80500
80501#ifndef SQLITE_OMIT_TRIGGER
80502  int isView;                 /* True if attempting to insert into a view */
80503  Trigger *pTrigger;          /* List of triggers on pTab, if required */
80504  int tmask;                  /* Mask of trigger times */
80505#endif
80506
80507  db = pParse->db;
80508  memset(&dest, 0, sizeof(dest));
80509  if( pParse->nErr || db->mallocFailed ){
80510    goto insert_cleanup;
80511  }
80512
80513  /* Locate the table into which we will be inserting new information.
80514  */
80515  assert( pTabList->nSrc==1 );
80516  zTab = pTabList->a[0].zName;
80517  if( NEVER(zTab==0) ) goto insert_cleanup;
80518  pTab = sqlite3SrcListLookup(pParse, pTabList);
80519  if( pTab==0 ){
80520    goto insert_cleanup;
80521  }
80522  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80523  assert( iDb<db->nDb );
80524  pDb = &db->aDb[iDb];
80525  zDb = pDb->zName;
80526  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
80527    goto insert_cleanup;
80528  }
80529
80530  /* Figure out if we have any triggers and if the table being
80531  ** inserted into is a view
80532  */
80533#ifndef SQLITE_OMIT_TRIGGER
80534  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
80535  isView = pTab->pSelect!=0;
80536#else
80537# define pTrigger 0
80538# define tmask 0
80539# define isView 0
80540#endif
80541#ifdef SQLITE_OMIT_VIEW
80542# undef isView
80543# define isView 0
80544#endif
80545  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
80546
80547  /* If pTab is really a view, make sure it has been initialized.
80548  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
80549  ** module table).
80550  */
80551  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
80552    goto insert_cleanup;
80553  }
80554
80555  /* Ensure that:
80556  *  (a) the table is not read-only,
80557  *  (b) that if it is a view then ON INSERT triggers exist
80558  */
80559  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
80560    goto insert_cleanup;
80561  }
80562
80563  /* Allocate a VDBE
80564  */
80565  v = sqlite3GetVdbe(pParse);
80566  if( v==0 ) goto insert_cleanup;
80567  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
80568  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
80569
80570#ifndef SQLITE_OMIT_XFER_OPT
80571  /* If the statement is of the form
80572  **
80573  **       INSERT INTO <table1> SELECT * FROM <table2>;
80574  **
80575  ** Then special optimizations can be applied that make the transfer
80576  ** very fast and which reduce fragmentation of indices.
80577  **
80578  ** This is the 2nd template.
80579  */
80580  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
80581    assert( !pTrigger );
80582    assert( pList==0 );
80583    goto insert_end;
80584  }
80585#endif /* SQLITE_OMIT_XFER_OPT */
80586
80587  /* If this is an AUTOINCREMENT table, look up the sequence number in the
80588  ** sqlite_sequence table and store it in memory cell regAutoinc.
80589  */
80590  regAutoinc = autoIncBegin(pParse, iDb, pTab);
80591
80592  /* Figure out how many columns of data are supplied.  If the data
80593  ** is coming from a SELECT statement, then generate a co-routine that
80594  ** produces a single row of the SELECT on each invocation.  The
80595  ** co-routine is the common header to the 3rd and 4th templates.
80596  */
80597  if( pSelect ){
80598    /* Data is coming from a SELECT.  Generate code to implement that SELECT
80599    ** as a co-routine.  The code is common to both the 3rd and 4th
80600    ** templates:
80601    **
80602    **         EOF <- 0
80603    **         X <- A
80604    **         goto B
80605    **      A: setup for the SELECT
80606    **         loop over the tables in the SELECT
80607    **           load value into register R..R+n
80608    **           yield X
80609    **         end loop
80610    **         cleanup after the SELECT
80611    **         EOF <- 1
80612    **         yield X
80613    **         halt-error
80614    **
80615    ** On each invocation of the co-routine, it puts a single row of the
80616    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
80617    ** (These output registers are allocated by sqlite3Select().)  When
80618    ** the SELECT completes, it sets the EOF flag stored in regEof.
80619    */
80620    int rc, j1;
80621
80622    regEof = ++pParse->nMem;
80623    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
80624    VdbeComment((v, "SELECT eof flag"));
80625    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
80626    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
80627    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
80628    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
80629    VdbeComment((v, "Jump over SELECT coroutine"));
80630
80631    /* Resolve the expressions in the SELECT statement and execute it. */
80632    rc = sqlite3Select(pParse, pSelect, &dest);
80633    assert( pParse->nErr==0 || rc );
80634    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
80635      goto insert_cleanup;
80636    }
80637    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
80638    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
80639    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
80640    VdbeComment((v, "End of SELECT coroutine"));
80641    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
80642
80643    regFromSelect = dest.iMem;
80644    assert( pSelect->pEList );
80645    nColumn = pSelect->pEList->nExpr;
80646    assert( dest.nMem==nColumn );
80647
80648    /* Set useTempTable to TRUE if the result of the SELECT statement
80649    ** should be written into a temporary table (template 4).  Set to
80650    ** FALSE if each* row of the SELECT can be written directly into
80651    ** the destination table (template 3).
80652    **
80653    ** A temp table must be used if the table being updated is also one
80654    ** of the tables being read by the SELECT statement.  Also use a
80655    ** temp table in the case of row triggers.
80656    */
80657    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
80658      useTempTable = 1;
80659    }
80660
80661    if( useTempTable ){
80662      /* Invoke the coroutine to extract information from the SELECT
80663      ** and add it to a transient table srcTab.  The code generated
80664      ** here is from the 4th template:
80665      **
80666      **      B: open temp table
80667      **      L: yield X
80668      **         if EOF goto M
80669      **         insert row from R..R+n into temp table
80670      **         goto L
80671      **      M: ...
80672      */
80673      int regRec;          /* Register to hold packed record */
80674      int regTempRowid;    /* Register to hold temp table ROWID */
80675      int addrTop;         /* Label "L" */
80676      int addrIf;          /* Address of jump to M */
80677
80678      srcTab = pParse->nTab++;
80679      regRec = sqlite3GetTempReg(pParse);
80680      regTempRowid = sqlite3GetTempReg(pParse);
80681      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
80682      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
80683      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
80684      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
80685      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
80686      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
80687      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
80688      sqlite3VdbeJumpHere(v, addrIf);
80689      sqlite3ReleaseTempReg(pParse, regRec);
80690      sqlite3ReleaseTempReg(pParse, regTempRowid);
80691    }
80692  }else{
80693    /* This is the case if the data for the INSERT is coming from a VALUES
80694    ** clause
80695    */
80696    NameContext sNC;
80697    memset(&sNC, 0, sizeof(sNC));
80698    sNC.pParse = pParse;
80699    srcTab = -1;
80700    assert( useTempTable==0 );
80701    nColumn = pList ? pList->nExpr : 0;
80702    for(i=0; i<nColumn; i++){
80703      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
80704        goto insert_cleanup;
80705      }
80706    }
80707  }
80708
80709  /* Make sure the number of columns in the source data matches the number
80710  ** of columns to be inserted into the table.
80711  */
80712  if( IsVirtual(pTab) ){
80713    for(i=0; i<pTab->nCol; i++){
80714      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
80715    }
80716  }
80717  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
80718    sqlite3ErrorMsg(pParse,
80719       "table %S has %d columns but %d values were supplied",
80720       pTabList, 0, pTab->nCol-nHidden, nColumn);
80721    goto insert_cleanup;
80722  }
80723  if( pColumn!=0 && nColumn!=pColumn->nId ){
80724    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
80725    goto insert_cleanup;
80726  }
80727
80728  /* If the INSERT statement included an IDLIST term, then make sure
80729  ** all elements of the IDLIST really are columns of the table and
80730  ** remember the column indices.
80731  **
80732  ** If the table has an INTEGER PRIMARY KEY column and that column
80733  ** is named in the IDLIST, then record in the keyColumn variable
80734  ** the index into IDLIST of the primary key column.  keyColumn is
80735  ** the index of the primary key as it appears in IDLIST, not as
80736  ** is appears in the original table.  (The index of the primary
80737  ** key in the original table is pTab->iPKey.)
80738  */
80739  if( pColumn ){
80740    for(i=0; i<pColumn->nId; i++){
80741      pColumn->a[i].idx = -1;
80742    }
80743    for(i=0; i<pColumn->nId; i++){
80744      for(j=0; j<pTab->nCol; j++){
80745        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
80746          pColumn->a[i].idx = j;
80747          if( j==pTab->iPKey ){
80748            keyColumn = i;
80749          }
80750          break;
80751        }
80752      }
80753      if( j>=pTab->nCol ){
80754        if( sqlite3IsRowid(pColumn->a[i].zName) ){
80755          keyColumn = i;
80756        }else{
80757          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
80758              pTabList, 0, pColumn->a[i].zName);
80759          pParse->checkSchema = 1;
80760          goto insert_cleanup;
80761        }
80762      }
80763    }
80764  }
80765
80766  /* If there is no IDLIST term but the table has an integer primary
80767  ** key, the set the keyColumn variable to the primary key column index
80768  ** in the original table definition.
80769  */
80770  if( pColumn==0 && nColumn>0 ){
80771    keyColumn = pTab->iPKey;
80772  }
80773
80774  /* Initialize the count of rows to be inserted
80775  */
80776  if( db->flags & SQLITE_CountRows ){
80777    regRowCount = ++pParse->nMem;
80778    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
80779  }
80780
80781  /* If this is not a view, open the table and and all indices */
80782  if( !isView ){
80783    int nIdx;
80784
80785    baseCur = pParse->nTab;
80786    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
80787    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
80788    if( aRegIdx==0 ){
80789      goto insert_cleanup;
80790    }
80791    for(i=0; i<nIdx; i++){
80792      aRegIdx[i] = ++pParse->nMem;
80793    }
80794  }
80795
80796  /* This is the top of the main insertion loop */
80797  if( useTempTable ){
80798    /* This block codes the top of loop only.  The complete loop is the
80799    ** following pseudocode (template 4):
80800    **
80801    **         rewind temp table
80802    **      C: loop over rows of intermediate table
80803    **           transfer values form intermediate table into <table>
80804    **         end loop
80805    **      D: ...
80806    */
80807    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
80808    addrCont = sqlite3VdbeCurrentAddr(v);
80809  }else if( pSelect ){
80810    /* This block codes the top of loop only.  The complete loop is the
80811    ** following pseudocode (template 3):
80812    **
80813    **      C: yield X
80814    **         if EOF goto D
80815    **         insert the select result into <table> from R..R+n
80816    **         goto C
80817    **      D: ...
80818    */
80819    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
80820    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
80821  }
80822
80823  /* Allocate registers for holding the rowid of the new row,
80824  ** the content of the new row, and the assemblied row record.
80825  */
80826  regRecord = ++pParse->nMem;
80827  regRowid = regIns = pParse->nMem+1;
80828  pParse->nMem += pTab->nCol + 1;
80829  if( IsVirtual(pTab) ){
80830    regRowid++;
80831    pParse->nMem++;
80832  }
80833  regData = regRowid+1;
80834
80835  /* Run the BEFORE and INSTEAD OF triggers, if there are any
80836  */
80837  endOfLoop = sqlite3VdbeMakeLabel(v);
80838  if( tmask & TRIGGER_BEFORE ){
80839    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
80840
80841    /* build the NEW.* reference row.  Note that if there is an INTEGER
80842    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
80843    ** translated into a unique ID for the row.  But on a BEFORE trigger,
80844    ** we do not know what the unique ID will be (because the insert has
80845    ** not happened yet) so we substitute a rowid of -1
80846    */
80847    if( keyColumn<0 ){
80848      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
80849    }else{
80850      int j1;
80851      if( useTempTable ){
80852        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
80853      }else{
80854        assert( pSelect==0 );  /* Otherwise useTempTable is true */
80855        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
80856      }
80857      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
80858      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
80859      sqlite3VdbeJumpHere(v, j1);
80860      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
80861    }
80862
80863    /* Cannot have triggers on a virtual table. If it were possible,
80864    ** this block would have to account for hidden column.
80865    */
80866    assert( !IsVirtual(pTab) );
80867
80868    /* Create the new column data
80869    */
80870    for(i=0; i<pTab->nCol; i++){
80871      if( pColumn==0 ){
80872        j = i;
80873      }else{
80874        for(j=0; j<pColumn->nId; j++){
80875          if( pColumn->a[j].idx==i ) break;
80876        }
80877      }
80878      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
80879        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
80880      }else if( useTempTable ){
80881        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
80882      }else{
80883        assert( pSelect==0 ); /* Otherwise useTempTable is true */
80884        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
80885      }
80886    }
80887
80888    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
80889    ** do not attempt any conversions before assembling the record.
80890    ** If this is a real table, attempt conversions as required by the
80891    ** table column affinities.
80892    */
80893    if( !isView ){
80894      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
80895      sqlite3TableAffinityStr(v, pTab);
80896    }
80897
80898    /* Fire BEFORE or INSTEAD OF triggers */
80899    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
80900        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
80901
80902    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
80903  }
80904
80905  /* Push the record number for the new entry onto the stack.  The
80906  ** record number is a randomly generate integer created by NewRowid
80907  ** except when the table has an INTEGER PRIMARY KEY column, in which
80908  ** case the record number is the same as that column.
80909  */
80910  if( !isView ){
80911    if( IsVirtual(pTab) ){
80912      /* The row that the VUpdate opcode will delete: none */
80913      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
80914    }
80915    if( keyColumn>=0 ){
80916      if( useTempTable ){
80917        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
80918      }else if( pSelect ){
80919        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
80920      }else{
80921        VdbeOp *pOp;
80922        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
80923        pOp = sqlite3VdbeGetOp(v, -1);
80924        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
80925          appendFlag = 1;
80926          pOp->opcode = OP_NewRowid;
80927          pOp->p1 = baseCur;
80928          pOp->p2 = regRowid;
80929          pOp->p3 = regAutoinc;
80930        }
80931      }
80932      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
80933      ** to generate a unique primary key value.
80934      */
80935      if( !appendFlag ){
80936        int j1;
80937        if( !IsVirtual(pTab) ){
80938          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
80939          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
80940          sqlite3VdbeJumpHere(v, j1);
80941        }else{
80942          j1 = sqlite3VdbeCurrentAddr(v);
80943          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
80944        }
80945        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
80946      }
80947    }else if( IsVirtual(pTab) ){
80948      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
80949    }else{
80950      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
80951      appendFlag = 1;
80952    }
80953    autoIncStep(pParse, regAutoinc, regRowid);
80954
80955    /* Push onto the stack, data for all columns of the new entry, beginning
80956    ** with the first column.
80957    */
80958    nHidden = 0;
80959    for(i=0; i<pTab->nCol; i++){
80960      int iRegStore = regRowid+1+i;
80961      if( i==pTab->iPKey ){
80962        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
80963        ** Whenever this column is read, the record number will be substituted
80964        ** in its place.  So will fill this column with a NULL to avoid
80965        ** taking up data space with information that will never be used. */
80966        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
80967        continue;
80968      }
80969      if( pColumn==0 ){
80970        if( IsHiddenColumn(&pTab->aCol[i]) ){
80971          assert( IsVirtual(pTab) );
80972          j = -1;
80973          nHidden++;
80974        }else{
80975          j = i - nHidden;
80976        }
80977      }else{
80978        for(j=0; j<pColumn->nId; j++){
80979          if( pColumn->a[j].idx==i ) break;
80980        }
80981      }
80982      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
80983        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
80984      }else if( useTempTable ){
80985        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
80986      }else if( pSelect ){
80987        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
80988      }else{
80989        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
80990      }
80991    }
80992
80993    /* Generate code to check constraints and generate index keys and
80994    ** do the insertion.
80995    */
80996#ifndef SQLITE_OMIT_VIRTUALTABLE
80997    if( IsVirtual(pTab) ){
80998      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
80999      sqlite3VtabMakeWritable(pParse, pTab);
81000      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
81001      sqlite3MayAbort(pParse);
81002    }else
81003#endif
81004    {
81005      int isReplace;    /* Set to true if constraints may cause a replace */
81006      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
81007          keyColumn>=0, 0, onError, endOfLoop, &isReplace
81008      );
81009      sqlite3FkCheck(pParse, pTab, 0, regIns);
81010      sqlite3CompleteInsertion(
81011          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
81012      );
81013    }
81014  }
81015
81016  /* Update the count of rows that are inserted
81017  */
81018  if( (db->flags & SQLITE_CountRows)!=0 ){
81019    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
81020  }
81021
81022  if( pTrigger ){
81023    /* Code AFTER triggers */
81024    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
81025        pTab, regData-2-pTab->nCol, onError, endOfLoop);
81026  }
81027
81028  /* The bottom of the main insertion loop, if the data source
81029  ** is a SELECT statement.
81030  */
81031  sqlite3VdbeResolveLabel(v, endOfLoop);
81032  if( useTempTable ){
81033    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
81034    sqlite3VdbeJumpHere(v, addrInsTop);
81035    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
81036  }else if( pSelect ){
81037    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
81038    sqlite3VdbeJumpHere(v, addrInsTop);
81039  }
81040
81041  if( !IsVirtual(pTab) && !isView ){
81042    /* Close all tables opened */
81043    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
81044    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
81045      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
81046    }
81047  }
81048
81049insert_end:
81050  /* Update the sqlite_sequence table by storing the content of the
81051  ** maximum rowid counter values recorded while inserting into
81052  ** autoincrement tables.
81053  */
81054  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81055    sqlite3AutoincrementEnd(pParse);
81056  }
81057
81058  /*
81059  ** Return the number of rows inserted. If this routine is
81060  ** generating code because of a call to sqlite3NestedParse(), do not
81061  ** invoke the callback function.
81062  */
81063  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81064    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
81065    sqlite3VdbeSetNumCols(v, 1);
81066    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
81067  }
81068
81069insert_cleanup:
81070  sqlite3SrcListDelete(db, pTabList);
81071  sqlite3ExprListDelete(db, pList);
81072  sqlite3SelectDelete(db, pSelect);
81073  sqlite3IdListDelete(db, pColumn);
81074  sqlite3DbFree(db, aRegIdx);
81075}
81076
81077/* Make sure "isView" and other macros defined above are undefined. Otherwise
81078** thely may interfere with compilation of other functions in this file
81079** (or in another file, if this file becomes part of the amalgamation).  */
81080#ifdef isView
81081 #undef isView
81082#endif
81083#ifdef pTrigger
81084 #undef pTrigger
81085#endif
81086#ifdef tmask
81087 #undef tmask
81088#endif
81089
81090
81091/*
81092** Generate code to do constraint checks prior to an INSERT or an UPDATE.
81093**
81094** The input is a range of consecutive registers as follows:
81095**
81096**    1.  The rowid of the row after the update.
81097**
81098**    2.  The data in the first column of the entry after the update.
81099**
81100**    i.  Data from middle columns...
81101**
81102**    N.  The data in the last column of the entry after the update.
81103**
81104** The regRowid parameter is the index of the register containing (1).
81105**
81106** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
81107** the address of a register containing the rowid before the update takes
81108** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
81109** is false, indicating an INSERT statement, then a non-zero rowidChng
81110** indicates that the rowid was explicitly specified as part of the
81111** INSERT statement. If rowidChng is false, it means that  the rowid is
81112** computed automatically in an insert or that the rowid value is not
81113** modified by an update.
81114**
81115** The code generated by this routine store new index entries into
81116** registers identified by aRegIdx[].  No index entry is created for
81117** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
81118** the same as the order of indices on the linked list of indices
81119** attached to the table.
81120**
81121** This routine also generates code to check constraints.  NOT NULL,
81122** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
81123** then the appropriate action is performed.  There are five possible
81124** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
81125**
81126**  Constraint type  Action       What Happens
81127**  ---------------  ----------   ----------------------------------------
81128**  any              ROLLBACK     The current transaction is rolled back and
81129**                                sqlite3_exec() returns immediately with a
81130**                                return code of SQLITE_CONSTRAINT.
81131**
81132**  any              ABORT        Back out changes from the current command
81133**                                only (do not do a complete rollback) then
81134**                                cause sqlite3_exec() to return immediately
81135**                                with SQLITE_CONSTRAINT.
81136**
81137**  any              FAIL         Sqlite_exec() returns immediately with a
81138**                                return code of SQLITE_CONSTRAINT.  The
81139**                                transaction is not rolled back and any
81140**                                prior changes are retained.
81141**
81142**  any              IGNORE       The record number and data is popped from
81143**                                the stack and there is an immediate jump
81144**                                to label ignoreDest.
81145**
81146**  NOT NULL         REPLACE      The NULL value is replace by the default
81147**                                value for that column.  If the default value
81148**                                is NULL, the action is the same as ABORT.
81149**
81150**  UNIQUE           REPLACE      The other row that conflicts with the row
81151**                                being inserted is removed.
81152**
81153**  CHECK            REPLACE      Illegal.  The results in an exception.
81154**
81155** Which action to take is determined by the overrideError parameter.
81156** Or if overrideError==OE_Default, then the pParse->onError parameter
81157** is used.  Or if pParse->onError==OE_Default then the onError value
81158** for the constraint is used.
81159**
81160** The calling routine must open a read/write cursor for pTab with
81161** cursor number "baseCur".  All indices of pTab must also have open
81162** read/write cursors with cursor number baseCur+i for the i-th cursor.
81163** Except, if there is no possibility of a REPLACE action then
81164** cursors do not need to be open for indices where aRegIdx[i]==0.
81165*/
81166SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
81167  Parse *pParse,      /* The parser context */
81168  Table *pTab,        /* the table into which we are inserting */
81169  int baseCur,        /* Index of a read/write cursor pointing at pTab */
81170  int regRowid,       /* Index of the range of input registers */
81171  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81172  int rowidChng,      /* True if the rowid might collide with existing entry */
81173  int isUpdate,       /* True for UPDATE, False for INSERT */
81174  int overrideError,  /* Override onError to this if not OE_Default */
81175  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
81176  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
81177){
81178  int i;              /* loop counter */
81179  Vdbe *v;            /* VDBE under constrution */
81180  int nCol;           /* Number of columns */
81181  int onError;        /* Conflict resolution strategy */
81182  int j1;             /* Addresss of jump instruction */
81183  int j2 = 0, j3;     /* Addresses of jump instructions */
81184  int regData;        /* Register containing first data column */
81185  int iCur;           /* Table cursor number */
81186  Index *pIdx;         /* Pointer to one of the indices */
81187  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
81188  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
81189
81190  v = sqlite3GetVdbe(pParse);
81191  assert( v!=0 );
81192  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81193  nCol = pTab->nCol;
81194  regData = regRowid + 1;
81195
81196  /* Test all NOT NULL constraints.
81197  */
81198  for(i=0; i<nCol; i++){
81199    if( i==pTab->iPKey ){
81200      continue;
81201    }
81202    onError = pTab->aCol[i].notNull;
81203    if( onError==OE_None ) continue;
81204    if( overrideError!=OE_Default ){
81205      onError = overrideError;
81206    }else if( onError==OE_Default ){
81207      onError = OE_Abort;
81208    }
81209    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
81210      onError = OE_Abort;
81211    }
81212    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81213        || onError==OE_Ignore || onError==OE_Replace );
81214    switch( onError ){
81215      case OE_Abort:
81216        sqlite3MayAbort(pParse);
81217      case OE_Rollback:
81218      case OE_Fail: {
81219        char *zMsg;
81220        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
81221                                  SQLITE_CONSTRAINT, onError, regData+i);
81222        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
81223                              pTab->zName, pTab->aCol[i].zName);
81224        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
81225        break;
81226      }
81227      case OE_Ignore: {
81228        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
81229        break;
81230      }
81231      default: {
81232        assert( onError==OE_Replace );
81233        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
81234        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
81235        sqlite3VdbeJumpHere(v, j1);
81236        break;
81237      }
81238    }
81239  }
81240
81241  /* Test all CHECK constraints
81242  */
81243#ifndef SQLITE_OMIT_CHECK
81244  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
81245    int allOk = sqlite3VdbeMakeLabel(v);
81246    pParse->ckBase = regData;
81247    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
81248    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
81249    if( onError==OE_Ignore ){
81250      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81251    }else{
81252      sqlite3HaltConstraint(pParse, onError, 0, 0);
81253    }
81254    sqlite3VdbeResolveLabel(v, allOk);
81255  }
81256#endif /* !defined(SQLITE_OMIT_CHECK) */
81257
81258  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
81259  ** of the new record does not previously exist.  Except, if this
81260  ** is an UPDATE and the primary key is not changing, that is OK.
81261  */
81262  if( rowidChng ){
81263    onError = pTab->keyConf;
81264    if( overrideError!=OE_Default ){
81265      onError = overrideError;
81266    }else if( onError==OE_Default ){
81267      onError = OE_Abort;
81268    }
81269
81270    if( isUpdate ){
81271      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
81272    }
81273    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
81274    switch( onError ){
81275      default: {
81276        onError = OE_Abort;
81277        /* Fall thru into the next case */
81278      }
81279      case OE_Rollback:
81280      case OE_Abort:
81281      case OE_Fail: {
81282        sqlite3HaltConstraint(
81283          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
81284        break;
81285      }
81286      case OE_Replace: {
81287        /* If there are DELETE triggers on this table and the
81288        ** recursive-triggers flag is set, call GenerateRowDelete() to
81289        ** remove the conflicting row from the the table. This will fire
81290        ** the triggers and remove both the table and index b-tree entries.
81291        **
81292        ** Otherwise, if there are no triggers or the recursive-triggers
81293        ** flag is not set, but the table has one or more indexes, call
81294        ** GenerateRowIndexDelete(). This removes the index b-tree entries
81295        ** only. The table b-tree entry will be replaced by the new entry
81296        ** when it is inserted.
81297        **
81298        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
81299        ** also invoke MultiWrite() to indicate that this VDBE may require
81300        ** statement rollback (if the statement is aborted after the delete
81301        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
81302        ** but being more selective here allows statements like:
81303        **
81304        **   REPLACE INTO t(rowid) VALUES($newrowid)
81305        **
81306        ** to run without a statement journal if there are no indexes on the
81307        ** table.
81308        */
81309        Trigger *pTrigger = 0;
81310        if( pParse->db->flags&SQLITE_RecTriggers ){
81311          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81312        }
81313        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
81314          sqlite3MultiWrite(pParse);
81315          sqlite3GenerateRowDelete(
81316              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
81317          );
81318        }else if( pTab->pIndex ){
81319          sqlite3MultiWrite(pParse);
81320          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
81321        }
81322        seenReplace = 1;
81323        break;
81324      }
81325      case OE_Ignore: {
81326        assert( seenReplace==0 );
81327        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81328        break;
81329      }
81330    }
81331    sqlite3VdbeJumpHere(v, j3);
81332    if( isUpdate ){
81333      sqlite3VdbeJumpHere(v, j2);
81334    }
81335  }
81336
81337  /* Test all UNIQUE constraints by creating entries for each UNIQUE
81338  ** index and making sure that duplicate entries do not already exist.
81339  ** Add the new records to the indices as we go.
81340  */
81341  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
81342    int regIdx;
81343    int regR;
81344
81345    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
81346
81347    /* Create a key for accessing the index entry */
81348    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
81349    for(i=0; i<pIdx->nColumn; i++){
81350      int idx = pIdx->aiColumn[i];
81351      if( idx==pTab->iPKey ){
81352        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81353      }else{
81354        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
81355      }
81356    }
81357    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81358    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
81359    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81360    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
81361
81362    /* Find out what action to take in case there is an indexing conflict */
81363    onError = pIdx->onError;
81364    if( onError==OE_None ){
81365      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81366      continue;  /* pIdx is not a UNIQUE index */
81367    }
81368    if( overrideError!=OE_Default ){
81369      onError = overrideError;
81370    }else if( onError==OE_Default ){
81371      onError = OE_Abort;
81372    }
81373    if( seenReplace ){
81374      if( onError==OE_Ignore ) onError = OE_Replace;
81375      else if( onError==OE_Fail ) onError = OE_Abort;
81376    }
81377
81378    /* Check to see if the new index entry will be unique */
81379    regR = sqlite3GetTempReg(pParse);
81380    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
81381    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
81382                           regR, SQLITE_INT_TO_PTR(regIdx),
81383                           P4_INT32);
81384    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81385
81386    /* Generate code that executes if the new index entry is not unique */
81387    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81388        || onError==OE_Ignore || onError==OE_Replace );
81389    switch( onError ){
81390      case OE_Rollback:
81391      case OE_Abort:
81392      case OE_Fail: {
81393        int j;
81394        StrAccum errMsg;
81395        const char *zSep;
81396        char *zErr;
81397
81398        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
81399        errMsg.db = pParse->db;
81400        zSep = pIdx->nColumn>1 ? "columns " : "column ";
81401        for(j=0; j<pIdx->nColumn; j++){
81402          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
81403          sqlite3StrAccumAppend(&errMsg, zSep, -1);
81404          zSep = ", ";
81405          sqlite3StrAccumAppend(&errMsg, zCol, -1);
81406        }
81407        sqlite3StrAccumAppend(&errMsg,
81408            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
81409        zErr = sqlite3StrAccumFinish(&errMsg);
81410        sqlite3HaltConstraint(pParse, onError, zErr, 0);
81411        sqlite3DbFree(errMsg.db, zErr);
81412        break;
81413      }
81414      case OE_Ignore: {
81415        assert( seenReplace==0 );
81416        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81417        break;
81418      }
81419      default: {
81420        Trigger *pTrigger = 0;
81421        assert( onError==OE_Replace );
81422        sqlite3MultiWrite(pParse);
81423        if( pParse->db->flags&SQLITE_RecTriggers ){
81424          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81425        }
81426        sqlite3GenerateRowDelete(
81427            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
81428        );
81429        seenReplace = 1;
81430        break;
81431      }
81432    }
81433    sqlite3VdbeJumpHere(v, j3);
81434    sqlite3ReleaseTempReg(pParse, regR);
81435  }
81436
81437  if( pbMayReplace ){
81438    *pbMayReplace = seenReplace;
81439  }
81440}
81441
81442/*
81443** This routine generates code to finish the INSERT or UPDATE operation
81444** that was started by a prior call to sqlite3GenerateConstraintChecks.
81445** A consecutive range of registers starting at regRowid contains the
81446** rowid and the content to be inserted.
81447**
81448** The arguments to this routine should be the same as the first six
81449** arguments to sqlite3GenerateConstraintChecks.
81450*/
81451SQLITE_PRIVATE void sqlite3CompleteInsertion(
81452  Parse *pParse,      /* The parser context */
81453  Table *pTab,        /* the table into which we are inserting */
81454  int baseCur,        /* Index of a read/write cursor pointing at pTab */
81455  int regRowid,       /* Range of content */
81456  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81457  int isUpdate,       /* True for UPDATE, False for INSERT */
81458  int appendBias,     /* True if this is likely to be an append */
81459  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
81460){
81461  int i;
81462  Vdbe *v;
81463  int nIdx;
81464  Index *pIdx;
81465  u8 pik_flags;
81466  int regData;
81467  int regRec;
81468
81469  v = sqlite3GetVdbe(pParse);
81470  assert( v!=0 );
81471  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81472  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
81473  for(i=nIdx-1; i>=0; i--){
81474    if( aRegIdx[i]==0 ) continue;
81475    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
81476    if( useSeekResult ){
81477      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81478    }
81479  }
81480  regData = regRowid + 1;
81481  regRec = sqlite3GetTempReg(pParse);
81482  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
81483  sqlite3TableAffinityStr(v, pTab);
81484  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
81485  if( pParse->nested ){
81486    pik_flags = 0;
81487  }else{
81488    pik_flags = OPFLAG_NCHANGE;
81489    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
81490  }
81491  if( appendBias ){
81492    pik_flags |= OPFLAG_APPEND;
81493  }
81494  if( useSeekResult ){
81495    pik_flags |= OPFLAG_USESEEKRESULT;
81496  }
81497  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
81498  if( !pParse->nested ){
81499    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
81500  }
81501  sqlite3VdbeChangeP5(v, pik_flags);
81502}
81503
81504/*
81505** Generate code that will open cursors for a table and for all
81506** indices of that table.  The "baseCur" parameter is the cursor number used
81507** for the table.  Indices are opened on subsequent cursors.
81508**
81509** Return the number of indices on the table.
81510*/
81511SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
81512  Parse *pParse,   /* Parsing context */
81513  Table *pTab,     /* Table to be opened */
81514  int baseCur,     /* Cursor number assigned to the table */
81515  int op           /* OP_OpenRead or OP_OpenWrite */
81516){
81517  int i;
81518  int iDb;
81519  Index *pIdx;
81520  Vdbe *v;
81521
81522  if( IsVirtual(pTab) ) return 0;
81523  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81524  v = sqlite3GetVdbe(pParse);
81525  assert( v!=0 );
81526  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
81527  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
81528    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81529    assert( pIdx->pSchema==pTab->pSchema );
81530    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
81531                      (char*)pKey, P4_KEYINFO_HANDOFF);
81532    VdbeComment((v, "%s", pIdx->zName));
81533  }
81534  if( pParse->nTab<baseCur+i ){
81535    pParse->nTab = baseCur+i;
81536  }
81537  return i-1;
81538}
81539
81540
81541#ifdef SQLITE_TEST
81542/*
81543** The following global variable is incremented whenever the
81544** transfer optimization is used.  This is used for testing
81545** purposes only - to make sure the transfer optimization really
81546** is happening when it is suppose to.
81547*/
81548SQLITE_API int sqlite3_xferopt_count;
81549#endif /* SQLITE_TEST */
81550
81551
81552#ifndef SQLITE_OMIT_XFER_OPT
81553/*
81554** Check to collation names to see if they are compatible.
81555*/
81556static int xferCompatibleCollation(const char *z1, const char *z2){
81557  if( z1==0 ){
81558    return z2==0;
81559  }
81560  if( z2==0 ){
81561    return 0;
81562  }
81563  return sqlite3StrICmp(z1, z2)==0;
81564}
81565
81566
81567/*
81568** Check to see if index pSrc is compatible as a source of data
81569** for index pDest in an insert transfer optimization.  The rules
81570** for a compatible index:
81571**
81572**    *   The index is over the same set of columns
81573**    *   The same DESC and ASC markings occurs on all columns
81574**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
81575**    *   The same collating sequence on each column
81576*/
81577static int xferCompatibleIndex(Index *pDest, Index *pSrc){
81578  int i;
81579  assert( pDest && pSrc );
81580  assert( pDest->pTable!=pSrc->pTable );
81581  if( pDest->nColumn!=pSrc->nColumn ){
81582    return 0;   /* Different number of columns */
81583  }
81584  if( pDest->onError!=pSrc->onError ){
81585    return 0;   /* Different conflict resolution strategies */
81586  }
81587  for(i=0; i<pSrc->nColumn; i++){
81588    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
81589      return 0;   /* Different columns indexed */
81590    }
81591    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
81592      return 0;   /* Different sort orders */
81593    }
81594    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
81595      return 0;   /* Different collating sequences */
81596    }
81597  }
81598
81599  /* If no test above fails then the indices must be compatible */
81600  return 1;
81601}
81602
81603/*
81604** Attempt the transfer optimization on INSERTs of the form
81605**
81606**     INSERT INTO tab1 SELECT * FROM tab2;
81607**
81608** This optimization is only attempted if
81609**
81610**    (1)  tab1 and tab2 have identical schemas including all the
81611**         same indices and constraints
81612**
81613**    (2)  tab1 and tab2 are different tables
81614**
81615**    (3)  There must be no triggers on tab1
81616**
81617**    (4)  The result set of the SELECT statement is "*"
81618**
81619**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
81620**         or LIMIT clause.
81621**
81622**    (6)  The SELECT statement is a simple (not a compound) select that
81623**         contains only tab2 in its FROM clause
81624**
81625** This method for implementing the INSERT transfers raw records from
81626** tab2 over to tab1.  The columns are not decoded.  Raw records from
81627** the indices of tab2 are transfered to tab1 as well.  In so doing,
81628** the resulting tab1 has much less fragmentation.
81629**
81630** This routine returns TRUE if the optimization is attempted.  If any
81631** of the conditions above fail so that the optimization should not
81632** be attempted, then this routine returns FALSE.
81633*/
81634static int xferOptimization(
81635  Parse *pParse,        /* Parser context */
81636  Table *pDest,         /* The table we are inserting into */
81637  Select *pSelect,      /* A SELECT statement to use as the data source */
81638  int onError,          /* How to handle constraint errors */
81639  int iDbDest           /* The database of pDest */
81640){
81641  ExprList *pEList;                /* The result set of the SELECT */
81642  Table *pSrc;                     /* The table in the FROM clause of SELECT */
81643  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
81644  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
81645  int i;                           /* Loop counter */
81646  int iDbSrc;                      /* The database of pSrc */
81647  int iSrc, iDest;                 /* Cursors from source and destination */
81648  int addr1, addr2;                /* Loop addresses */
81649  int emptyDestTest;               /* Address of test for empty pDest */
81650  int emptySrcTest;                /* Address of test for empty pSrc */
81651  Vdbe *v;                         /* The VDBE we are building */
81652  KeyInfo *pKey;                   /* Key information for an index */
81653  int regAutoinc;                  /* Memory register used by AUTOINC */
81654  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
81655  int regData, regRowid;           /* Registers holding data and rowid */
81656
81657  if( pSelect==0 ){
81658    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
81659  }
81660  if( sqlite3TriggerList(pParse, pDest) ){
81661    return 0;   /* tab1 must not have triggers */
81662  }
81663#ifndef SQLITE_OMIT_VIRTUALTABLE
81664  if( pDest->tabFlags & TF_Virtual ){
81665    return 0;   /* tab1 must not be a virtual table */
81666  }
81667#endif
81668  if( onError==OE_Default ){
81669    onError = OE_Abort;
81670  }
81671  if( onError!=OE_Abort && onError!=OE_Rollback ){
81672    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
81673  }
81674  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
81675  if( pSelect->pSrc->nSrc!=1 ){
81676    return 0;   /* FROM clause must have exactly one term */
81677  }
81678  if( pSelect->pSrc->a[0].pSelect ){
81679    return 0;   /* FROM clause cannot contain a subquery */
81680  }
81681  if( pSelect->pWhere ){
81682    return 0;   /* SELECT may not have a WHERE clause */
81683  }
81684  if( pSelect->pOrderBy ){
81685    return 0;   /* SELECT may not have an ORDER BY clause */
81686  }
81687  /* Do not need to test for a HAVING clause.  If HAVING is present but
81688  ** there is no ORDER BY, we will get an error. */
81689  if( pSelect->pGroupBy ){
81690    return 0;   /* SELECT may not have a GROUP BY clause */
81691  }
81692  if( pSelect->pLimit ){
81693    return 0;   /* SELECT may not have a LIMIT clause */
81694  }
81695  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
81696  if( pSelect->pPrior ){
81697    return 0;   /* SELECT may not be a compound query */
81698  }
81699  if( pSelect->selFlags & SF_Distinct ){
81700    return 0;   /* SELECT may not be DISTINCT */
81701  }
81702  pEList = pSelect->pEList;
81703  assert( pEList!=0 );
81704  if( pEList->nExpr!=1 ){
81705    return 0;   /* The result set must have exactly one column */
81706  }
81707  assert( pEList->a[0].pExpr );
81708  if( pEList->a[0].pExpr->op!=TK_ALL ){
81709    return 0;   /* The result set must be the special operator "*" */
81710  }
81711
81712  /* At this point we have established that the statement is of the
81713  ** correct syntactic form to participate in this optimization.  Now
81714  ** we have to check the semantics.
81715  */
81716  pItem = pSelect->pSrc->a;
81717  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
81718  if( pSrc==0 ){
81719    return 0;   /* FROM clause does not contain a real table */
81720  }
81721  if( pSrc==pDest ){
81722    return 0;   /* tab1 and tab2 may not be the same table */
81723  }
81724#ifndef SQLITE_OMIT_VIRTUALTABLE
81725  if( pSrc->tabFlags & TF_Virtual ){
81726    return 0;   /* tab2 must not be a virtual table */
81727  }
81728#endif
81729  if( pSrc->pSelect ){
81730    return 0;   /* tab2 may not be a view */
81731  }
81732  if( pDest->nCol!=pSrc->nCol ){
81733    return 0;   /* Number of columns must be the same in tab1 and tab2 */
81734  }
81735  if( pDest->iPKey!=pSrc->iPKey ){
81736    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
81737  }
81738  for(i=0; i<pDest->nCol; i++){
81739    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
81740      return 0;    /* Affinity must be the same on all columns */
81741    }
81742    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
81743      return 0;    /* Collating sequence must be the same on all columns */
81744    }
81745    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
81746      return 0;    /* tab2 must be NOT NULL if tab1 is */
81747    }
81748  }
81749  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
81750    if( pDestIdx->onError!=OE_None ){
81751      destHasUniqueIdx = 1;
81752    }
81753    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
81754      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
81755    }
81756    if( pSrcIdx==0 ){
81757      return 0;    /* pDestIdx has no corresponding index in pSrc */
81758    }
81759  }
81760#ifndef SQLITE_OMIT_CHECK
81761  if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
81762    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
81763  }
81764#endif
81765
81766  /* If we get this far, it means either:
81767  **
81768  **    *   We can always do the transfer if the table contains an
81769  **        an integer primary key
81770  **
81771  **    *   We can conditionally do the transfer if the destination
81772  **        table is empty.
81773  */
81774#ifdef SQLITE_TEST
81775  sqlite3_xferopt_count++;
81776#endif
81777  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
81778  v = sqlite3GetVdbe(pParse);
81779  sqlite3CodeVerifySchema(pParse, iDbSrc);
81780  iSrc = pParse->nTab++;
81781  iDest = pParse->nTab++;
81782  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
81783  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
81784  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
81785    /* If tables do not have an INTEGER PRIMARY KEY and there
81786    ** are indices to be copied and the destination is not empty,
81787    ** we have to disallow the transfer optimization because the
81788    ** the rowids might change which will mess up indexing.
81789    **
81790    ** Or if the destination has a UNIQUE index and is not empty,
81791    ** we also disallow the transfer optimization because we cannot
81792    ** insure that all entries in the union of DEST and SRC will be
81793    ** unique.
81794    */
81795    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
81796    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
81797    sqlite3VdbeJumpHere(v, addr1);
81798  }else{
81799    emptyDestTest = 0;
81800  }
81801  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
81802  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
81803  regData = sqlite3GetTempReg(pParse);
81804  regRowid = sqlite3GetTempReg(pParse);
81805  if( pDest->iPKey>=0 ){
81806    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
81807    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
81808    sqlite3HaltConstraint(
81809        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
81810    sqlite3VdbeJumpHere(v, addr2);
81811    autoIncStep(pParse, regAutoinc, regRowid);
81812  }else if( pDest->pIndex==0 ){
81813    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
81814  }else{
81815    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
81816    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
81817  }
81818  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
81819  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
81820  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
81821  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
81822  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
81823  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
81824    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
81825      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
81826    }
81827    assert( pSrcIdx );
81828    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
81829    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
81830    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
81831    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
81832                      (char*)pKey, P4_KEYINFO_HANDOFF);
81833    VdbeComment((v, "%s", pSrcIdx->zName));
81834    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
81835    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
81836                      (char*)pKey, P4_KEYINFO_HANDOFF);
81837    VdbeComment((v, "%s", pDestIdx->zName));
81838    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
81839    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
81840    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
81841    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
81842    sqlite3VdbeJumpHere(v, addr1);
81843  }
81844  sqlite3VdbeJumpHere(v, emptySrcTest);
81845  sqlite3ReleaseTempReg(pParse, regRowid);
81846  sqlite3ReleaseTempReg(pParse, regData);
81847  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
81848  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
81849  if( emptyDestTest ){
81850    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
81851    sqlite3VdbeJumpHere(v, emptyDestTest);
81852    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
81853    return 0;
81854  }else{
81855    return 1;
81856  }
81857}
81858#endif /* SQLITE_OMIT_XFER_OPT */
81859
81860/************** End of insert.c **********************************************/
81861/************** Begin file legacy.c ******************************************/
81862/*
81863** 2001 September 15
81864**
81865** The author disclaims copyright to this source code.  In place of
81866** a legal notice, here is a blessing:
81867**
81868**    May you do good and not evil.
81869**    May you find forgiveness for yourself and forgive others.
81870**    May you share freely, never taking more than you give.
81871**
81872*************************************************************************
81873** Main file for the SQLite library.  The routines in this file
81874** implement the programmer interface to the library.  Routines in
81875** other files are for internal use by SQLite and should not be
81876** accessed by users of the library.
81877*/
81878
81879
81880/*
81881** Execute SQL code.  Return one of the SQLITE_ success/failure
81882** codes.  Also write an error message into memory obtained from
81883** malloc() and make *pzErrMsg point to that message.
81884**
81885** If the SQL is a query, then for each row in the query result
81886** the xCallback() function is called.  pArg becomes the first
81887** argument to xCallback().  If xCallback=NULL then no callback
81888** is invoked, even for queries.
81889*/
81890SQLITE_API int sqlite3_exec(
81891  sqlite3 *db,                /* The database on which the SQL executes */
81892  const char *zSql,           /* The SQL to be executed */
81893  sqlite3_callback xCallback, /* Invoke this callback routine */
81894  void *pArg,                 /* First argument to xCallback() */
81895  char **pzErrMsg             /* Write error messages here */
81896){
81897  int rc = SQLITE_OK;         /* Return code */
81898  const char *zLeftover;      /* Tail of unprocessed SQL */
81899  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
81900  char **azCols = 0;          /* Names of result columns */
81901  int nRetry = 0;             /* Number of retry attempts */
81902  int callbackIsInit;         /* True if callback data is initialized */
81903
81904  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
81905  if( zSql==0 ) zSql = "";
81906
81907  sqlite3_mutex_enter(db->mutex);
81908  sqlite3Error(db, SQLITE_OK, 0);
81909  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
81910    int nCol;
81911    char **azVals = 0;
81912
81913    pStmt = 0;
81914    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
81915    assert( rc==SQLITE_OK || pStmt==0 );
81916    if( rc!=SQLITE_OK ){
81917      continue;
81918    }
81919    if( !pStmt ){
81920      /* this happens for a comment or white-space */
81921      zSql = zLeftover;
81922      continue;
81923    }
81924
81925    callbackIsInit = 0;
81926    nCol = sqlite3_column_count(pStmt);
81927
81928    while( 1 ){
81929      int i;
81930      rc = sqlite3_step(pStmt);
81931
81932      /* Invoke the callback function if required */
81933      if( xCallback && (SQLITE_ROW==rc ||
81934          (SQLITE_DONE==rc && !callbackIsInit
81935                           && db->flags&SQLITE_NullCallback)) ){
81936        if( !callbackIsInit ){
81937          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
81938          if( azCols==0 ){
81939            goto exec_out;
81940          }
81941          for(i=0; i<nCol; i++){
81942            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
81943            /* sqlite3VdbeSetColName() installs column names as UTF8
81944            ** strings so there is no way for sqlite3_column_name() to fail. */
81945            assert( azCols[i]!=0 );
81946          }
81947          callbackIsInit = 1;
81948        }
81949        if( rc==SQLITE_ROW ){
81950          azVals = &azCols[nCol];
81951          for(i=0; i<nCol; i++){
81952            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
81953            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
81954              db->mallocFailed = 1;
81955              goto exec_out;
81956            }
81957          }
81958        }
81959        if( xCallback(pArg, nCol, azVals, azCols) ){
81960          rc = SQLITE_ABORT;
81961          sqlite3VdbeFinalize((Vdbe *)pStmt);
81962          pStmt = 0;
81963          sqlite3Error(db, SQLITE_ABORT, 0);
81964          goto exec_out;
81965        }
81966      }
81967
81968      if( rc!=SQLITE_ROW ){
81969        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
81970        pStmt = 0;
81971        if( rc!=SQLITE_SCHEMA ){
81972          nRetry = 0;
81973          zSql = zLeftover;
81974          while( sqlite3Isspace(zSql[0]) ) zSql++;
81975        }
81976        break;
81977      }
81978    }
81979
81980    sqlite3DbFree(db, azCols);
81981    azCols = 0;
81982  }
81983
81984exec_out:
81985  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
81986  sqlite3DbFree(db, azCols);
81987
81988  rc = sqlite3ApiExit(db, rc);
81989  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
81990    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
81991    *pzErrMsg = sqlite3Malloc(nErrMsg);
81992    if( *pzErrMsg ){
81993      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
81994    }else{
81995      rc = SQLITE_NOMEM;
81996      sqlite3Error(db, SQLITE_NOMEM, 0);
81997    }
81998  }else if( pzErrMsg ){
81999    *pzErrMsg = 0;
82000  }
82001
82002  assert( (rc&db->errMask)==rc );
82003  sqlite3_mutex_leave(db->mutex);
82004  return rc;
82005}
82006
82007/************** End of legacy.c **********************************************/
82008/************** Begin file loadext.c *****************************************/
82009/*
82010** 2006 June 7
82011**
82012** The author disclaims copyright to this source code.  In place of
82013** a legal notice, here is a blessing:
82014**
82015**    May you do good and not evil.
82016**    May you find forgiveness for yourself and forgive others.
82017**    May you share freely, never taking more than you give.
82018**
82019*************************************************************************
82020** This file contains code used to dynamically load extensions into
82021** the SQLite library.
82022*/
82023
82024#ifndef SQLITE_CORE
82025  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
82026#endif
82027/************** Include sqlite3ext.h in the middle of loadext.c **************/
82028/************** Begin file sqlite3ext.h **************************************/
82029/*
82030** 2006 June 7
82031**
82032** The author disclaims copyright to this source code.  In place of
82033** a legal notice, here is a blessing:
82034**
82035**    May you do good and not evil.
82036**    May you find forgiveness for yourself and forgive others.
82037**    May you share freely, never taking more than you give.
82038**
82039*************************************************************************
82040** This header file defines the SQLite interface for use by
82041** shared libraries that want to be imported as extensions into
82042** an SQLite instance.  Shared libraries that intend to be loaded
82043** as extensions by SQLite should #include this file instead of
82044** sqlite3.h.
82045*/
82046#ifndef _SQLITE3EXT_H_
82047#define _SQLITE3EXT_H_
82048
82049typedef struct sqlite3_api_routines sqlite3_api_routines;
82050
82051/*
82052** The following structure holds pointers to all of the SQLite API
82053** routines.
82054**
82055** WARNING:  In order to maintain backwards compatibility, add new
82056** interfaces to the end of this structure only.  If you insert new
82057** interfaces in the middle of this structure, then older different
82058** versions of SQLite will not be able to load each others' shared
82059** libraries!
82060*/
82061struct sqlite3_api_routines {
82062  void * (*aggregate_context)(sqlite3_context*,int nBytes);
82063  int  (*aggregate_count)(sqlite3_context*);
82064  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
82065  int  (*bind_double)(sqlite3_stmt*,int,double);
82066  int  (*bind_int)(sqlite3_stmt*,int,int);
82067  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
82068  int  (*bind_null)(sqlite3_stmt*,int);
82069  int  (*bind_parameter_count)(sqlite3_stmt*);
82070  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
82071  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
82072  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
82073  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
82074  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
82075  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
82076  int  (*busy_timeout)(sqlite3*,int ms);
82077  int  (*changes)(sqlite3*);
82078  int  (*close)(sqlite3*);
82079  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
82080  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
82081  const void * (*column_blob)(sqlite3_stmt*,int iCol);
82082  int  (*column_bytes)(sqlite3_stmt*,int iCol);
82083  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
82084  int  (*column_count)(sqlite3_stmt*pStmt);
82085  const char * (*column_database_name)(sqlite3_stmt*,int);
82086  const void * (*column_database_name16)(sqlite3_stmt*,int);
82087  const char * (*column_decltype)(sqlite3_stmt*,int i);
82088  const void * (*column_decltype16)(sqlite3_stmt*,int);
82089  double  (*column_double)(sqlite3_stmt*,int iCol);
82090  int  (*column_int)(sqlite3_stmt*,int iCol);
82091  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
82092  const char * (*column_name)(sqlite3_stmt*,int);
82093  const void * (*column_name16)(sqlite3_stmt*,int);
82094  const char * (*column_origin_name)(sqlite3_stmt*,int);
82095  const void * (*column_origin_name16)(sqlite3_stmt*,int);
82096  const char * (*column_table_name)(sqlite3_stmt*,int);
82097  const void * (*column_table_name16)(sqlite3_stmt*,int);
82098  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
82099  const void * (*column_text16)(sqlite3_stmt*,int iCol);
82100  int  (*column_type)(sqlite3_stmt*,int iCol);
82101  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
82102  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
82103  int  (*complete)(const char*sql);
82104  int  (*complete16)(const void*sql);
82105  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
82106  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
82107  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*));
82108  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*));
82109  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
82110  int  (*data_count)(sqlite3_stmt*pStmt);
82111  sqlite3 * (*db_handle)(sqlite3_stmt*);
82112  int (*declare_vtab)(sqlite3*,const char*);
82113  int  (*enable_shared_cache)(int);
82114  int  (*errcode)(sqlite3*db);
82115  const char * (*errmsg)(sqlite3*);
82116  const void * (*errmsg16)(sqlite3*);
82117  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
82118  int  (*expired)(sqlite3_stmt*);
82119  int  (*finalize)(sqlite3_stmt*pStmt);
82120  void  (*free)(void*);
82121  void  (*free_table)(char**result);
82122  int  (*get_autocommit)(sqlite3*);
82123  void * (*get_auxdata)(sqlite3_context*,int);
82124  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
82125  int  (*global_recover)(void);
82126  void  (*interruptx)(sqlite3*);
82127  sqlite_int64  (*last_insert_rowid)(sqlite3*);
82128  const char * (*libversion)(void);
82129  int  (*libversion_number)(void);
82130  void *(*malloc)(int);
82131  char * (*mprintf)(const char*,...);
82132  int  (*open)(const char*,sqlite3**);
82133  int  (*open16)(const void*,sqlite3**);
82134  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82135  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82136  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
82137  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
82138  void *(*realloc)(void*,int);
82139  int  (*reset)(sqlite3_stmt*pStmt);
82140  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
82141  void  (*result_double)(sqlite3_context*,double);
82142  void  (*result_error)(sqlite3_context*,const char*,int);
82143  void  (*result_error16)(sqlite3_context*,const void*,int);
82144  void  (*result_int)(sqlite3_context*,int);
82145  void  (*result_int64)(sqlite3_context*,sqlite_int64);
82146  void  (*result_null)(sqlite3_context*);
82147  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
82148  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
82149  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
82150  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
82151  void  (*result_value)(sqlite3_context*,sqlite3_value*);
82152  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
82153  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
82154  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
82155  char * (*snprintf)(int,char*,const char*,...);
82156  int  (*step)(sqlite3_stmt*);
82157  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
82158  void  (*thread_cleanup)(void);
82159  int  (*total_changes)(sqlite3*);
82160  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
82161  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
82162  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
82163  void * (*user_data)(sqlite3_context*);
82164  const void * (*value_blob)(sqlite3_value*);
82165  int  (*value_bytes)(sqlite3_value*);
82166  int  (*value_bytes16)(sqlite3_value*);
82167  double  (*value_double)(sqlite3_value*);
82168  int  (*value_int)(sqlite3_value*);
82169  sqlite_int64  (*value_int64)(sqlite3_value*);
82170  int  (*value_numeric_type)(sqlite3_value*);
82171  const unsigned char * (*value_text)(sqlite3_value*);
82172  const void * (*value_text16)(sqlite3_value*);
82173  const void * (*value_text16be)(sqlite3_value*);
82174  const void * (*value_text16le)(sqlite3_value*);
82175  int  (*value_type)(sqlite3_value*);
82176  char *(*vmprintf)(const char*,va_list);
82177  /* Added ??? */
82178  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
82179  /* Added by 3.3.13 */
82180  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82181  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82182  int (*clear_bindings)(sqlite3_stmt*);
82183  /* Added by 3.4.1 */
82184  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
82185  /* Added by 3.5.0 */
82186  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
82187  int (*blob_bytes)(sqlite3_blob*);
82188  int (*blob_close)(sqlite3_blob*);
82189  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
82190  int (*blob_read)(sqlite3_blob*,void*,int,int);
82191  int (*blob_write)(sqlite3_blob*,const void*,int,int);
82192  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
82193  int (*file_control)(sqlite3*,const char*,int,void*);
82194  sqlite3_int64 (*memory_highwater)(int);
82195  sqlite3_int64 (*memory_used)(void);
82196  sqlite3_mutex *(*mutex_alloc)(int);
82197  void (*mutex_enter)(sqlite3_mutex*);
82198  void (*mutex_free)(sqlite3_mutex*);
82199  void (*mutex_leave)(sqlite3_mutex*);
82200  int (*mutex_try)(sqlite3_mutex*);
82201  int (*open_v2)(const char*,sqlite3**,int,const char*);
82202  int (*release_memory)(int);
82203  void (*result_error_nomem)(sqlite3_context*);
82204  void (*result_error_toobig)(sqlite3_context*);
82205  int (*sleep)(int);
82206  void (*soft_heap_limit)(int);
82207  sqlite3_vfs *(*vfs_find)(const char*);
82208  int (*vfs_register)(sqlite3_vfs*,int);
82209  int (*vfs_unregister)(sqlite3_vfs*);
82210  int (*xthreadsafe)(void);
82211  void (*result_zeroblob)(sqlite3_context*,int);
82212  void (*result_error_code)(sqlite3_context*,int);
82213  int (*test_control)(int, ...);
82214  void (*randomness)(int,void*);
82215  sqlite3 *(*context_db_handle)(sqlite3_context*);
82216  int (*extended_result_codes)(sqlite3*,int);
82217  int (*limit)(sqlite3*,int,int);
82218  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
82219  const char *(*sql)(sqlite3_stmt*);
82220  int (*status)(int,int*,int*,int);
82221};
82222
82223/*
82224** The following macros redefine the API routines so that they are
82225** redirected throught the global sqlite3_api structure.
82226**
82227** This header file is also used by the loadext.c source file
82228** (part of the main SQLite library - not an extension) so that
82229** it can get access to the sqlite3_api_routines structure
82230** definition.  But the main library does not want to redefine
82231** the API.  So the redefinition macros are only valid if the
82232** SQLITE_CORE macros is undefined.
82233*/
82234#ifndef SQLITE_CORE
82235#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
82236#ifndef SQLITE_OMIT_DEPRECATED
82237#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
82238#endif
82239#define sqlite3_bind_blob              sqlite3_api->bind_blob
82240#define sqlite3_bind_double            sqlite3_api->bind_double
82241#define sqlite3_bind_int               sqlite3_api->bind_int
82242#define sqlite3_bind_int64             sqlite3_api->bind_int64
82243#define sqlite3_bind_null              sqlite3_api->bind_null
82244#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
82245#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
82246#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
82247#define sqlite3_bind_text              sqlite3_api->bind_text
82248#define sqlite3_bind_text16            sqlite3_api->bind_text16
82249#define sqlite3_bind_value             sqlite3_api->bind_value
82250#define sqlite3_busy_handler           sqlite3_api->busy_handler
82251#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
82252#define sqlite3_changes                sqlite3_api->changes
82253#define sqlite3_close                  sqlite3_api->close
82254#define sqlite3_collation_needed       sqlite3_api->collation_needed
82255#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
82256#define sqlite3_column_blob            sqlite3_api->column_blob
82257#define sqlite3_column_bytes           sqlite3_api->column_bytes
82258#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
82259#define sqlite3_column_count           sqlite3_api->column_count
82260#define sqlite3_column_database_name   sqlite3_api->column_database_name
82261#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
82262#define sqlite3_column_decltype        sqlite3_api->column_decltype
82263#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
82264#define sqlite3_column_double          sqlite3_api->column_double
82265#define sqlite3_column_int             sqlite3_api->column_int
82266#define sqlite3_column_int64           sqlite3_api->column_int64
82267#define sqlite3_column_name            sqlite3_api->column_name
82268#define sqlite3_column_name16          sqlite3_api->column_name16
82269#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
82270#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
82271#define sqlite3_column_table_name      sqlite3_api->column_table_name
82272#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
82273#define sqlite3_column_text            sqlite3_api->column_text
82274#define sqlite3_column_text16          sqlite3_api->column_text16
82275#define sqlite3_column_type            sqlite3_api->column_type
82276#define sqlite3_column_value           sqlite3_api->column_value
82277#define sqlite3_commit_hook            sqlite3_api->commit_hook
82278#define sqlite3_complete               sqlite3_api->complete
82279#define sqlite3_complete16             sqlite3_api->complete16
82280#define sqlite3_create_collation       sqlite3_api->create_collation
82281#define sqlite3_create_collation16     sqlite3_api->create_collation16
82282#define sqlite3_create_function        sqlite3_api->create_function
82283#define sqlite3_create_function16      sqlite3_api->create_function16
82284#define sqlite3_create_module          sqlite3_api->create_module
82285#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
82286#define sqlite3_data_count             sqlite3_api->data_count
82287#define sqlite3_db_handle              sqlite3_api->db_handle
82288#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
82289#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
82290#define sqlite3_errcode                sqlite3_api->errcode
82291#define sqlite3_errmsg                 sqlite3_api->errmsg
82292#define sqlite3_errmsg16               sqlite3_api->errmsg16
82293#define sqlite3_exec                   sqlite3_api->exec
82294#ifndef SQLITE_OMIT_DEPRECATED
82295#define sqlite3_expired                sqlite3_api->expired
82296#endif
82297#define sqlite3_finalize               sqlite3_api->finalize
82298#define sqlite3_free                   sqlite3_api->free
82299#define sqlite3_free_table             sqlite3_api->free_table
82300#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
82301#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
82302#define sqlite3_get_table              sqlite3_api->get_table
82303#ifndef SQLITE_OMIT_DEPRECATED
82304#define sqlite3_global_recover         sqlite3_api->global_recover
82305#endif
82306#define sqlite3_interrupt              sqlite3_api->interruptx
82307#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
82308#define sqlite3_libversion             sqlite3_api->libversion
82309#define sqlite3_libversion_number      sqlite3_api->libversion_number
82310#define sqlite3_malloc                 sqlite3_api->malloc
82311#define sqlite3_mprintf                sqlite3_api->mprintf
82312#define sqlite3_open                   sqlite3_api->open
82313#define sqlite3_open16                 sqlite3_api->open16
82314#define sqlite3_prepare                sqlite3_api->prepare
82315#define sqlite3_prepare16              sqlite3_api->prepare16
82316#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82317#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82318#define sqlite3_profile                sqlite3_api->profile
82319#define sqlite3_progress_handler       sqlite3_api->progress_handler
82320#define sqlite3_realloc                sqlite3_api->realloc
82321#define sqlite3_reset                  sqlite3_api->reset
82322#define sqlite3_result_blob            sqlite3_api->result_blob
82323#define sqlite3_result_double          sqlite3_api->result_double
82324#define sqlite3_result_error           sqlite3_api->result_error
82325#define sqlite3_result_error16         sqlite3_api->result_error16
82326#define sqlite3_result_int             sqlite3_api->result_int
82327#define sqlite3_result_int64           sqlite3_api->result_int64
82328#define sqlite3_result_null            sqlite3_api->result_null
82329#define sqlite3_result_text            sqlite3_api->result_text
82330#define sqlite3_result_text16          sqlite3_api->result_text16
82331#define sqlite3_result_text16be        sqlite3_api->result_text16be
82332#define sqlite3_result_text16le        sqlite3_api->result_text16le
82333#define sqlite3_result_value           sqlite3_api->result_value
82334#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
82335#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
82336#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
82337#define sqlite3_snprintf               sqlite3_api->snprintf
82338#define sqlite3_step                   sqlite3_api->step
82339#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
82340#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
82341#define sqlite3_total_changes          sqlite3_api->total_changes
82342#define sqlite3_trace                  sqlite3_api->trace
82343#ifndef SQLITE_OMIT_DEPRECATED
82344#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
82345#endif
82346#define sqlite3_update_hook            sqlite3_api->update_hook
82347#define sqlite3_user_data              sqlite3_api->user_data
82348#define sqlite3_value_blob             sqlite3_api->value_blob
82349#define sqlite3_value_bytes            sqlite3_api->value_bytes
82350#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
82351#define sqlite3_value_double           sqlite3_api->value_double
82352#define sqlite3_value_int              sqlite3_api->value_int
82353#define sqlite3_value_int64            sqlite3_api->value_int64
82354#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
82355#define sqlite3_value_text             sqlite3_api->value_text
82356#define sqlite3_value_text16           sqlite3_api->value_text16
82357#define sqlite3_value_text16be         sqlite3_api->value_text16be
82358#define sqlite3_value_text16le         sqlite3_api->value_text16le
82359#define sqlite3_value_type             sqlite3_api->value_type
82360#define sqlite3_vmprintf               sqlite3_api->vmprintf
82361#define sqlite3_overload_function      sqlite3_api->overload_function
82362#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82363#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82364#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
82365#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
82366#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
82367#define sqlite3_blob_close             sqlite3_api->blob_close
82368#define sqlite3_blob_open              sqlite3_api->blob_open
82369#define sqlite3_blob_read              sqlite3_api->blob_read
82370#define sqlite3_blob_write             sqlite3_api->blob_write
82371#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
82372#define sqlite3_file_control           sqlite3_api->file_control
82373#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
82374#define sqlite3_memory_used            sqlite3_api->memory_used
82375#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
82376#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
82377#define sqlite3_mutex_free             sqlite3_api->mutex_free
82378#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
82379#define sqlite3_mutex_try              sqlite3_api->mutex_try
82380#define sqlite3_open_v2                sqlite3_api->open_v2
82381#define sqlite3_release_memory         sqlite3_api->release_memory
82382#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
82383#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
82384#define sqlite3_sleep                  sqlite3_api->sleep
82385#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
82386#define sqlite3_vfs_find               sqlite3_api->vfs_find
82387#define sqlite3_vfs_register           sqlite3_api->vfs_register
82388#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
82389#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
82390#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
82391#define sqlite3_result_error_code      sqlite3_api->result_error_code
82392#define sqlite3_test_control           sqlite3_api->test_control
82393#define sqlite3_randomness             sqlite3_api->randomness
82394#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
82395#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
82396#define sqlite3_limit                  sqlite3_api->limit
82397#define sqlite3_next_stmt              sqlite3_api->next_stmt
82398#define sqlite3_sql                    sqlite3_api->sql
82399#define sqlite3_status                 sqlite3_api->status
82400#endif /* SQLITE_CORE */
82401
82402#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
82403#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
82404
82405#endif /* _SQLITE3EXT_H_ */
82406
82407/************** End of sqlite3ext.h ******************************************/
82408/************** Continuing where we left off in loadext.c ********************/
82409
82410#ifndef SQLITE_OMIT_LOAD_EXTENSION
82411
82412/*
82413** Some API routines are omitted when various features are
82414** excluded from a build of SQLite.  Substitute a NULL pointer
82415** for any missing APIs.
82416*/
82417#ifndef SQLITE_ENABLE_COLUMN_METADATA
82418# define sqlite3_column_database_name   0
82419# define sqlite3_column_database_name16 0
82420# define sqlite3_column_table_name      0
82421# define sqlite3_column_table_name16    0
82422# define sqlite3_column_origin_name     0
82423# define sqlite3_column_origin_name16   0
82424# define sqlite3_table_column_metadata  0
82425#endif
82426
82427#ifdef SQLITE_OMIT_AUTHORIZATION
82428# define sqlite3_set_authorizer         0
82429#endif
82430
82431#ifdef SQLITE_OMIT_UTF16
82432# define sqlite3_bind_text16            0
82433# define sqlite3_collation_needed16     0
82434# define sqlite3_column_decltype16      0
82435# define sqlite3_column_name16          0
82436# define sqlite3_column_text16          0
82437# define sqlite3_complete16             0
82438# define sqlite3_create_collation16     0
82439# define sqlite3_create_function16      0
82440# define sqlite3_errmsg16               0
82441# define sqlite3_open16                 0
82442# define sqlite3_prepare16              0
82443# define sqlite3_prepare16_v2           0
82444# define sqlite3_result_error16         0
82445# define sqlite3_result_text16          0
82446# define sqlite3_result_text16be        0
82447# define sqlite3_result_text16le        0
82448# define sqlite3_value_text16           0
82449# define sqlite3_value_text16be         0
82450# define sqlite3_value_text16le         0
82451# define sqlite3_column_database_name16 0
82452# define sqlite3_column_table_name16    0
82453# define sqlite3_column_origin_name16   0
82454#endif
82455
82456#ifdef SQLITE_OMIT_COMPLETE
82457# define sqlite3_complete 0
82458# define sqlite3_complete16 0
82459#endif
82460
82461#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
82462# define sqlite3_progress_handler 0
82463#endif
82464
82465#ifdef SQLITE_OMIT_VIRTUALTABLE
82466# define sqlite3_create_module 0
82467# define sqlite3_create_module_v2 0
82468# define sqlite3_declare_vtab 0
82469#endif
82470
82471#ifdef SQLITE_OMIT_SHARED_CACHE
82472# define sqlite3_enable_shared_cache 0
82473#endif
82474
82475#ifdef SQLITE_OMIT_TRACE
82476# define sqlite3_profile       0
82477# define sqlite3_trace         0
82478#endif
82479
82480#ifdef SQLITE_OMIT_GET_TABLE
82481# define sqlite3_free_table    0
82482# define sqlite3_get_table     0
82483#endif
82484
82485#ifdef SQLITE_OMIT_INCRBLOB
82486#define sqlite3_bind_zeroblob  0
82487#define sqlite3_blob_bytes     0
82488#define sqlite3_blob_close     0
82489#define sqlite3_blob_open      0
82490#define sqlite3_blob_read      0
82491#define sqlite3_blob_write     0
82492#endif
82493
82494/*
82495** The following structure contains pointers to all SQLite API routines.
82496** A pointer to this structure is passed into extensions when they are
82497** loaded so that the extension can make calls back into the SQLite
82498** library.
82499**
82500** When adding new APIs, add them to the bottom of this structure
82501** in order to preserve backwards compatibility.
82502**
82503** Extensions that use newer APIs should first call the
82504** sqlite3_libversion_number() to make sure that the API they
82505** intend to use is supported by the library.  Extensions should
82506** also check to make sure that the pointer to the function is
82507** not NULL before calling it.
82508*/
82509static const sqlite3_api_routines sqlite3Apis = {
82510  sqlite3_aggregate_context,
82511#ifndef SQLITE_OMIT_DEPRECATED
82512  sqlite3_aggregate_count,
82513#else
82514  0,
82515#endif
82516  sqlite3_bind_blob,
82517  sqlite3_bind_double,
82518  sqlite3_bind_int,
82519  sqlite3_bind_int64,
82520  sqlite3_bind_null,
82521  sqlite3_bind_parameter_count,
82522  sqlite3_bind_parameter_index,
82523  sqlite3_bind_parameter_name,
82524  sqlite3_bind_text,
82525  sqlite3_bind_text16,
82526  sqlite3_bind_value,
82527  sqlite3_busy_handler,
82528  sqlite3_busy_timeout,
82529  sqlite3_changes,
82530  sqlite3_close,
82531  sqlite3_collation_needed,
82532  sqlite3_collation_needed16,
82533  sqlite3_column_blob,
82534  sqlite3_column_bytes,
82535  sqlite3_column_bytes16,
82536  sqlite3_column_count,
82537  sqlite3_column_database_name,
82538  sqlite3_column_database_name16,
82539  sqlite3_column_decltype,
82540  sqlite3_column_decltype16,
82541  sqlite3_column_double,
82542  sqlite3_column_int,
82543  sqlite3_column_int64,
82544  sqlite3_column_name,
82545  sqlite3_column_name16,
82546  sqlite3_column_origin_name,
82547  sqlite3_column_origin_name16,
82548  sqlite3_column_table_name,
82549  sqlite3_column_table_name16,
82550  sqlite3_column_text,
82551  sqlite3_column_text16,
82552  sqlite3_column_type,
82553  sqlite3_column_value,
82554  sqlite3_commit_hook,
82555  sqlite3_complete,
82556  sqlite3_complete16,
82557  sqlite3_create_collation,
82558  sqlite3_create_collation16,
82559  sqlite3_create_function,
82560  sqlite3_create_function16,
82561  sqlite3_create_module,
82562  sqlite3_data_count,
82563  sqlite3_db_handle,
82564  sqlite3_declare_vtab,
82565  sqlite3_enable_shared_cache,
82566  sqlite3_errcode,
82567  sqlite3_errmsg,
82568  sqlite3_errmsg16,
82569  sqlite3_exec,
82570#ifndef SQLITE_OMIT_DEPRECATED
82571  sqlite3_expired,
82572#else
82573  0,
82574#endif
82575  sqlite3_finalize,
82576  sqlite3_free,
82577  sqlite3_free_table,
82578  sqlite3_get_autocommit,
82579  sqlite3_get_auxdata,
82580  sqlite3_get_table,
82581  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
82582  sqlite3_interrupt,
82583  sqlite3_last_insert_rowid,
82584  sqlite3_libversion,
82585  sqlite3_libversion_number,
82586  sqlite3_malloc,
82587  sqlite3_mprintf,
82588  sqlite3_open,
82589  sqlite3_open16,
82590  sqlite3_prepare,
82591  sqlite3_prepare16,
82592  sqlite3_profile,
82593  sqlite3_progress_handler,
82594  sqlite3_realloc,
82595  sqlite3_reset,
82596  sqlite3_result_blob,
82597  sqlite3_result_double,
82598  sqlite3_result_error,
82599  sqlite3_result_error16,
82600  sqlite3_result_int,
82601  sqlite3_result_int64,
82602  sqlite3_result_null,
82603  sqlite3_result_text,
82604  sqlite3_result_text16,
82605  sqlite3_result_text16be,
82606  sqlite3_result_text16le,
82607  sqlite3_result_value,
82608  sqlite3_rollback_hook,
82609  sqlite3_set_authorizer,
82610  sqlite3_set_auxdata,
82611  sqlite3_snprintf,
82612  sqlite3_step,
82613  sqlite3_table_column_metadata,
82614#ifndef SQLITE_OMIT_DEPRECATED
82615  sqlite3_thread_cleanup,
82616#else
82617  0,
82618#endif
82619  sqlite3_total_changes,
82620  sqlite3_trace,
82621#ifndef SQLITE_OMIT_DEPRECATED
82622  sqlite3_transfer_bindings,
82623#else
82624  0,
82625#endif
82626  sqlite3_update_hook,
82627  sqlite3_user_data,
82628  sqlite3_value_blob,
82629  sqlite3_value_bytes,
82630  sqlite3_value_bytes16,
82631  sqlite3_value_double,
82632  sqlite3_value_int,
82633  sqlite3_value_int64,
82634  sqlite3_value_numeric_type,
82635  sqlite3_value_text,
82636  sqlite3_value_text16,
82637  sqlite3_value_text16be,
82638  sqlite3_value_text16le,
82639  sqlite3_value_type,
82640  sqlite3_vmprintf,
82641  /*
82642  ** The original API set ends here.  All extensions can call any
82643  ** of the APIs above provided that the pointer is not NULL.  But
82644  ** before calling APIs that follow, extension should check the
82645  ** sqlite3_libversion_number() to make sure they are dealing with
82646  ** a library that is new enough to support that API.
82647  *************************************************************************
82648  */
82649  sqlite3_overload_function,
82650
82651  /*
82652  ** Added after 3.3.13
82653  */
82654  sqlite3_prepare_v2,
82655  sqlite3_prepare16_v2,
82656  sqlite3_clear_bindings,
82657
82658  /*
82659  ** Added for 3.4.1
82660  */
82661  sqlite3_create_module_v2,
82662
82663  /*
82664  ** Added for 3.5.0
82665  */
82666  sqlite3_bind_zeroblob,
82667  sqlite3_blob_bytes,
82668  sqlite3_blob_close,
82669  sqlite3_blob_open,
82670  sqlite3_blob_read,
82671  sqlite3_blob_write,
82672  sqlite3_create_collation_v2,
82673  sqlite3_file_control,
82674  sqlite3_memory_highwater,
82675  sqlite3_memory_used,
82676#ifdef SQLITE_MUTEX_OMIT
82677  0,
82678  0,
82679  0,
82680  0,
82681  0,
82682#else
82683  sqlite3_mutex_alloc,
82684  sqlite3_mutex_enter,
82685  sqlite3_mutex_free,
82686  sqlite3_mutex_leave,
82687  sqlite3_mutex_try,
82688#endif
82689  sqlite3_open_v2,
82690  sqlite3_release_memory,
82691  sqlite3_result_error_nomem,
82692  sqlite3_result_error_toobig,
82693  sqlite3_sleep,
82694  sqlite3_soft_heap_limit,
82695  sqlite3_vfs_find,
82696  sqlite3_vfs_register,
82697  sqlite3_vfs_unregister,
82698
82699  /*
82700  ** Added for 3.5.8
82701  */
82702  sqlite3_threadsafe,
82703  sqlite3_result_zeroblob,
82704  sqlite3_result_error_code,
82705  sqlite3_test_control,
82706  sqlite3_randomness,
82707  sqlite3_context_db_handle,
82708
82709  /*
82710  ** Added for 3.6.0
82711  */
82712  sqlite3_extended_result_codes,
82713  sqlite3_limit,
82714  sqlite3_next_stmt,
82715  sqlite3_sql,
82716  sqlite3_status,
82717};
82718
82719/*
82720** Attempt to load an SQLite extension library contained in the file
82721** zFile.  The entry point is zProc.  zProc may be 0 in which case a
82722** default entry point name (sqlite3_extension_init) is used.  Use
82723** of the default name is recommended.
82724**
82725** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
82726**
82727** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
82728** error message text.  The calling function should free this memory
82729** by calling sqlite3DbFree(db, ).
82730*/
82731static int sqlite3LoadExtension(
82732  sqlite3 *db,          /* Load the extension into this database connection */
82733  const char *zFile,    /* Name of the shared library containing extension */
82734  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
82735  char **pzErrMsg       /* Put error message here if not 0 */
82736){
82737  sqlite3_vfs *pVfs = db->pVfs;
82738  void *handle;
82739  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
82740  char *zErrmsg = 0;
82741  void **aHandle;
82742  const int nMsg = 300;
82743
82744  if( pzErrMsg ) *pzErrMsg = 0;
82745
82746  /* Ticket #1863.  To avoid a creating security problems for older
82747  ** applications that relink against newer versions of SQLite, the
82748  ** ability to run load_extension is turned off by default.  One
82749  ** must call sqlite3_enable_load_extension() to turn on extension
82750  ** loading.  Otherwise you get the following error.
82751  */
82752  if( (db->flags & SQLITE_LoadExtension)==0 ){
82753    if( pzErrMsg ){
82754      *pzErrMsg = sqlite3_mprintf("not authorized");
82755    }
82756    return SQLITE_ERROR;
82757  }
82758
82759  if( zProc==0 ){
82760    zProc = "sqlite3_extension_init";
82761  }
82762
82763  handle = sqlite3OsDlOpen(pVfs, zFile);
82764  if( handle==0 ){
82765    if( pzErrMsg ){
82766      zErrmsg = sqlite3StackAllocZero(db, nMsg);
82767      if( zErrmsg ){
82768        sqlite3_snprintf(nMsg, zErrmsg,
82769            "unable to open shared library [%s]", zFile);
82770        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
82771        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
82772        sqlite3StackFree(db, zErrmsg);
82773      }
82774    }
82775    return SQLITE_ERROR;
82776  }
82777  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
82778                   sqlite3OsDlSym(pVfs, handle, zProc);
82779  if( xInit==0 ){
82780    if( pzErrMsg ){
82781      zErrmsg = sqlite3StackAllocZero(db, nMsg);
82782      if( zErrmsg ){
82783        sqlite3_snprintf(nMsg, zErrmsg,
82784            "no entry point [%s] in shared library [%s]", zProc,zFile);
82785        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
82786        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
82787        sqlite3StackFree(db, zErrmsg);
82788      }
82789      sqlite3OsDlClose(pVfs, handle);
82790    }
82791    return SQLITE_ERROR;
82792  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
82793    if( pzErrMsg ){
82794      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
82795    }
82796    sqlite3_free(zErrmsg);
82797    sqlite3OsDlClose(pVfs, handle);
82798    return SQLITE_ERROR;
82799  }
82800
82801  /* Append the new shared library handle to the db->aExtension array. */
82802  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
82803  if( aHandle==0 ){
82804    return SQLITE_NOMEM;
82805  }
82806  if( db->nExtension>0 ){
82807    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
82808  }
82809  sqlite3DbFree(db, db->aExtension);
82810  db->aExtension = aHandle;
82811
82812  db->aExtension[db->nExtension++] = handle;
82813  return SQLITE_OK;
82814}
82815SQLITE_API int sqlite3_load_extension(
82816  sqlite3 *db,          /* Load the extension into this database connection */
82817  const char *zFile,    /* Name of the shared library containing extension */
82818  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
82819  char **pzErrMsg       /* Put error message here if not 0 */
82820){
82821  int rc;
82822  sqlite3_mutex_enter(db->mutex);
82823  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
82824  rc = sqlite3ApiExit(db, rc);
82825  sqlite3_mutex_leave(db->mutex);
82826  return rc;
82827}
82828
82829/*
82830** Call this routine when the database connection is closing in order
82831** to clean up loaded extensions
82832*/
82833SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
82834  int i;
82835  assert( sqlite3_mutex_held(db->mutex) );
82836  for(i=0; i<db->nExtension; i++){
82837    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
82838  }
82839  sqlite3DbFree(db, db->aExtension);
82840}
82841
82842/*
82843** Enable or disable extension loading.  Extension loading is disabled by
82844** default so as not to open security holes in older applications.
82845*/
82846SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
82847  sqlite3_mutex_enter(db->mutex);
82848  if( onoff ){
82849    db->flags |= SQLITE_LoadExtension;
82850  }else{
82851    db->flags &= ~SQLITE_LoadExtension;
82852  }
82853  sqlite3_mutex_leave(db->mutex);
82854  return SQLITE_OK;
82855}
82856
82857#endif /* SQLITE_OMIT_LOAD_EXTENSION */
82858
82859/*
82860** The auto-extension code added regardless of whether or not extension
82861** loading is supported.  We need a dummy sqlite3Apis pointer for that
82862** code if regular extension loading is not available.  This is that
82863** dummy pointer.
82864*/
82865#ifdef SQLITE_OMIT_LOAD_EXTENSION
82866static const sqlite3_api_routines sqlite3Apis = { 0 };
82867#endif
82868
82869
82870/*
82871** The following object holds the list of automatically loaded
82872** extensions.
82873**
82874** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
82875** mutex must be held while accessing this list.
82876*/
82877typedef struct sqlite3AutoExtList sqlite3AutoExtList;
82878static SQLITE_WSD struct sqlite3AutoExtList {
82879  int nExt;              /* Number of entries in aExt[] */
82880  void (**aExt)(void);   /* Pointers to the extension init functions */
82881} sqlite3Autoext = { 0, 0 };
82882
82883/* The "wsdAutoext" macro will resolve to the autoextension
82884** state vector.  If writable static data is unsupported on the target,
82885** we have to locate the state vector at run-time.  In the more common
82886** case where writable static data is supported, wsdStat can refer directly
82887** to the "sqlite3Autoext" state vector declared above.
82888*/
82889#ifdef SQLITE_OMIT_WSD
82890# define wsdAutoextInit \
82891  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
82892# define wsdAutoext x[0]
82893#else
82894# define wsdAutoextInit
82895# define wsdAutoext sqlite3Autoext
82896#endif
82897
82898
82899/*
82900** Register a statically linked extension that is automatically
82901** loaded by every new database connection.
82902*/
82903SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
82904  int rc = SQLITE_OK;
82905#ifndef SQLITE_OMIT_AUTOINIT
82906  rc = sqlite3_initialize();
82907  if( rc ){
82908    return rc;
82909  }else
82910#endif
82911  {
82912    int i;
82913#if SQLITE_THREADSAFE
82914    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
82915#endif
82916    wsdAutoextInit;
82917    sqlite3_mutex_enter(mutex);
82918    for(i=0; i<wsdAutoext.nExt; i++){
82919      if( wsdAutoext.aExt[i]==xInit ) break;
82920    }
82921    if( i==wsdAutoext.nExt ){
82922      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
82923      void (**aNew)(void);
82924      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
82925      if( aNew==0 ){
82926        rc = SQLITE_NOMEM;
82927      }else{
82928        wsdAutoext.aExt = aNew;
82929        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
82930        wsdAutoext.nExt++;
82931      }
82932    }
82933    sqlite3_mutex_leave(mutex);
82934    assert( (rc&0xff)==rc );
82935    return rc;
82936  }
82937}
82938
82939/*
82940** Reset the automatic extension loading mechanism.
82941*/
82942SQLITE_API void sqlite3_reset_auto_extension(void){
82943#ifndef SQLITE_OMIT_AUTOINIT
82944  if( sqlite3_initialize()==SQLITE_OK )
82945#endif
82946  {
82947#if SQLITE_THREADSAFE
82948    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
82949#endif
82950    wsdAutoextInit;
82951    sqlite3_mutex_enter(mutex);
82952    sqlite3_free(wsdAutoext.aExt);
82953    wsdAutoext.aExt = 0;
82954    wsdAutoext.nExt = 0;
82955    sqlite3_mutex_leave(mutex);
82956  }
82957}
82958
82959/*
82960** Load all automatic extensions.
82961**
82962** If anything goes wrong, set an error in the database connection.
82963*/
82964SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
82965  int i;
82966  int go = 1;
82967  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
82968
82969  wsdAutoextInit;
82970  if( wsdAutoext.nExt==0 ){
82971    /* Common case: early out without every having to acquire a mutex */
82972    return;
82973  }
82974  for(i=0; go; i++){
82975    char *zErrmsg;
82976#if SQLITE_THREADSAFE
82977    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
82978#endif
82979    sqlite3_mutex_enter(mutex);
82980    if( i>=wsdAutoext.nExt ){
82981      xInit = 0;
82982      go = 0;
82983    }else{
82984      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
82985              wsdAutoext.aExt[i];
82986    }
82987    sqlite3_mutex_leave(mutex);
82988    zErrmsg = 0;
82989    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
82990      sqlite3Error(db, SQLITE_ERROR,
82991            "automatic extension loading failed: %s", zErrmsg);
82992      go = 0;
82993    }
82994    sqlite3_free(zErrmsg);
82995  }
82996}
82997
82998/************** End of loadext.c *********************************************/
82999/************** Begin file pragma.c ******************************************/
83000/*
83001** 2003 April 6
83002**
83003** The author disclaims copyright to this source code.  In place of
83004** a legal notice, here is a blessing:
83005**
83006**    May you do good and not evil.
83007**    May you find forgiveness for yourself and forgive others.
83008**    May you share freely, never taking more than you give.
83009**
83010*************************************************************************
83011** This file contains code used to implement the PRAGMA command.
83012*/
83013
83014/* Ignore this whole file if pragmas are disabled
83015*/
83016#if !defined(SQLITE_OMIT_PRAGMA)
83017
83018/*
83019** Interpret the given string as a safety level.  Return 0 for OFF,
83020** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
83021** unrecognized string argument.
83022**
83023** Note that the values returned are one less that the values that
83024** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
83025** to support legacy SQL code.  The safety level used to be boolean
83026** and older scripts may have used numbers 0 for OFF and 1 for ON.
83027*/
83028static u8 getSafetyLevel(const char *z){
83029                             /* 123456789 123456789 */
83030  static const char zText[] = "onoffalseyestruefull";
83031  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
83032  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
83033  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
83034  int i, n;
83035  if( sqlite3Isdigit(*z) ){
83036    return (u8)atoi(z);
83037  }
83038  n = sqlite3Strlen30(z);
83039  for(i=0; i<ArraySize(iLength); i++){
83040    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
83041      return iValue[i];
83042    }
83043  }
83044  return 1;
83045}
83046
83047/*
83048** Interpret the given string as a boolean value.
83049*/
83050static u8 getBoolean(const char *z){
83051  return getSafetyLevel(z)&1;
83052}
83053
83054/*
83055** Interpret the given string as a locking mode value.
83056*/
83057static int getLockingMode(const char *z){
83058  if( z ){
83059    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
83060    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
83061  }
83062  return PAGER_LOCKINGMODE_QUERY;
83063}
83064
83065#ifndef SQLITE_OMIT_AUTOVACUUM
83066/*
83067** Interpret the given string as an auto-vacuum mode value.
83068**
83069** The following strings, "none", "full" and "incremental" are
83070** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
83071*/
83072static int getAutoVacuum(const char *z){
83073  int i;
83074  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
83075  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
83076  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
83077  i = atoi(z);
83078  return (u8)((i>=0&&i<=2)?i:0);
83079}
83080#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
83081
83082#ifndef SQLITE_OMIT_PAGER_PRAGMAS
83083/*
83084** Interpret the given string as a temp db location. Return 1 for file
83085** backed temporary databases, 2 for the Red-Black tree in memory database
83086** and 0 to use the compile-time default.
83087*/
83088static int getTempStore(const char *z){
83089  if( z[0]>='0' && z[0]<='2' ){
83090    return z[0] - '0';
83091  }else if( sqlite3StrICmp(z, "file")==0 ){
83092    return 1;
83093  }else if( sqlite3StrICmp(z, "memory")==0 ){
83094    return 2;
83095  }else{
83096    return 0;
83097  }
83098}
83099#endif /* SQLITE_PAGER_PRAGMAS */
83100
83101#ifndef SQLITE_OMIT_PAGER_PRAGMAS
83102/*
83103** Invalidate temp storage, either when the temp storage is changed
83104** from default, or when 'file' and the temp_store_directory has changed
83105*/
83106static int invalidateTempStorage(Parse *pParse){
83107  sqlite3 *db = pParse->db;
83108  if( db->aDb[1].pBt!=0 ){
83109    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
83110      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
83111        "from within a transaction");
83112      return SQLITE_ERROR;
83113    }
83114    sqlite3BtreeClose(db->aDb[1].pBt);
83115    db->aDb[1].pBt = 0;
83116    sqlite3ResetInternalSchema(db, 0);
83117  }
83118  return SQLITE_OK;
83119}
83120#endif /* SQLITE_PAGER_PRAGMAS */
83121
83122#ifndef SQLITE_OMIT_PAGER_PRAGMAS
83123/*
83124** If the TEMP database is open, close it and mark the database schema
83125** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
83126** or DEFAULT_TEMP_STORE pragmas.
83127*/
83128static int changeTempStorage(Parse *pParse, const char *zStorageType){
83129  int ts = getTempStore(zStorageType);
83130  sqlite3 *db = pParse->db;
83131  if( db->temp_store==ts ) return SQLITE_OK;
83132  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
83133    return SQLITE_ERROR;
83134  }
83135  db->temp_store = (u8)ts;
83136  return SQLITE_OK;
83137}
83138#endif /* SQLITE_PAGER_PRAGMAS */
83139
83140/*
83141** Generate code to return a single integer value.
83142*/
83143static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
83144  Vdbe *v = sqlite3GetVdbe(pParse);
83145  int mem = ++pParse->nMem;
83146  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
83147  if( pI64 ){
83148    memcpy(pI64, &value, sizeof(value));
83149  }
83150  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
83151  sqlite3VdbeSetNumCols(v, 1);
83152  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
83153  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
83154}
83155
83156#ifndef SQLITE_OMIT_FLAG_PRAGMAS
83157/*
83158** Check to see if zRight and zLeft refer to a pragma that queries
83159** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
83160** Also, implement the pragma.
83161*/
83162static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
83163  static const struct sPragmaType {
83164    const char *zName;  /* Name of the pragma */
83165    int mask;           /* Mask for the db->flags value */
83166  } aPragma[] = {
83167    { "full_column_names",        SQLITE_FullColNames  },
83168    { "short_column_names",       SQLITE_ShortColNames },
83169    { "count_changes",            SQLITE_CountRows     },
83170    { "empty_result_callbacks",   SQLITE_NullCallback  },
83171    { "legacy_file_format",       SQLITE_LegacyFileFmt },
83172    { "fullfsync",                SQLITE_FullFSync     },
83173    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
83174#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
83175    { "automatic_index",          SQLITE_AutoIndex     },
83176#endif
83177#ifdef SQLITE_DEBUG
83178    { "sql_trace",                SQLITE_SqlTrace      },
83179    { "vdbe_listing",             SQLITE_VdbeListing   },
83180    { "vdbe_trace",               SQLITE_VdbeTrace     },
83181#endif
83182#ifndef SQLITE_OMIT_CHECK
83183    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
83184#endif
83185    /* The following is VERY experimental */
83186    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
83187    { "omit_readlock",            SQLITE_NoReadlock    },
83188
83189    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
83190    ** flag if there are any active statements. */
83191    { "read_uncommitted",         SQLITE_ReadUncommitted },
83192    { "recursive_triggers",       SQLITE_RecTriggers },
83193
83194    /* This flag may only be set if both foreign-key and trigger support
83195    ** are present in the build.  */
83196#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
83197    { "foreign_keys",             SQLITE_ForeignKeys },
83198#endif
83199  };
83200  int i;
83201  const struct sPragmaType *p;
83202  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
83203    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
83204      sqlite3 *db = pParse->db;
83205      Vdbe *v;
83206      v = sqlite3GetVdbe(pParse);
83207      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
83208      if( ALWAYS(v) ){
83209        if( zRight==0 ){
83210          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
83211        }else{
83212          int mask = p->mask;          /* Mask of bits to set or clear. */
83213          if( db->autoCommit==0 ){
83214            /* Foreign key support may not be enabled or disabled while not
83215            ** in auto-commit mode.  */
83216            mask &= ~(SQLITE_ForeignKeys);
83217          }
83218
83219          if( getBoolean(zRight) ){
83220            db->flags |= mask;
83221          }else{
83222            db->flags &= ~mask;
83223          }
83224
83225          /* Many of the flag-pragmas modify the code generated by the SQL
83226          ** compiler (eg. count_changes). So add an opcode to expire all
83227          ** compiled SQL statements after modifying a pragma value.
83228          */
83229          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
83230        }
83231      }
83232
83233      return 1;
83234    }
83235  }
83236  return 0;
83237}
83238#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
83239
83240/*
83241** Return a human-readable name for a constraint resolution action.
83242*/
83243#ifndef SQLITE_OMIT_FOREIGN_KEY
83244static const char *actionName(u8 action){
83245  const char *zName;
83246  switch( action ){
83247    case OE_SetNull:  zName = "SET NULL";        break;
83248    case OE_SetDflt:  zName = "SET DEFAULT";     break;
83249    case OE_Cascade:  zName = "CASCADE";         break;
83250    case OE_Restrict: zName = "RESTRICT";        break;
83251    default:          zName = "NO ACTION";
83252                      assert( action==OE_None ); break;
83253  }
83254  return zName;
83255}
83256#endif
83257
83258
83259/*
83260** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
83261** defined in pager.h. This function returns the associated lowercase
83262** journal-mode name.
83263*/
83264SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
83265  static char * const azModeName[] = {
83266    "delete", "persist", "off", "truncate", "memory"
83267#ifndef SQLITE_OMIT_WAL
83268     , "wal"
83269#endif
83270  };
83271  assert( PAGER_JOURNALMODE_DELETE==0 );
83272  assert( PAGER_JOURNALMODE_PERSIST==1 );
83273  assert( PAGER_JOURNALMODE_OFF==2 );
83274  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
83275  assert( PAGER_JOURNALMODE_MEMORY==4 );
83276  assert( PAGER_JOURNALMODE_WAL==5 );
83277  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
83278
83279  if( eMode==ArraySize(azModeName) ) return 0;
83280  return azModeName[eMode];
83281}
83282
83283/*
83284** Process a pragma statement.
83285**
83286** Pragmas are of this form:
83287**
83288**      PRAGMA [database.]id [= value]
83289**
83290** The identifier might also be a string.  The value is a string, and
83291** identifier, or a number.  If minusFlag is true, then the value is
83292** a number that was preceded by a minus sign.
83293**
83294** If the left side is "database.id" then pId1 is the database name
83295** and pId2 is the id.  If the left side is just "id" then pId1 is the
83296** id and pId2 is any empty string.
83297*/
83298SQLITE_PRIVATE void sqlite3Pragma(
83299  Parse *pParse,
83300  Token *pId1,        /* First part of [database.]id field */
83301  Token *pId2,        /* Second part of [database.]id field, or NULL */
83302  Token *pValue,      /* Token for <value>, or NULL */
83303  int minusFlag       /* True if a '-' sign preceded <value> */
83304){
83305  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
83306  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
83307  const char *zDb = 0;   /* The database name */
83308  Token *pId;            /* Pointer to <id> token */
83309  int iDb;               /* Database index for <database> */
83310  sqlite3 *db = pParse->db;
83311  Db *pDb;
83312  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
83313  if( v==0 ) return;
83314  sqlite3VdbeRunOnlyOnce(v);
83315  pParse->nMem = 2;
83316
83317  /* Interpret the [database.] part of the pragma statement. iDb is the
83318  ** index of the database this pragma is being applied to in db.aDb[]. */
83319  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
83320  if( iDb<0 ) return;
83321  pDb = &db->aDb[iDb];
83322
83323  /* If the temp database has been explicitly named as part of the
83324  ** pragma, make sure it is open.
83325  */
83326  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
83327    return;
83328  }
83329
83330  zLeft = sqlite3NameFromToken(db, pId);
83331  if( !zLeft ) return;
83332  if( minusFlag ){
83333    zRight = sqlite3MPrintf(db, "-%T", pValue);
83334  }else{
83335    zRight = sqlite3NameFromToken(db, pValue);
83336  }
83337
83338  assert( pId2 );
83339  zDb = pId2->n>0 ? pDb->zName : 0;
83340  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
83341    goto pragma_out;
83342  }
83343
83344#ifndef SQLITE_OMIT_PAGER_PRAGMAS
83345  /*
83346  **  PRAGMA [database.]default_cache_size
83347  **  PRAGMA [database.]default_cache_size=N
83348  **
83349  ** The first form reports the current persistent setting for the
83350  ** page cache size.  The value returned is the maximum number of
83351  ** pages in the page cache.  The second form sets both the current
83352  ** page cache size value and the persistent page cache size value
83353  ** stored in the database file.
83354  **
83355  ** Older versions of SQLite would set the default cache size to a
83356  ** negative number to indicate synchronous=OFF.  These days, synchronous
83357  ** is always on by default regardless of the sign of the default cache
83358  ** size.  But continue to take the absolute value of the default cache
83359  ** size of historical compatibility.
83360  */
83361  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
83362    static const VdbeOpList getCacheSize[] = {
83363      { OP_Transaction, 0, 0,        0},                         /* 0 */
83364      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
83365      { OP_IfPos,       1, 7,        0},
83366      { OP_Integer,     0, 2,        0},
83367      { OP_Subtract,    1, 2,        1},
83368      { OP_IfPos,       1, 7,        0},
83369      { OP_Integer,     0, 1,        0},                         /* 6 */
83370      { OP_ResultRow,   1, 1,        0},
83371    };
83372    int addr;
83373    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83374    sqlite3VdbeUsesBtree(v, iDb);
83375    if( !zRight ){
83376      sqlite3VdbeSetNumCols(v, 1);
83377      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
83378      pParse->nMem += 2;
83379      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
83380      sqlite3VdbeChangeP1(v, addr, iDb);
83381      sqlite3VdbeChangeP1(v, addr+1, iDb);
83382      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
83383    }else{
83384      int size = atoi(zRight);
83385      if( size<0 ) size = -size;
83386      sqlite3BeginWriteOperation(pParse, 0, iDb);
83387      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
83388      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
83389      pDb->pSchema->cache_size = size;
83390      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
83391    }
83392  }else
83393
83394  /*
83395  **  PRAGMA [database.]page_size
83396  **  PRAGMA [database.]page_size=N
83397  **
83398  ** The first form reports the current setting for the
83399  ** database page size in bytes.  The second form sets the
83400  ** database page size value.  The value can only be set if
83401  ** the database has not yet been created.
83402  */
83403  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
83404    Btree *pBt = pDb->pBt;
83405    assert( pBt!=0 );
83406    if( !zRight ){
83407      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
83408      returnSingleInt(pParse, "page_size", size);
83409    }else{
83410      /* Malloc may fail when setting the page-size, as there is an internal
83411      ** buffer that the pager module resizes using sqlite3_realloc().
83412      */
83413      db->nextPagesize = atoi(zRight);
83414      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
83415        db->mallocFailed = 1;
83416      }
83417    }
83418  }else
83419
83420  /*
83421  **  PRAGMA [database.]max_page_count
83422  **  PRAGMA [database.]max_page_count=N
83423  **
83424  ** The first form reports the current setting for the
83425  ** maximum number of pages in the database file.  The
83426  ** second form attempts to change this setting.  Both
83427  ** forms return the current setting.
83428  */
83429  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
83430    Btree *pBt = pDb->pBt;
83431    int newMax = 0;
83432    assert( pBt!=0 );
83433    if( zRight ){
83434      newMax = atoi(zRight);
83435    }
83436    if( ALWAYS(pBt) ){
83437      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
83438    }
83439    returnSingleInt(pParse, "max_page_count", newMax);
83440  }else
83441
83442  /*
83443  **  PRAGMA [database.]secure_delete
83444  **  PRAGMA [database.]secure_delete=ON/OFF
83445  **
83446  ** The first form reports the current setting for the
83447  ** secure_delete flag.  The second form changes the secure_delete
83448  ** flag setting and reports thenew value.
83449  */
83450  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
83451    Btree *pBt = pDb->pBt;
83452    int b = -1;
83453    assert( pBt!=0 );
83454    if( zRight ){
83455      b = getBoolean(zRight);
83456    }
83457    if( pId2->n==0 && b>=0 ){
83458      int ii;
83459      for(ii=0; ii<db->nDb; ii++){
83460        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
83461      }
83462    }
83463    b = sqlite3BtreeSecureDelete(pBt, b);
83464    returnSingleInt(pParse, "secure_delete", b);
83465  }else
83466
83467  /*
83468  **  PRAGMA [database.]page_count
83469  **
83470  ** Return the number of pages in the specified database.
83471  */
83472  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
83473    int iReg;
83474    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83475    sqlite3CodeVerifySchema(pParse, iDb);
83476    iReg = ++pParse->nMem;
83477    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
83478    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
83479    sqlite3VdbeSetNumCols(v, 1);
83480    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
83481  }else
83482
83483  /*
83484  **  PRAGMA [database.]locking_mode
83485  **  PRAGMA [database.]locking_mode = (normal|exclusive)
83486  */
83487  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
83488    const char *zRet = "normal";
83489    int eMode = getLockingMode(zRight);
83490
83491    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
83492      /* Simple "PRAGMA locking_mode;" statement. This is a query for
83493      ** the current default locking mode (which may be different to
83494      ** the locking-mode of the main database).
83495      */
83496      eMode = db->dfltLockMode;
83497    }else{
83498      Pager *pPager;
83499      if( pId2->n==0 ){
83500        /* This indicates that no database name was specified as part
83501        ** of the PRAGMA command. In this case the locking-mode must be
83502        ** set on all attached databases, as well as the main db file.
83503        **
83504        ** Also, the sqlite3.dfltLockMode variable is set so that
83505        ** any subsequently attached databases also use the specified
83506        ** locking mode.
83507        */
83508        int ii;
83509        assert(pDb==&db->aDb[0]);
83510        for(ii=2; ii<db->nDb; ii++){
83511          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
83512          sqlite3PagerLockingMode(pPager, eMode);
83513        }
83514        db->dfltLockMode = (u8)eMode;
83515      }
83516      pPager = sqlite3BtreePager(pDb->pBt);
83517      eMode = sqlite3PagerLockingMode(pPager, eMode);
83518    }
83519
83520    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
83521    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
83522      zRet = "exclusive";
83523    }
83524    sqlite3VdbeSetNumCols(v, 1);
83525    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
83526    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
83527    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83528  }else
83529
83530  /*
83531  **  PRAGMA [database.]journal_mode
83532  **  PRAGMA [database.]journal_mode =
83533  **                      (delete|persist|off|truncate|memory|wal|off)
83534  */
83535  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
83536    int eMode;                    /* One of the PAGER_JOURNALMODE_XXX symbols */
83537
83538    sqlite3VdbeSetNumCols(v, 1);
83539    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
83540
83541    if( zRight==0 ){
83542      eMode = PAGER_JOURNALMODE_QUERY;
83543    }else{
83544      const char *zMode;
83545      int n = sqlite3Strlen30(zRight);
83546      for(eMode=0; (zMode = sqlite3JournalModename(eMode)); eMode++){
83547        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
83548      }
83549      if( !zMode ){
83550        eMode = PAGER_JOURNALMODE_QUERY;
83551      }
83552    }
83553    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
83554      /* Simple "PRAGMA journal_mode;" statement. This is a query for
83555      ** the current default journal mode (which may be different to
83556      ** the journal-mode of the main database).
83557      */
83558      eMode = db->dfltJournalMode;
83559      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
83560      sqlite3VdbeChangeP4(v, -1, sqlite3JournalModename(eMode), P4_STATIC);
83561    }else{
83562      int ii;
83563
83564      if( pId2->n==0 ){
83565        /* When there is no database name before the "journal_mode" keyword
83566        ** in the PRAGMA, then the journal-mode will be set on
83567        ** all attached databases, as well as the main db file.
83568        **
83569        ** Also, the sqlite3.dfltJournalMode variable is set so that
83570        ** any subsequently attached databases also use the specified
83571        ** journal mode.
83572        */
83573        db->dfltJournalMode = (u8)eMode;
83574      }
83575
83576      for(ii=db->nDb-1; ii>=0; ii--){
83577        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
83578          sqlite3VdbeUsesBtree(v, ii);
83579          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
83580        }
83581      }
83582    }
83583
83584    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83585  }else
83586
83587  /*
83588  **  PRAGMA [database.]journal_size_limit
83589  **  PRAGMA [database.]journal_size_limit=N
83590  **
83591  ** Get or set the size limit on rollback journal files.
83592  */
83593  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
83594    Pager *pPager = sqlite3BtreePager(pDb->pBt);
83595    i64 iLimit = -2;
83596    if( zRight ){
83597      sqlite3Atoi64(zRight, &iLimit);
83598      if( iLimit<-1 ) iLimit = -1;
83599    }
83600    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
83601    returnSingleInt(pParse, "journal_size_limit", iLimit);
83602  }else
83603
83604#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
83605
83606  /*
83607  **  PRAGMA [database.]auto_vacuum
83608  **  PRAGMA [database.]auto_vacuum=N
83609  **
83610  ** Get or set the value of the database 'auto-vacuum' parameter.
83611  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
83612  */
83613#ifndef SQLITE_OMIT_AUTOVACUUM
83614  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
83615    Btree *pBt = pDb->pBt;
83616    assert( pBt!=0 );
83617    if( sqlite3ReadSchema(pParse) ){
83618      goto pragma_out;
83619    }
83620    if( !zRight ){
83621      int auto_vacuum;
83622      if( ALWAYS(pBt) ){
83623         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
83624      }else{
83625         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
83626      }
83627      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
83628    }else{
83629      int eAuto = getAutoVacuum(zRight);
83630      assert( eAuto>=0 && eAuto<=2 );
83631      db->nextAutovac = (u8)eAuto;
83632      if( ALWAYS(eAuto>=0) ){
83633        /* Call SetAutoVacuum() to set initialize the internal auto and
83634        ** incr-vacuum flags. This is required in case this connection
83635        ** creates the database file. It is important that it is created
83636        ** as an auto-vacuum capable db.
83637        */
83638        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
83639        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
83640          /* When setting the auto_vacuum mode to either "full" or
83641          ** "incremental", write the value of meta[6] in the database
83642          ** file. Before writing to meta[6], check that meta[3] indicates
83643          ** that this really is an auto-vacuum capable database.
83644          */
83645          static const VdbeOpList setMeta6[] = {
83646            { OP_Transaction,    0,         1,                 0},    /* 0 */
83647            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
83648            { OP_If,             1,         0,                 0},    /* 2 */
83649            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
83650            { OP_Integer,        0,         1,                 0},    /* 4 */
83651            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
83652          };
83653          int iAddr;
83654          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
83655          sqlite3VdbeChangeP1(v, iAddr, iDb);
83656          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
83657          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
83658          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
83659          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
83660          sqlite3VdbeUsesBtree(v, iDb);
83661        }
83662      }
83663    }
83664  }else
83665#endif
83666
83667  /*
83668  **  PRAGMA [database.]incremental_vacuum(N)
83669  **
83670  ** Do N steps of incremental vacuuming on a database.
83671  */
83672#ifndef SQLITE_OMIT_AUTOVACUUM
83673  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
83674    int iLimit, addr;
83675    if( sqlite3ReadSchema(pParse) ){
83676      goto pragma_out;
83677    }
83678    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
83679      iLimit = 0x7fffffff;
83680    }
83681    sqlite3BeginWriteOperation(pParse, 0, iDb);
83682    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
83683    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
83684    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
83685    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
83686    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
83687    sqlite3VdbeJumpHere(v, addr);
83688  }else
83689#endif
83690
83691#ifndef SQLITE_OMIT_PAGER_PRAGMAS
83692  /*
83693  **  PRAGMA [database.]cache_size
83694  **  PRAGMA [database.]cache_size=N
83695  **
83696  ** The first form reports the current local setting for the
83697  ** page cache size.  The local setting can be different from
83698  ** the persistent cache size value that is stored in the database
83699  ** file itself.  The value returned is the maximum number of
83700  ** pages in the page cache.  The second form sets the local
83701  ** page cache size value.  It does not change the persistent
83702  ** cache size stored on the disk so the cache size will revert
83703  ** to its default value when the database is closed and reopened.
83704  ** N should be a positive integer.
83705  */
83706  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
83707    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83708    if( !zRight ){
83709      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
83710    }else{
83711      int size = atoi(zRight);
83712      if( size<0 ) size = -size;
83713      pDb->pSchema->cache_size = size;
83714      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
83715    }
83716  }else
83717
83718  /*
83719  **   PRAGMA temp_store
83720  **   PRAGMA temp_store = "default"|"memory"|"file"
83721  **
83722  ** Return or set the local value of the temp_store flag.  Changing
83723  ** the local value does not make changes to the disk file and the default
83724  ** value will be restored the next time the database is opened.
83725  **
83726  ** Note that it is possible for the library compile-time options to
83727  ** override this setting
83728  */
83729  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
83730    if( !zRight ){
83731      returnSingleInt(pParse, "temp_store", db->temp_store);
83732    }else{
83733      changeTempStorage(pParse, zRight);
83734    }
83735  }else
83736
83737  /*
83738  **   PRAGMA temp_store_directory
83739  **   PRAGMA temp_store_directory = ""|"directory_name"
83740  **
83741  ** Return or set the local value of the temp_store_directory flag.  Changing
83742  ** the value sets a specific directory to be used for temporary files.
83743  ** Setting to a null string reverts to the default temporary directory search.
83744  ** If temporary directory is changed, then invalidateTempStorage.
83745  **
83746  */
83747  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
83748    if( !zRight ){
83749      if( sqlite3_temp_directory ){
83750        sqlite3VdbeSetNumCols(v, 1);
83751        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
83752            "temp_store_directory", SQLITE_STATIC);
83753        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
83754        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83755      }
83756    }else{
83757#ifndef SQLITE_OMIT_WSD
83758      if( zRight[0] ){
83759        int rc;
83760        int res;
83761        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
83762        if( rc!=SQLITE_OK || res==0 ){
83763          sqlite3ErrorMsg(pParse, "not a writable directory");
83764          goto pragma_out;
83765        }
83766      }
83767      if( SQLITE_TEMP_STORE==0
83768       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
83769       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
83770      ){
83771        invalidateTempStorage(pParse);
83772      }
83773      sqlite3_free(sqlite3_temp_directory);
83774      if( zRight[0] ){
83775        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
83776      }else{
83777        sqlite3_temp_directory = 0;
83778      }
83779#endif /* SQLITE_OMIT_WSD */
83780    }
83781  }else
83782
83783#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
83784#  if defined(__APPLE__)
83785#    define SQLITE_ENABLE_LOCKING_STYLE 1
83786#  else
83787#    define SQLITE_ENABLE_LOCKING_STYLE 0
83788#  endif
83789#endif
83790#if SQLITE_ENABLE_LOCKING_STYLE
83791  /*
83792   **   PRAGMA [database.]lock_proxy_file
83793   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
83794   **
83795   ** Return or set the value of the lock_proxy_file flag.  Changing
83796   ** the value sets a specific file to be used for database access locks.
83797   **
83798   */
83799  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
83800    if( !zRight ){
83801      Pager *pPager = sqlite3BtreePager(pDb->pBt);
83802      char *proxy_file_path = NULL;
83803      sqlite3_file *pFile = sqlite3PagerFile(pPager);
83804      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
83805                           &proxy_file_path);
83806
83807      if( proxy_file_path ){
83808        sqlite3VdbeSetNumCols(v, 1);
83809        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
83810                              "lock_proxy_file", SQLITE_STATIC);
83811        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
83812        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83813      }
83814    }else{
83815      Pager *pPager = sqlite3BtreePager(pDb->pBt);
83816      sqlite3_file *pFile = sqlite3PagerFile(pPager);
83817      int res;
83818      if( zRight[0] ){
83819        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
83820                                     zRight);
83821      } else {
83822        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
83823                                     NULL);
83824      }
83825      if( res!=SQLITE_OK ){
83826        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
83827        goto pragma_out;
83828      }
83829    }
83830  }else
83831#endif /* SQLITE_ENABLE_LOCKING_STYLE */
83832
83833  /*
83834  **   PRAGMA [database.]synchronous
83835  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
83836  **
83837  ** Return or set the local value of the synchronous flag.  Changing
83838  ** the local value does not make changes to the disk file and the
83839  ** default value will be restored the next time the database is
83840  ** opened.
83841  */
83842  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
83843    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83844    if( !zRight ){
83845      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
83846    }else{
83847      if( !db->autoCommit ){
83848        sqlite3ErrorMsg(pParse,
83849            "Safety level may not be changed inside a transaction");
83850      }else{
83851        pDb->safety_level = getSafetyLevel(zRight)+1;
83852      }
83853    }
83854  }else
83855#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
83856
83857#ifndef SQLITE_OMIT_FLAG_PRAGMAS
83858  if( flagPragma(pParse, zLeft, zRight) ){
83859    /* The flagPragma() subroutine also generates any necessary code
83860    ** there is nothing more to do here */
83861  }else
83862#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
83863
83864#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
83865  /*
83866  **   PRAGMA table_info(<table>)
83867  **
83868  ** Return a single row for each column of the named table. The columns of
83869  ** the returned data set are:
83870  **
83871  ** cid:        Column id (numbered from left to right, starting at 0)
83872  ** name:       Column name
83873  ** type:       Column declaration type.
83874  ** notnull:    True if 'NOT NULL' is part of column declaration
83875  ** dflt_value: The default value for the column, if any.
83876  */
83877  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
83878    Table *pTab;
83879    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83880    pTab = sqlite3FindTable(db, zRight, zDb);
83881    if( pTab ){
83882      int i;
83883      int nHidden = 0;
83884      Column *pCol;
83885      sqlite3VdbeSetNumCols(v, 6);
83886      pParse->nMem = 6;
83887      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
83888      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
83889      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
83890      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
83891      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
83892      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
83893      sqlite3ViewGetColumnNames(pParse, pTab);
83894      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
83895        if( IsHiddenColumn(pCol) ){
83896          nHidden++;
83897          continue;
83898        }
83899        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
83900        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
83901        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
83902           pCol->zType ? pCol->zType : "", 0);
83903        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
83904        if( pCol->zDflt ){
83905          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
83906        }else{
83907          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
83908        }
83909        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
83910        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
83911      }
83912    }
83913  }else
83914
83915  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
83916    Index *pIdx;
83917    Table *pTab;
83918    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83919    pIdx = sqlite3FindIndex(db, zRight, zDb);
83920    if( pIdx ){
83921      int i;
83922      pTab = pIdx->pTable;
83923      sqlite3VdbeSetNumCols(v, 3);
83924      pParse->nMem = 3;
83925      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
83926      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
83927      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
83928      for(i=0; i<pIdx->nColumn; i++){
83929        int cnum = pIdx->aiColumn[i];
83930        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
83931        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
83932        assert( pTab->nCol>cnum );
83933        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
83934        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
83935      }
83936    }
83937  }else
83938
83939  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
83940    Index *pIdx;
83941    Table *pTab;
83942    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83943    pTab = sqlite3FindTable(db, zRight, zDb);
83944    if( pTab ){
83945      v = sqlite3GetVdbe(pParse);
83946      pIdx = pTab->pIndex;
83947      if( pIdx ){
83948        int i = 0;
83949        sqlite3VdbeSetNumCols(v, 3);
83950        pParse->nMem = 3;
83951        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
83952        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
83953        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
83954        while(pIdx){
83955          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
83956          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
83957          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
83958          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
83959          ++i;
83960          pIdx = pIdx->pNext;
83961        }
83962      }
83963    }
83964  }else
83965
83966  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
83967    int i;
83968    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83969    sqlite3VdbeSetNumCols(v, 3);
83970    pParse->nMem = 3;
83971    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
83972    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
83973    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
83974    for(i=0; i<db->nDb; i++){
83975      if( db->aDb[i].pBt==0 ) continue;
83976      assert( db->aDb[i].zName!=0 );
83977      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
83978      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
83979      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
83980           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
83981      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
83982    }
83983  }else
83984
83985  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
83986    int i = 0;
83987    HashElem *p;
83988    sqlite3VdbeSetNumCols(v, 2);
83989    pParse->nMem = 2;
83990    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
83991    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
83992    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
83993      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
83994      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
83995      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
83996      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
83997    }
83998  }else
83999#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
84000
84001#ifndef SQLITE_OMIT_FOREIGN_KEY
84002  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
84003    FKey *pFK;
84004    Table *pTab;
84005    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84006    pTab = sqlite3FindTable(db, zRight, zDb);
84007    if( pTab ){
84008      v = sqlite3GetVdbe(pParse);
84009      pFK = pTab->pFKey;
84010      if( pFK ){
84011        int i = 0;
84012        sqlite3VdbeSetNumCols(v, 8);
84013        pParse->nMem = 8;
84014        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
84015        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
84016        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
84017        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
84018        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
84019        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
84020        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
84021        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
84022        while(pFK){
84023          int j;
84024          for(j=0; j<pFK->nCol; j++){
84025            char *zCol = pFK->aCol[j].zCol;
84026            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
84027            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
84028            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84029            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
84030            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
84031            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
84032                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
84033            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
84034            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
84035            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
84036            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
84037            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
84038          }
84039          ++i;
84040          pFK = pFK->pNextFrom;
84041        }
84042      }
84043    }
84044  }else
84045#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84046
84047#ifndef NDEBUG
84048  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
84049    if( zRight ){
84050      if( getBoolean(zRight) ){
84051        sqlite3ParserTrace(stderr, "parser: ");
84052      }else{
84053        sqlite3ParserTrace(0, 0);
84054      }
84055    }
84056  }else
84057#endif
84058
84059  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
84060  ** used will be case sensitive or not depending on the RHS.
84061  */
84062  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
84063    if( zRight ){
84064      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
84065    }
84066  }else
84067
84068#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
84069# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
84070#endif
84071
84072#ifndef SQLITE_OMIT_INTEGRITY_CHECK
84073  /* Pragma "quick_check" is an experimental reduced version of
84074  ** integrity_check designed to detect most database corruption
84075  ** without most of the overhead of a full integrity-check.
84076  */
84077  if( sqlite3StrICmp(zLeft, "integrity_check")==0
84078   || sqlite3StrICmp(zLeft, "quick_check")==0
84079  ){
84080    int i, j, addr, mxErr;
84081
84082    /* Code that appears at the end of the integrity check.  If no error
84083    ** messages have been generated, output OK.  Otherwise output the
84084    ** error message
84085    */
84086    static const VdbeOpList endCode[] = {
84087      { OP_AddImm,      1, 0,        0},    /* 0 */
84088      { OP_IfNeg,       1, 0,        0},    /* 1 */
84089      { OP_String8,     0, 3,        0},    /* 2 */
84090      { OP_ResultRow,   3, 1,        0},
84091    };
84092
84093    int isQuick = (zLeft[0]=='q');
84094
84095    /* Initialize the VDBE program */
84096    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84097    pParse->nMem = 6;
84098    sqlite3VdbeSetNumCols(v, 1);
84099    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
84100
84101    /* Set the maximum error count */
84102    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84103    if( zRight ){
84104      mxErr = atoi(zRight);
84105      if( mxErr<=0 ){
84106        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84107      }
84108    }
84109    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
84110
84111    /* Do an integrity check on each database file */
84112    for(i=0; i<db->nDb; i++){
84113      HashElem *x;
84114      Hash *pTbls;
84115      int cnt = 0;
84116
84117      if( OMIT_TEMPDB && i==1 ) continue;
84118
84119      sqlite3CodeVerifySchema(pParse, i);
84120      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
84121      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84122      sqlite3VdbeJumpHere(v, addr);
84123
84124      /* Do an integrity check of the B-Tree
84125      **
84126      ** Begin by filling registers 2, 3, ... with the root pages numbers
84127      ** for all tables and indices in the database.
84128      */
84129      pTbls = &db->aDb[i].pSchema->tblHash;
84130      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
84131        Table *pTab = sqliteHashData(x);
84132        Index *pIdx;
84133        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
84134        cnt++;
84135        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84136          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
84137          cnt++;
84138        }
84139      }
84140
84141      /* Make sure sufficient number of registers have been allocated */
84142      if( pParse->nMem < cnt+4 ){
84143        pParse->nMem = cnt+4;
84144      }
84145
84146      /* Do the b-tree integrity checks */
84147      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
84148      sqlite3VdbeChangeP5(v, (u8)i);
84149      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
84150      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84151         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
84152         P4_DYNAMIC);
84153      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
84154      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
84155      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
84156      sqlite3VdbeJumpHere(v, addr);
84157
84158      /* Make sure all the indices are constructed correctly.
84159      */
84160      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
84161        Table *pTab = sqliteHashData(x);
84162        Index *pIdx;
84163        int loopTop;
84164
84165        if( pTab->pIndex==0 ) continue;
84166        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
84167        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84168        sqlite3VdbeJumpHere(v, addr);
84169        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
84170        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
84171        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
84172        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
84173        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84174          int jmp2;
84175          int r1;
84176          static const VdbeOpList idxErr[] = {
84177            { OP_AddImm,      1, -1,  0},
84178            { OP_String8,     0,  3,  0},    /* 1 */
84179            { OP_Rowid,       1,  4,  0},
84180            { OP_String8,     0,  5,  0},    /* 3 */
84181            { OP_String8,     0,  6,  0},    /* 4 */
84182            { OP_Concat,      4,  3,  3},
84183            { OP_Concat,      5,  3,  3},
84184            { OP_Concat,      6,  3,  3},
84185            { OP_ResultRow,   3,  1,  0},
84186            { OP_IfPos,       1,  0,  0},    /* 9 */
84187            { OP_Halt,        0,  0,  0},
84188          };
84189          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
84190          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
84191          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
84192          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
84193          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
84194          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
84195          sqlite3VdbeJumpHere(v, addr+9);
84196          sqlite3VdbeJumpHere(v, jmp2);
84197        }
84198        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
84199        sqlite3VdbeJumpHere(v, loopTop);
84200        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84201          static const VdbeOpList cntIdx[] = {
84202             { OP_Integer,      0,  3,  0},
84203             { OP_Rewind,       0,  0,  0},  /* 1 */
84204             { OP_AddImm,       3,  1,  0},
84205             { OP_Next,         0,  0,  0},  /* 3 */
84206             { OP_Eq,           2,  0,  3},  /* 4 */
84207             { OP_AddImm,       1, -1,  0},
84208             { OP_String8,      0,  2,  0},  /* 6 */
84209             { OP_String8,      0,  3,  0},  /* 7 */
84210             { OP_Concat,       3,  2,  2},
84211             { OP_ResultRow,    2,  1,  0},
84212          };
84213          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
84214          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84215          sqlite3VdbeJumpHere(v, addr);
84216          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
84217          sqlite3VdbeChangeP1(v, addr+1, j+2);
84218          sqlite3VdbeChangeP2(v, addr+1, addr+4);
84219          sqlite3VdbeChangeP1(v, addr+3, j+2);
84220          sqlite3VdbeChangeP2(v, addr+3, addr+2);
84221          sqlite3VdbeJumpHere(v, addr+4);
84222          sqlite3VdbeChangeP4(v, addr+6,
84223                     "wrong # of entries in index ", P4_STATIC);
84224          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
84225        }
84226      }
84227    }
84228    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
84229    sqlite3VdbeChangeP2(v, addr, -mxErr);
84230    sqlite3VdbeJumpHere(v, addr+1);
84231    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
84232  }else
84233#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
84234
84235#ifndef SQLITE_OMIT_UTF16
84236  /*
84237  **   PRAGMA encoding
84238  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
84239  **
84240  ** In its first form, this pragma returns the encoding of the main
84241  ** database. If the database is not initialized, it is initialized now.
84242  **
84243  ** The second form of this pragma is a no-op if the main database file
84244  ** has not already been initialized. In this case it sets the default
84245  ** encoding that will be used for the main database file if a new file
84246  ** is created. If an existing main database file is opened, then the
84247  ** default text encoding for the existing database is used.
84248  **
84249  ** In all cases new databases created using the ATTACH command are
84250  ** created to use the same default text encoding as the main database. If
84251  ** the main database has not been initialized and/or created when ATTACH
84252  ** is executed, this is done before the ATTACH operation.
84253  **
84254  ** In the second form this pragma sets the text encoding to be used in
84255  ** new database files created using this database handle. It is only
84256  ** useful if invoked immediately after the main database i
84257  */
84258  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
84259    static const struct EncName {
84260      char *zName;
84261      u8 enc;
84262    } encnames[] = {
84263      { "UTF8",     SQLITE_UTF8        },
84264      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
84265      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
84266      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
84267      { "UTF16le",  SQLITE_UTF16LE     },
84268      { "UTF16be",  SQLITE_UTF16BE     },
84269      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
84270      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
84271      { 0, 0 }
84272    };
84273    const struct EncName *pEnc;
84274    if( !zRight ){    /* "PRAGMA encoding" */
84275      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84276      sqlite3VdbeSetNumCols(v, 1);
84277      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
84278      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
84279      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
84280      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
84281      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
84282      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
84283      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84284    }else{                        /* "PRAGMA encoding = XXX" */
84285      /* Only change the value of sqlite.enc if the database handle is not
84286      ** initialized. If the main database exists, the new sqlite.enc value
84287      ** will be overwritten when the schema is next loaded. If it does not
84288      ** already exists, it will be created to use the new encoding value.
84289      */
84290      if(
84291        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
84292        DbHasProperty(db, 0, DB_Empty)
84293      ){
84294        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
84295          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
84296            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
84297            break;
84298          }
84299        }
84300        if( !pEnc->zName ){
84301          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
84302        }
84303      }
84304    }
84305  }else
84306#endif /* SQLITE_OMIT_UTF16 */
84307
84308#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
84309  /*
84310  **   PRAGMA [database.]schema_version
84311  **   PRAGMA [database.]schema_version = <integer>
84312  **
84313  **   PRAGMA [database.]user_version
84314  **   PRAGMA [database.]user_version = <integer>
84315  **
84316  ** The pragma's schema_version and user_version are used to set or get
84317  ** the value of the schema-version and user-version, respectively. Both
84318  ** the schema-version and the user-version are 32-bit signed integers
84319  ** stored in the database header.
84320  **
84321  ** The schema-cookie is usually only manipulated internally by SQLite. It
84322  ** is incremented by SQLite whenever the database schema is modified (by
84323  ** creating or dropping a table or index). The schema version is used by
84324  ** SQLite each time a query is executed to ensure that the internal cache
84325  ** of the schema used when compiling the SQL query matches the schema of
84326  ** the database against which the compiled query is actually executed.
84327  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
84328  ** the schema-version is potentially dangerous and may lead to program
84329  ** crashes or database corruption. Use with caution!
84330  **
84331  ** The user-version is not used internally by SQLite. It may be used by
84332  ** applications for any purpose.
84333  */
84334  if( sqlite3StrICmp(zLeft, "schema_version")==0
84335   || sqlite3StrICmp(zLeft, "user_version")==0
84336   || sqlite3StrICmp(zLeft, "freelist_count")==0
84337  ){
84338    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
84339    sqlite3VdbeUsesBtree(v, iDb);
84340    switch( zLeft[0] ){
84341      case 'f': case 'F':
84342        iCookie = BTREE_FREE_PAGE_COUNT;
84343        break;
84344      case 's': case 'S':
84345        iCookie = BTREE_SCHEMA_VERSION;
84346        break;
84347      default:
84348        iCookie = BTREE_USER_VERSION;
84349        break;
84350    }
84351
84352    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
84353      /* Write the specified cookie value */
84354      static const VdbeOpList setCookie[] = {
84355        { OP_Transaction,    0,  1,  0},    /* 0 */
84356        { OP_Integer,        0,  1,  0},    /* 1 */
84357        { OP_SetCookie,      0,  0,  1},    /* 2 */
84358      };
84359      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
84360      sqlite3VdbeChangeP1(v, addr, iDb);
84361      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
84362      sqlite3VdbeChangeP1(v, addr+2, iDb);
84363      sqlite3VdbeChangeP2(v, addr+2, iCookie);
84364    }else{
84365      /* Read the specified cookie value */
84366      static const VdbeOpList readCookie[] = {
84367        { OP_Transaction,     0,  0,  0},    /* 0 */
84368        { OP_ReadCookie,      0,  1,  0},    /* 1 */
84369        { OP_ResultRow,       1,  1,  0}
84370      };
84371      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
84372      sqlite3VdbeChangeP1(v, addr, iDb);
84373      sqlite3VdbeChangeP1(v, addr+1, iDb);
84374      sqlite3VdbeChangeP3(v, addr+1, iCookie);
84375      sqlite3VdbeSetNumCols(v, 1);
84376      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
84377    }
84378  }else
84379#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
84380
84381#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
84382  /*
84383  **   PRAGMA compile_options
84384  **
84385  ** Return the names of all compile-time options used in this build,
84386  ** one option per row.
84387  */
84388  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
84389    int i = 0;
84390    const char *zOpt;
84391    sqlite3VdbeSetNumCols(v, 1);
84392    pParse->nMem = 1;
84393    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
84394    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
84395      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
84396      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84397    }
84398  }else
84399#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
84400
84401#ifndef SQLITE_OMIT_WAL
84402  /*
84403  **   PRAGMA [database.]wal_checkpoint
84404  **
84405  ** Checkpoint the database.
84406  */
84407  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
84408    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84409    sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
84410  }else
84411
84412  /*
84413  **   PRAGMA wal_autocheckpoint
84414  **   PRAGMA wal_autocheckpoint = N
84415  **
84416  ** Configure a database connection to automatically checkpoint a database
84417  ** after accumulating N frames in the log. Or query for the current value
84418  ** of N.
84419  */
84420  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
84421    if( zRight ){
84422      int nAuto = atoi(zRight);
84423      sqlite3_wal_autocheckpoint(db, nAuto);
84424    }
84425    returnSingleInt(pParse, "wal_autocheckpoint",
84426       db->xWalCallback==sqlite3WalDefaultHook ?
84427           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
84428  }else
84429#endif
84430
84431#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
84432  /*
84433  ** Report the current state of file logs for all databases
84434  */
84435  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
84436    static const char *const azLockName[] = {
84437      "unlocked", "shared", "reserved", "pending", "exclusive"
84438    };
84439    int i;
84440    sqlite3VdbeSetNumCols(v, 2);
84441    pParse->nMem = 2;
84442    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
84443    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
84444    for(i=0; i<db->nDb; i++){
84445      Btree *pBt;
84446      Pager *pPager;
84447      const char *zState = "unknown";
84448      int j;
84449      if( db->aDb[i].zName==0 ) continue;
84450      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
84451      pBt = db->aDb[i].pBt;
84452      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
84453        zState = "closed";
84454      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
84455                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
84456         zState = azLockName[j];
84457      }
84458      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
84459      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
84460    }
84461
84462  }else
84463#endif
84464
84465#ifdef SQLITE_HAS_CODEC
84466  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
84467    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
84468  }else
84469  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
84470    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
84471  }else
84472  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
84473                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
84474    int i, h1, h2;
84475    char zKey[40];
84476    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
84477      h1 += 9*(1&(h1>>6));
84478      h2 += 9*(1&(h2>>6));
84479      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
84480    }
84481    if( (zLeft[3] & 0xf)==0xb ){
84482      sqlite3_key(db, zKey, i/2);
84483    }else{
84484      sqlite3_rekey(db, zKey, i/2);
84485    }
84486  }else
84487#endif
84488#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
84489  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
84490#ifdef SQLITE_HAS_CODEC
84491    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
84492      sqlite3_activate_see(&zRight[4]);
84493    }
84494#endif
84495#ifdef SQLITE_ENABLE_CEROD
84496    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
84497      sqlite3_activate_cerod(&zRight[6]);
84498    }
84499#endif
84500  }else
84501#endif
84502
84503
84504  {/* Empty ELSE clause */}
84505
84506  /*
84507  ** Reset the safety level, in case the fullfsync flag or synchronous
84508  ** setting changed.
84509  */
84510#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84511  if( db->autoCommit ){
84512    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
84513               (db->flags&SQLITE_FullFSync)!=0);
84514  }
84515#endif
84516pragma_out:
84517  sqlite3DbFree(db, zLeft);
84518  sqlite3DbFree(db, zRight);
84519}
84520
84521#endif /* SQLITE_OMIT_PRAGMA */
84522
84523/************** End of pragma.c **********************************************/
84524/************** Begin file prepare.c *****************************************/
84525/*
84526** 2005 May 25
84527**
84528** The author disclaims copyright to this source code.  In place of
84529** a legal notice, here is a blessing:
84530**
84531**    May you do good and not evil.
84532**    May you find forgiveness for yourself and forgive others.
84533**    May you share freely, never taking more than you give.
84534**
84535*************************************************************************
84536** This file contains the implementation of the sqlite3_prepare()
84537** interface, and routines that contribute to loading the database schema
84538** from disk.
84539*/
84540
84541/*
84542** Fill the InitData structure with an error message that indicates
84543** that the database is corrupt.
84544*/
84545static void corruptSchema(
84546  InitData *pData,     /* Initialization context */
84547  const char *zObj,    /* Object being parsed at the point of error */
84548  const char *zExtra   /* Error information */
84549){
84550  sqlite3 *db = pData->db;
84551  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
84552    if( zObj==0 ) zObj = "?";
84553    sqlite3SetString(pData->pzErrMsg, db,
84554      "malformed database schema (%s)", zObj);
84555    if( zExtra ){
84556      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
84557                                 "%s - %s", *pData->pzErrMsg, zExtra);
84558    }
84559  }
84560  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
84561}
84562
84563/*
84564** This is the callback routine for the code that initializes the
84565** database.  See sqlite3Init() below for additional information.
84566** This routine is also called from the OP_ParseSchema opcode of the VDBE.
84567**
84568** Each callback contains the following information:
84569**
84570**     argv[0] = name of thing being created
84571**     argv[1] = root page number for table or index. 0 for trigger or view.
84572**     argv[2] = SQL text for the CREATE statement.
84573**
84574*/
84575SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
84576  InitData *pData = (InitData*)pInit;
84577  sqlite3 *db = pData->db;
84578  int iDb = pData->iDb;
84579
84580  assert( argc==3 );
84581  UNUSED_PARAMETER2(NotUsed, argc);
84582  assert( sqlite3_mutex_held(db->mutex) );
84583  DbClearProperty(db, iDb, DB_Empty);
84584  if( db->mallocFailed ){
84585    corruptSchema(pData, argv[0], 0);
84586    return 1;
84587  }
84588
84589  assert( iDb>=0 && iDb<db->nDb );
84590  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
84591  if( argv[1]==0 ){
84592    corruptSchema(pData, argv[0], 0);
84593  }else if( argv[2] && argv[2][0] ){
84594    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
84595    ** But because db->init.busy is set to 1, no VDBE code is generated
84596    ** or executed.  All the parser does is build the internal data
84597    ** structures that describe the table, index, or view.
84598    */
84599    int rc;
84600    sqlite3_stmt *pStmt;
84601
84602    assert( db->init.busy );
84603    db->init.iDb = iDb;
84604    db->init.newTnum = atoi(argv[1]);
84605    db->init.orphanTrigger = 0;
84606    rc = sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
84607    db->init.iDb = 0;
84608    if( SQLITE_OK!=rc ){
84609      if( db->init.orphanTrigger ){
84610        assert( iDb==1 );
84611      }else{
84612        pData->rc = rc;
84613        if( rc==SQLITE_NOMEM ){
84614          db->mallocFailed = 1;
84615        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
84616          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
84617        }
84618      }
84619    }
84620    sqlite3_finalize(pStmt);
84621  }else if( argv[0]==0 ){
84622    corruptSchema(pData, 0, 0);
84623  }else{
84624    /* If the SQL column is blank it means this is an index that
84625    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
84626    ** constraint for a CREATE TABLE.  The index should have already
84627    ** been created when we processed the CREATE TABLE.  All we have
84628    ** to do here is record the root page number for that index.
84629    */
84630    Index *pIndex;
84631    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
84632    if( pIndex==0 ){
84633      /* This can occur if there exists an index on a TEMP table which
84634      ** has the same name as another index on a permanent index.  Since
84635      ** the permanent table is hidden by the TEMP table, we can also
84636      ** safely ignore the index on the permanent table.
84637      */
84638      /* Do Nothing */;
84639    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
84640      corruptSchema(pData, argv[0], "invalid rootpage");
84641    }
84642  }
84643  return 0;
84644}
84645
84646/*
84647** Attempt to read the database schema and initialize internal
84648** data structures for a single database file.  The index of the
84649** database file is given by iDb.  iDb==0 is used for the main
84650** database.  iDb==1 should never be used.  iDb>=2 is used for
84651** auxiliary databases.  Return one of the SQLITE_ error codes to
84652** indicate success or failure.
84653*/
84654static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
84655  int rc;
84656  int i;
84657  int size;
84658  Table *pTab;
84659  Db *pDb;
84660  char const *azArg[4];
84661  int meta[5];
84662  InitData initData;
84663  char const *zMasterSchema;
84664  char const *zMasterName = SCHEMA_TABLE(iDb);
84665  int openedTransaction = 0;
84666
84667  /*
84668  ** The master database table has a structure like this
84669  */
84670  static const char master_schema[] =
84671     "CREATE TABLE sqlite_master(\n"
84672     "  type text,\n"
84673     "  name text,\n"
84674     "  tbl_name text,\n"
84675     "  rootpage integer,\n"
84676     "  sql text\n"
84677     ")"
84678  ;
84679#ifndef SQLITE_OMIT_TEMPDB
84680  static const char temp_master_schema[] =
84681     "CREATE TEMP TABLE sqlite_temp_master(\n"
84682     "  type text,\n"
84683     "  name text,\n"
84684     "  tbl_name text,\n"
84685     "  rootpage integer,\n"
84686     "  sql text\n"
84687     ")"
84688  ;
84689#else
84690  #define temp_master_schema 0
84691#endif
84692
84693  assert( iDb>=0 && iDb<db->nDb );
84694  assert( db->aDb[iDb].pSchema );
84695  assert( sqlite3_mutex_held(db->mutex) );
84696  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
84697
84698  /* zMasterSchema and zInitScript are set to point at the master schema
84699  ** and initialisation script appropriate for the database being
84700  ** initialised. zMasterName is the name of the master table.
84701  */
84702  if( !OMIT_TEMPDB && iDb==1 ){
84703    zMasterSchema = temp_master_schema;
84704  }else{
84705    zMasterSchema = master_schema;
84706  }
84707  zMasterName = SCHEMA_TABLE(iDb);
84708
84709  /* Construct the schema tables.  */
84710  azArg[0] = zMasterName;
84711  azArg[1] = "1";
84712  azArg[2] = zMasterSchema;
84713  azArg[3] = 0;
84714  initData.db = db;
84715  initData.iDb = iDb;
84716  initData.rc = SQLITE_OK;
84717  initData.pzErrMsg = pzErrMsg;
84718  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
84719  if( initData.rc ){
84720    rc = initData.rc;
84721    goto error_out;
84722  }
84723  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
84724  if( ALWAYS(pTab) ){
84725    pTab->tabFlags |= TF_Readonly;
84726  }
84727
84728  /* Create a cursor to hold the database open
84729  */
84730  pDb = &db->aDb[iDb];
84731  if( pDb->pBt==0 ){
84732    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
84733      DbSetProperty(db, 1, DB_SchemaLoaded);
84734    }
84735    return SQLITE_OK;
84736  }
84737
84738  /* If there is not already a read-only (or read-write) transaction opened
84739  ** on the b-tree database, open one now. If a transaction is opened, it
84740  ** will be closed before this function returns.  */
84741  sqlite3BtreeEnter(pDb->pBt);
84742  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
84743    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
84744    if( rc!=SQLITE_OK ){
84745      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
84746      goto initone_error_out;
84747    }
84748    openedTransaction = 1;
84749  }
84750
84751  /* Get the database meta information.
84752  **
84753  ** Meta values are as follows:
84754  **    meta[0]   Schema cookie.  Changes with each schema change.
84755  **    meta[1]   File format of schema layer.
84756  **    meta[2]   Size of the page cache.
84757  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
84758  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
84759  **    meta[5]   User version
84760  **    meta[6]   Incremental vacuum mode
84761  **    meta[7]   unused
84762  **    meta[8]   unused
84763  **    meta[9]   unused
84764  **
84765  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
84766  ** the possible values of meta[4].
84767  */
84768  for(i=0; i<ArraySize(meta); i++){
84769    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
84770  }
84771  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
84772
84773  /* If opening a non-empty database, check the text encoding. For the
84774  ** main database, set sqlite3.enc to the encoding of the main database.
84775  ** For an attached db, it is an error if the encoding is not the same
84776  ** as sqlite3.enc.
84777  */
84778  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
84779    if( iDb==0 ){
84780      u8 encoding;
84781      /* If opening the main database, set ENC(db). */
84782      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
84783      if( encoding==0 ) encoding = SQLITE_UTF8;
84784      ENC(db) = encoding;
84785      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
84786    }else{
84787      /* If opening an attached database, the encoding much match ENC(db) */
84788      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
84789        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
84790            " text encoding as main database");
84791        rc = SQLITE_ERROR;
84792        goto initone_error_out;
84793      }
84794    }
84795  }else{
84796    DbSetProperty(db, iDb, DB_Empty);
84797  }
84798  pDb->pSchema->enc = ENC(db);
84799
84800  if( pDb->pSchema->cache_size==0 ){
84801    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
84802    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
84803    if( size<0 ) size = -size;
84804    pDb->pSchema->cache_size = size;
84805    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84806  }
84807
84808  /*
84809  ** file_format==1    Version 3.0.0.
84810  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
84811  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
84812  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
84813  */
84814  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
84815  if( pDb->pSchema->file_format==0 ){
84816    pDb->pSchema->file_format = 1;
84817  }
84818  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
84819    sqlite3SetString(pzErrMsg, db, "unsupported file format");
84820    rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
84821    goto initone_error_out;
84822  }
84823
84824  /* Ticket #2804:  When we open a database in the newer file format,
84825  ** clear the legacy_file_format pragma flag so that a VACUUM will
84826  ** not downgrade the database and thus invalidate any descending
84827  ** indices that the user might have created.
84828  */
84829  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
84830    db->flags &= ~SQLITE_LegacyFileFmt;
84831  }
84832
84833  /* Read the schema information out of the schema tables
84834  */
84835  assert( db->init.busy );
84836  {
84837    char *zSql;
84838    zSql = sqlite3MPrintf(db,
84839        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
84840        db->aDb[iDb].zName, zMasterName);
84841#ifndef SQLITE_OMIT_AUTHORIZATION
84842    {
84843      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
84844      xAuth = db->xAuth;
84845      db->xAuth = 0;
84846#endif
84847      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
84848#ifndef SQLITE_OMIT_AUTHORIZATION
84849      db->xAuth = xAuth;
84850    }
84851#endif
84852    if( rc==SQLITE_OK ) rc = initData.rc;
84853    sqlite3DbFree(db, zSql);
84854#ifndef SQLITE_OMIT_ANALYZE
84855    if( rc==SQLITE_OK ){
84856      sqlite3AnalysisLoad(db, iDb);
84857    }
84858#endif
84859  }
84860  if( db->mallocFailed ){
84861    rc = SQLITE_NOMEM;
84862    sqlite3ResetInternalSchema(db, 0);
84863  }
84864  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
84865    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
84866    ** the schema loaded, even if errors occurred. In this situation the
84867    ** current sqlite3_prepare() operation will fail, but the following one
84868    ** will attempt to compile the supplied statement against whatever subset
84869    ** of the schema was loaded before the error occurred. The primary
84870    ** purpose of this is to allow access to the sqlite_master table
84871    ** even when its contents have been corrupted.
84872    */
84873    DbSetProperty(db, iDb, DB_SchemaLoaded);
84874    rc = SQLITE_OK;
84875  }
84876
84877  /* Jump here for an error that occurs after successfully allocating
84878  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
84879  ** before that point, jump to error_out.
84880  */
84881initone_error_out:
84882  if( openedTransaction ){
84883    sqlite3BtreeCommit(pDb->pBt);
84884  }
84885  sqlite3BtreeLeave(pDb->pBt);
84886
84887error_out:
84888  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
84889    db->mallocFailed = 1;
84890  }
84891  return rc;
84892}
84893
84894/*
84895** Initialize all database files - the main database file, the file
84896** used to store temporary tables, and any additional database files
84897** created using ATTACH statements.  Return a success code.  If an
84898** error occurs, write an error message into *pzErrMsg.
84899**
84900** After a database is initialized, the DB_SchemaLoaded bit is set
84901** bit is set in the flags field of the Db structure. If the database
84902** file was of zero-length, then the DB_Empty flag is also set.
84903*/
84904SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
84905  int i, rc;
84906  int commit_internal = !(db->flags&SQLITE_InternChanges);
84907
84908  assert( sqlite3_mutex_held(db->mutex) );
84909  rc = SQLITE_OK;
84910  db->init.busy = 1;
84911  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
84912    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
84913    rc = sqlite3InitOne(db, i, pzErrMsg);
84914    if( rc ){
84915      sqlite3ResetInternalSchema(db, i);
84916    }
84917  }
84918
84919  /* Once all the other databases have been initialised, load the schema
84920  ** for the TEMP database. This is loaded last, as the TEMP database
84921  ** schema may contain references to objects in other databases.
84922  */
84923#ifndef SQLITE_OMIT_TEMPDB
84924  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
84925                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
84926    rc = sqlite3InitOne(db, 1, pzErrMsg);
84927    if( rc ){
84928      sqlite3ResetInternalSchema(db, 1);
84929    }
84930  }
84931#endif
84932
84933  db->init.busy = 0;
84934  if( rc==SQLITE_OK && commit_internal ){
84935    sqlite3CommitInternalChanges(db);
84936  }
84937
84938  return rc;
84939}
84940
84941/*
84942** This routine is a no-op if the database schema is already initialised.
84943** Otherwise, the schema is loaded. An error code is returned.
84944*/
84945SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
84946  int rc = SQLITE_OK;
84947  sqlite3 *db = pParse->db;
84948  assert( sqlite3_mutex_held(db->mutex) );
84949  if( !db->init.busy ){
84950    rc = sqlite3Init(db, &pParse->zErrMsg);
84951  }
84952  if( rc!=SQLITE_OK ){
84953    pParse->rc = rc;
84954    pParse->nErr++;
84955  }
84956  return rc;
84957}
84958
84959
84960/*
84961** Check schema cookies in all databases.  If any cookie is out
84962** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
84963** make no changes to pParse->rc.
84964*/
84965static void schemaIsValid(Parse *pParse){
84966  sqlite3 *db = pParse->db;
84967  int iDb;
84968  int rc;
84969  int cookie;
84970
84971  assert( pParse->checkSchema );
84972  assert( sqlite3_mutex_held(db->mutex) );
84973  for(iDb=0; iDb<db->nDb; iDb++){
84974    int openedTransaction = 0;         /* True if a transaction is opened */
84975    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
84976    if( pBt==0 ) continue;
84977
84978    /* If there is not already a read-only (or read-write) transaction opened
84979    ** on the b-tree database, open one now. If a transaction is opened, it
84980    ** will be closed immediately after reading the meta-value. */
84981    if( !sqlite3BtreeIsInReadTrans(pBt) ){
84982      rc = sqlite3BtreeBeginTrans(pBt, 0);
84983      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
84984        db->mallocFailed = 1;
84985      }
84986      if( rc!=SQLITE_OK ) return;
84987      openedTransaction = 1;
84988    }
84989
84990    /* Read the schema cookie from the database. If it does not match the
84991    ** value stored as part of the in-memory schema representation,
84992    ** set Parse.rc to SQLITE_SCHEMA. */
84993    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
84994    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
84995      pParse->rc = SQLITE_SCHEMA;
84996    }
84997
84998    /* Close the transaction, if one was opened. */
84999    if( openedTransaction ){
85000      sqlite3BtreeCommit(pBt);
85001    }
85002  }
85003}
85004
85005/*
85006** Convert a schema pointer into the iDb index that indicates
85007** which database file in db->aDb[] the schema refers to.
85008**
85009** If the same database is attached more than once, the first
85010** attached database is returned.
85011*/
85012SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
85013  int i = -1000000;
85014
85015  /* If pSchema is NULL, then return -1000000. This happens when code in
85016  ** expr.c is trying to resolve a reference to a transient table (i.e. one
85017  ** created by a sub-select). In this case the return value of this
85018  ** function should never be used.
85019  **
85020  ** We return -1000000 instead of the more usual -1 simply because using
85021  ** -1000000 as the incorrect index into db->aDb[] is much
85022  ** more likely to cause a segfault than -1 (of course there are assert()
85023  ** statements too, but it never hurts to play the odds).
85024  */
85025  assert( sqlite3_mutex_held(db->mutex) );
85026  if( pSchema ){
85027    for(i=0; ALWAYS(i<db->nDb); i++){
85028      if( db->aDb[i].pSchema==pSchema ){
85029        break;
85030      }
85031    }
85032    assert( i>=0 && i<db->nDb );
85033  }
85034  return i;
85035}
85036
85037/*
85038** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
85039*/
85040static int sqlite3Prepare(
85041  sqlite3 *db,              /* Database handle. */
85042  const char *zSql,         /* UTF-8 encoded SQL statement. */
85043  int nBytes,               /* Length of zSql in bytes. */
85044  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85045  Vdbe *pReprepare,         /* VM being reprepared */
85046  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85047  const char **pzTail       /* OUT: End of parsed string */
85048){
85049  Parse *pParse;            /* Parsing context */
85050  char *zErrMsg = 0;        /* Error message */
85051  int rc = SQLITE_OK;       /* Result code */
85052  int i;                    /* Loop counter */
85053
85054  /* Allocate the parsing context */
85055  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
85056  if( pParse==0 ){
85057    rc = SQLITE_NOMEM;
85058    goto end_prepare;
85059  }
85060  pParse->pReprepare = pReprepare;
85061  assert( ppStmt && *ppStmt==0 );
85062  assert( !db->mallocFailed );
85063  assert( sqlite3_mutex_held(db->mutex) );
85064
85065  /* Check to verify that it is possible to get a read lock on all
85066  ** database schemas.  The inability to get a read lock indicates that
85067  ** some other database connection is holding a write-lock, which in
85068  ** turn means that the other connection has made uncommitted changes
85069  ** to the schema.
85070  **
85071  ** Were we to proceed and prepare the statement against the uncommitted
85072  ** schema changes and if those schema changes are subsequently rolled
85073  ** back and different changes are made in their place, then when this
85074  ** prepared statement goes to run the schema cookie would fail to detect
85075  ** the schema change.  Disaster would follow.
85076  **
85077  ** This thread is currently holding mutexes on all Btrees (because
85078  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
85079  ** is not possible for another thread to start a new schema change
85080  ** while this routine is running.  Hence, we do not need to hold
85081  ** locks on the schema, we just need to make sure nobody else is
85082  ** holding them.
85083  **
85084  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
85085  ** but it does *not* override schema lock detection, so this all still
85086  ** works even if READ_UNCOMMITTED is set.
85087  */
85088  for(i=0; i<db->nDb; i++) {
85089    Btree *pBt = db->aDb[i].pBt;
85090    if( pBt ){
85091      assert( sqlite3BtreeHoldsMutex(pBt) );
85092      rc = sqlite3BtreeSchemaLocked(pBt);
85093      if( rc ){
85094        const char *zDb = db->aDb[i].zName;
85095        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
85096        testcase( db->flags & SQLITE_ReadUncommitted );
85097        goto end_prepare;
85098      }
85099    }
85100  }
85101
85102  sqlite3VtabUnlockList(db);
85103
85104  pParse->db = db;
85105  pParse->nQueryLoop = (double)1;
85106  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
85107    char *zSqlCopy;
85108    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
85109    testcase( nBytes==mxLen );
85110    testcase( nBytes==mxLen+1 );
85111    if( nBytes>mxLen ){
85112      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
85113      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
85114      goto end_prepare;
85115    }
85116    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
85117    if( zSqlCopy ){
85118      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
85119      sqlite3DbFree(db, zSqlCopy);
85120      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
85121    }else{
85122      pParse->zTail = &zSql[nBytes];
85123    }
85124  }else{
85125    sqlite3RunParser(pParse, zSql, &zErrMsg);
85126  }
85127  assert( 1==(int)pParse->nQueryLoop );
85128
85129  if( db->mallocFailed ){
85130    pParse->rc = SQLITE_NOMEM;
85131  }
85132  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
85133  if( pParse->checkSchema ){
85134    schemaIsValid(pParse);
85135  }
85136  if( pParse->rc==SQLITE_SCHEMA ){
85137    sqlite3ResetInternalSchema(db, 0);
85138  }
85139  if( db->mallocFailed ){
85140    pParse->rc = SQLITE_NOMEM;
85141  }
85142  if( pzTail ){
85143    *pzTail = pParse->zTail;
85144  }
85145  rc = pParse->rc;
85146
85147#ifndef SQLITE_OMIT_EXPLAIN
85148  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
85149    static const char * const azColName[] = {
85150       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
85151       "order", "from", "detail"
85152    };
85153    int iFirst, mx;
85154    if( pParse->explain==2 ){
85155      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
85156      iFirst = 8;
85157      mx = 11;
85158    }else{
85159      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
85160      iFirst = 0;
85161      mx = 8;
85162    }
85163    for(i=iFirst; i<mx; i++){
85164      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
85165                            azColName[i], SQLITE_STATIC);
85166    }
85167  }
85168#endif
85169
85170  assert( db->init.busy==0 || saveSqlFlag==0 );
85171  if( db->init.busy==0 ){
85172    Vdbe *pVdbe = pParse->pVdbe;
85173    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
85174  }
85175  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
85176    sqlite3VdbeFinalize(pParse->pVdbe);
85177    assert(!(*ppStmt));
85178  }else{
85179    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
85180  }
85181
85182  if( zErrMsg ){
85183    sqlite3Error(db, rc, "%s", zErrMsg);
85184    sqlite3DbFree(db, zErrMsg);
85185  }else{
85186    sqlite3Error(db, rc, 0);
85187  }
85188
85189  /* Delete any TriggerPrg structures allocated while parsing this statement. */
85190  while( pParse->pTriggerPrg ){
85191    TriggerPrg *pT = pParse->pTriggerPrg;
85192    pParse->pTriggerPrg = pT->pNext;
85193    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
85194    sqlite3DbFree(db, pT);
85195  }
85196
85197end_prepare:
85198
85199  sqlite3StackFree(db, pParse);
85200  rc = sqlite3ApiExit(db, rc);
85201  assert( (rc&db->errMask)==rc );
85202  return rc;
85203}
85204static int sqlite3LockAndPrepare(
85205  sqlite3 *db,              /* Database handle. */
85206  const char *zSql,         /* UTF-8 encoded SQL statement. */
85207  int nBytes,               /* Length of zSql in bytes. */
85208  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85209  Vdbe *pOld,               /* VM being reprepared */
85210  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85211  const char **pzTail       /* OUT: End of parsed string */
85212){
85213  int rc;
85214  assert( ppStmt!=0 );
85215  *ppStmt = 0;
85216  if( !sqlite3SafetyCheckOk(db) ){
85217    return SQLITE_MISUSE_BKPT;
85218  }
85219  sqlite3_mutex_enter(db->mutex);
85220  sqlite3BtreeEnterAll(db);
85221  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85222  if( rc==SQLITE_SCHEMA ){
85223    sqlite3_finalize(*ppStmt);
85224    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85225  }
85226  sqlite3BtreeLeaveAll(db);
85227  sqlite3_mutex_leave(db->mutex);
85228  return rc;
85229}
85230
85231/*
85232** Rerun the compilation of a statement after a schema change.
85233**
85234** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
85235** if the statement cannot be recompiled because another connection has
85236** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
85237** occurs, return SQLITE_SCHEMA.
85238*/
85239SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
85240  int rc;
85241  sqlite3_stmt *pNew;
85242  const char *zSql;
85243  sqlite3 *db;
85244
85245  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
85246  zSql = sqlite3_sql((sqlite3_stmt *)p);
85247  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
85248  db = sqlite3VdbeDb(p);
85249  assert( sqlite3_mutex_held(db->mutex) );
85250  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
85251  if( rc ){
85252    if( rc==SQLITE_NOMEM ){
85253      db->mallocFailed = 1;
85254    }
85255    assert( pNew==0 );
85256    return rc;
85257  }else{
85258    assert( pNew!=0 );
85259  }
85260  sqlite3VdbeSwap((Vdbe*)pNew, p);
85261  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
85262  sqlite3VdbeResetStepResult((Vdbe*)pNew);
85263  sqlite3VdbeFinalize((Vdbe*)pNew);
85264  return SQLITE_OK;
85265}
85266
85267
85268/*
85269** Two versions of the official API.  Legacy and new use.  In the legacy
85270** version, the original SQL text is not saved in the prepared statement
85271** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85272** sqlite3_step().  In the new version, the original SQL text is retained
85273** and the statement is automatically recompiled if an schema change
85274** occurs.
85275*/
85276SQLITE_API int sqlite3_prepare(
85277  sqlite3 *db,              /* Database handle. */
85278  const char *zSql,         /* UTF-8 encoded SQL statement. */
85279  int nBytes,               /* Length of zSql in bytes. */
85280  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85281  const char **pzTail       /* OUT: End of parsed string */
85282){
85283  int rc;
85284  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
85285  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85286  return rc;
85287}
85288SQLITE_API int sqlite3_prepare_v2(
85289  sqlite3 *db,              /* Database handle. */
85290  const char *zSql,         /* UTF-8 encoded SQL statement. */
85291  int nBytes,               /* Length of zSql in bytes. */
85292  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85293  const char **pzTail       /* OUT: End of parsed string */
85294){
85295  int rc;
85296  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
85297  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85298  return rc;
85299}
85300
85301
85302#ifndef SQLITE_OMIT_UTF16
85303/*
85304** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
85305*/
85306static int sqlite3Prepare16(
85307  sqlite3 *db,              /* Database handle. */
85308  const void *zSql,         /* UTF-8 encoded SQL statement. */
85309  int nBytes,               /* Length of zSql in bytes. */
85310  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
85311  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85312  const void **pzTail       /* OUT: End of parsed string */
85313){
85314  /* This function currently works by first transforming the UTF-16
85315  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
85316  ** tricky bit is figuring out the pointer to return in *pzTail.
85317  */
85318  char *zSql8;
85319  const char *zTail8 = 0;
85320  int rc = SQLITE_OK;
85321
85322  assert( ppStmt );
85323  *ppStmt = 0;
85324  if( !sqlite3SafetyCheckOk(db) ){
85325    return SQLITE_MISUSE_BKPT;
85326  }
85327  sqlite3_mutex_enter(db->mutex);
85328  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
85329  if( zSql8 ){
85330    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
85331  }
85332
85333  if( zTail8 && pzTail ){
85334    /* If sqlite3_prepare returns a tail pointer, we calculate the
85335    ** equivalent pointer into the UTF-16 string by counting the unicode
85336    ** characters between zSql8 and zTail8, and then returning a pointer
85337    ** the same number of characters into the UTF-16 string.
85338    */
85339    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
85340    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
85341  }
85342  sqlite3DbFree(db, zSql8);
85343  rc = sqlite3ApiExit(db, rc);
85344  sqlite3_mutex_leave(db->mutex);
85345  return rc;
85346}
85347
85348/*
85349** Two versions of the official API.  Legacy and new use.  In the legacy
85350** version, the original SQL text is not saved in the prepared statement
85351** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85352** sqlite3_step().  In the new version, the original SQL text is retained
85353** and the statement is automatically recompiled if an schema change
85354** occurs.
85355*/
85356SQLITE_API int sqlite3_prepare16(
85357  sqlite3 *db,              /* Database handle. */
85358  const void *zSql,         /* UTF-8 encoded SQL statement. */
85359  int nBytes,               /* Length of zSql in bytes. */
85360  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85361  const void **pzTail       /* OUT: End of parsed string */
85362){
85363  int rc;
85364  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
85365  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85366  return rc;
85367}
85368SQLITE_API int sqlite3_prepare16_v2(
85369  sqlite3 *db,              /* Database handle. */
85370  const void *zSql,         /* UTF-8 encoded SQL statement. */
85371  int nBytes,               /* Length of zSql in bytes. */
85372  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85373  const void **pzTail       /* OUT: End of parsed string */
85374){
85375  int rc;
85376  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
85377  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85378  return rc;
85379}
85380
85381#endif /* SQLITE_OMIT_UTF16 */
85382
85383/************** End of prepare.c *********************************************/
85384/************** Begin file select.c ******************************************/
85385/*
85386** 2001 September 15
85387**
85388** The author disclaims copyright to this source code.  In place of
85389** a legal notice, here is a blessing:
85390**
85391**    May you do good and not evil.
85392**    May you find forgiveness for yourself and forgive others.
85393**    May you share freely, never taking more than you give.
85394**
85395*************************************************************************
85396** This file contains C code routines that are called by the parser
85397** to handle SELECT statements in SQLite.
85398*/
85399
85400
85401/*
85402** Delete all the content of a Select structure but do not deallocate
85403** the select structure itself.
85404*/
85405static void clearSelect(sqlite3 *db, Select *p){
85406  sqlite3ExprListDelete(db, p->pEList);
85407  sqlite3SrcListDelete(db, p->pSrc);
85408  sqlite3ExprDelete(db, p->pWhere);
85409  sqlite3ExprListDelete(db, p->pGroupBy);
85410  sqlite3ExprDelete(db, p->pHaving);
85411  sqlite3ExprListDelete(db, p->pOrderBy);
85412  sqlite3SelectDelete(db, p->pPrior);
85413  sqlite3ExprDelete(db, p->pLimit);
85414  sqlite3ExprDelete(db, p->pOffset);
85415}
85416
85417/*
85418** Initialize a SelectDest structure.
85419*/
85420SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
85421  pDest->eDest = (u8)eDest;
85422  pDest->iParm = iParm;
85423  pDest->affinity = 0;
85424  pDest->iMem = 0;
85425  pDest->nMem = 0;
85426}
85427
85428
85429/*
85430** Allocate a new Select structure and return a pointer to that
85431** structure.
85432*/
85433SQLITE_PRIVATE Select *sqlite3SelectNew(
85434  Parse *pParse,        /* Parsing context */
85435  ExprList *pEList,     /* which columns to include in the result */
85436  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
85437  Expr *pWhere,         /* the WHERE clause */
85438  ExprList *pGroupBy,   /* the GROUP BY clause */
85439  Expr *pHaving,        /* the HAVING clause */
85440  ExprList *pOrderBy,   /* the ORDER BY clause */
85441  int isDistinct,       /* true if the DISTINCT keyword is present */
85442  Expr *pLimit,         /* LIMIT value.  NULL means not used */
85443  Expr *pOffset         /* OFFSET value.  NULL means no offset */
85444){
85445  Select *pNew;
85446  Select standin;
85447  sqlite3 *db = pParse->db;
85448  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
85449  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
85450  if( pNew==0 ){
85451    pNew = &standin;
85452    memset(pNew, 0, sizeof(*pNew));
85453  }
85454  if( pEList==0 ){
85455    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
85456  }
85457  pNew->pEList = pEList;
85458  pNew->pSrc = pSrc;
85459  pNew->pWhere = pWhere;
85460  pNew->pGroupBy = pGroupBy;
85461  pNew->pHaving = pHaving;
85462  pNew->pOrderBy = pOrderBy;
85463  pNew->selFlags = isDistinct ? SF_Distinct : 0;
85464  pNew->op = TK_SELECT;
85465  pNew->pLimit = pLimit;
85466  pNew->pOffset = pOffset;
85467  assert( pOffset==0 || pLimit!=0 );
85468  pNew->addrOpenEphm[0] = -1;
85469  pNew->addrOpenEphm[1] = -1;
85470  pNew->addrOpenEphm[2] = -1;
85471  if( db->mallocFailed ) {
85472    clearSelect(db, pNew);
85473    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
85474    pNew = 0;
85475  }
85476  return pNew;
85477}
85478
85479/*
85480** Delete the given Select structure and all of its substructures.
85481*/
85482SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
85483  if( p ){
85484    clearSelect(db, p);
85485    sqlite3DbFree(db, p);
85486  }
85487}
85488
85489/*
85490** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
85491** type of join.  Return an integer constant that expresses that type
85492** in terms of the following bit values:
85493**
85494**     JT_INNER
85495**     JT_CROSS
85496**     JT_OUTER
85497**     JT_NATURAL
85498**     JT_LEFT
85499**     JT_RIGHT
85500**
85501** A full outer join is the combination of JT_LEFT and JT_RIGHT.
85502**
85503** If an illegal or unsupported join type is seen, then still return
85504** a join type, but put an error in the pParse structure.
85505*/
85506SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
85507  int jointype = 0;
85508  Token *apAll[3];
85509  Token *p;
85510                             /*   0123456789 123456789 123456789 123 */
85511  static const char zKeyText[] = "naturaleftouterightfullinnercross";
85512  static const struct {
85513    u8 i;        /* Beginning of keyword text in zKeyText[] */
85514    u8 nChar;    /* Length of the keyword in characters */
85515    u8 code;     /* Join type mask */
85516  } aKeyword[] = {
85517    /* natural */ { 0,  7, JT_NATURAL                },
85518    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
85519    /* outer   */ { 10, 5, JT_OUTER                  },
85520    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
85521    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
85522    /* inner   */ { 23, 5, JT_INNER                  },
85523    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
85524  };
85525  int i, j;
85526  apAll[0] = pA;
85527  apAll[1] = pB;
85528  apAll[2] = pC;
85529  for(i=0; i<3 && apAll[i]; i++){
85530    p = apAll[i];
85531    for(j=0; j<ArraySize(aKeyword); j++){
85532      if( p->n==aKeyword[j].nChar
85533          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
85534        jointype |= aKeyword[j].code;
85535        break;
85536      }
85537    }
85538    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
85539    if( j>=ArraySize(aKeyword) ){
85540      jointype |= JT_ERROR;
85541      break;
85542    }
85543  }
85544  if(
85545     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
85546     (jointype & JT_ERROR)!=0
85547  ){
85548    const char *zSp = " ";
85549    assert( pB!=0 );
85550    if( pC==0 ){ zSp++; }
85551    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
85552       "%T %T%s%T", pA, pB, zSp, pC);
85553    jointype = JT_INNER;
85554  }else if( (jointype & JT_OUTER)!=0
85555         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
85556    sqlite3ErrorMsg(pParse,
85557      "RIGHT and FULL OUTER JOINs are not currently supported");
85558    jointype = JT_INNER;
85559  }
85560  return jointype;
85561}
85562
85563/*
85564** Return the index of a column in a table.  Return -1 if the column
85565** is not contained in the table.
85566*/
85567static int columnIndex(Table *pTab, const char *zCol){
85568  int i;
85569  for(i=0; i<pTab->nCol; i++){
85570    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
85571  }
85572  return -1;
85573}
85574
85575/*
85576** Search the first N tables in pSrc, from left to right, looking for a
85577** table that has a column named zCol.
85578**
85579** When found, set *piTab and *piCol to the table index and column index
85580** of the matching column and return TRUE.
85581**
85582** If not found, return FALSE.
85583*/
85584static int tableAndColumnIndex(
85585  SrcList *pSrc,       /* Array of tables to search */
85586  int N,               /* Number of tables in pSrc->a[] to search */
85587  const char *zCol,    /* Name of the column we are looking for */
85588  int *piTab,          /* Write index of pSrc->a[] here */
85589  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
85590){
85591  int i;               /* For looping over tables in pSrc */
85592  int iCol;            /* Index of column matching zCol */
85593
85594  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
85595  for(i=0; i<N; i++){
85596    iCol = columnIndex(pSrc->a[i].pTab, zCol);
85597    if( iCol>=0 ){
85598      if( piTab ){
85599        *piTab = i;
85600        *piCol = iCol;
85601      }
85602      return 1;
85603    }
85604  }
85605  return 0;
85606}
85607
85608/*
85609** This function is used to add terms implied by JOIN syntax to the
85610** WHERE clause expression of a SELECT statement. The new term, which
85611** is ANDed with the existing WHERE clause, is of the form:
85612**
85613**    (tab1.col1 = tab2.col2)
85614**
85615** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
85616** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
85617** column iColRight of tab2.
85618*/
85619static void addWhereTerm(
85620  Parse *pParse,                  /* Parsing context */
85621  SrcList *pSrc,                  /* List of tables in FROM clause */
85622  int iLeft,                      /* Index of first table to join in pSrc */
85623  int iColLeft,                   /* Index of column in first table */
85624  int iRight,                     /* Index of second table in pSrc */
85625  int iColRight,                  /* Index of column in second table */
85626  int isOuterJoin,                /* True if this is an OUTER join */
85627  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
85628){
85629  sqlite3 *db = pParse->db;
85630  Expr *pE1;
85631  Expr *pE2;
85632  Expr *pEq;
85633
85634  assert( iLeft<iRight );
85635  assert( pSrc->nSrc>iRight );
85636  assert( pSrc->a[iLeft].pTab );
85637  assert( pSrc->a[iRight].pTab );
85638
85639  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
85640  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
85641
85642  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
85643  if( pEq && isOuterJoin ){
85644    ExprSetProperty(pEq, EP_FromJoin);
85645    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
85646    ExprSetIrreducible(pEq);
85647    pEq->iRightJoinTable = (i16)pE2->iTable;
85648  }
85649  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
85650}
85651
85652/*
85653** Set the EP_FromJoin property on all terms of the given expression.
85654** And set the Expr.iRightJoinTable to iTable for every term in the
85655** expression.
85656**
85657** The EP_FromJoin property is used on terms of an expression to tell
85658** the LEFT OUTER JOIN processing logic that this term is part of the
85659** join restriction specified in the ON or USING clause and not a part
85660** of the more general WHERE clause.  These terms are moved over to the
85661** WHERE clause during join processing but we need to remember that they
85662** originated in the ON or USING clause.
85663**
85664** The Expr.iRightJoinTable tells the WHERE clause processing that the
85665** expression depends on table iRightJoinTable even if that table is not
85666** explicitly mentioned in the expression.  That information is needed
85667** for cases like this:
85668**
85669**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
85670**
85671** The where clause needs to defer the handling of the t1.x=5
85672** term until after the t2 loop of the join.  In that way, a
85673** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
85674** defer the handling of t1.x=5, it will be processed immediately
85675** after the t1 loop and rows with t1.x!=5 will never appear in
85676** the output, which is incorrect.
85677*/
85678static void setJoinExpr(Expr *p, int iTable){
85679  while( p ){
85680    ExprSetProperty(p, EP_FromJoin);
85681    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
85682    ExprSetIrreducible(p);
85683    p->iRightJoinTable = (i16)iTable;
85684    setJoinExpr(p->pLeft, iTable);
85685    p = p->pRight;
85686  }
85687}
85688
85689/*
85690** This routine processes the join information for a SELECT statement.
85691** ON and USING clauses are converted into extra terms of the WHERE clause.
85692** NATURAL joins also create extra WHERE clause terms.
85693**
85694** The terms of a FROM clause are contained in the Select.pSrc structure.
85695** The left most table is the first entry in Select.pSrc.  The right-most
85696** table is the last entry.  The join operator is held in the entry to
85697** the left.  Thus entry 0 contains the join operator for the join between
85698** entries 0 and 1.  Any ON or USING clauses associated with the join are
85699** also attached to the left entry.
85700**
85701** This routine returns the number of errors encountered.
85702*/
85703static int sqliteProcessJoin(Parse *pParse, Select *p){
85704  SrcList *pSrc;                  /* All tables in the FROM clause */
85705  int i, j;                       /* Loop counters */
85706  struct SrcList_item *pLeft;     /* Left table being joined */
85707  struct SrcList_item *pRight;    /* Right table being joined */
85708
85709  pSrc = p->pSrc;
85710  pLeft = &pSrc->a[0];
85711  pRight = &pLeft[1];
85712  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
85713    Table *pLeftTab = pLeft->pTab;
85714    Table *pRightTab = pRight->pTab;
85715    int isOuter;
85716
85717    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
85718    isOuter = (pRight->jointype & JT_OUTER)!=0;
85719
85720    /* When the NATURAL keyword is present, add WHERE clause terms for
85721    ** every column that the two tables have in common.
85722    */
85723    if( pRight->jointype & JT_NATURAL ){
85724      if( pRight->pOn || pRight->pUsing ){
85725        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
85726           "an ON or USING clause", 0);
85727        return 1;
85728      }
85729      for(j=0; j<pRightTab->nCol; j++){
85730        char *zName;   /* Name of column in the right table */
85731        int iLeft;     /* Matching left table */
85732        int iLeftCol;  /* Matching column in the left table */
85733
85734        zName = pRightTab->aCol[j].zName;
85735        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
85736          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
85737                       isOuter, &p->pWhere);
85738        }
85739      }
85740    }
85741
85742    /* Disallow both ON and USING clauses in the same join
85743    */
85744    if( pRight->pOn && pRight->pUsing ){
85745      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
85746        "clauses in the same join");
85747      return 1;
85748    }
85749
85750    /* Add the ON clause to the end of the WHERE clause, connected by
85751    ** an AND operator.
85752    */
85753    if( pRight->pOn ){
85754      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
85755      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
85756      pRight->pOn = 0;
85757    }
85758
85759    /* Create extra terms on the WHERE clause for each column named
85760    ** in the USING clause.  Example: If the two tables to be joined are
85761    ** A and B and the USING clause names X, Y, and Z, then add this
85762    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
85763    ** Report an error if any column mentioned in the USING clause is
85764    ** not contained in both tables to be joined.
85765    */
85766    if( pRight->pUsing ){
85767      IdList *pList = pRight->pUsing;
85768      for(j=0; j<pList->nId; j++){
85769        char *zName;     /* Name of the term in the USING clause */
85770        int iLeft;       /* Table on the left with matching column name */
85771        int iLeftCol;    /* Column number of matching column on the left */
85772        int iRightCol;   /* Column number of matching column on the right */
85773
85774        zName = pList->a[j].zName;
85775        iRightCol = columnIndex(pRightTab, zName);
85776        if( iRightCol<0
85777         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
85778        ){
85779          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
85780            "not present in both tables", zName);
85781          return 1;
85782        }
85783        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
85784                     isOuter, &p->pWhere);
85785      }
85786    }
85787  }
85788  return 0;
85789}
85790
85791/*
85792** Insert code into "v" that will push the record on the top of the
85793** stack into the sorter.
85794*/
85795static void pushOntoSorter(
85796  Parse *pParse,         /* Parser context */
85797  ExprList *pOrderBy,    /* The ORDER BY clause */
85798  Select *pSelect,       /* The whole SELECT statement */
85799  int regData            /* Register holding data to be sorted */
85800){
85801  Vdbe *v = pParse->pVdbe;
85802  int nExpr = pOrderBy->nExpr;
85803  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
85804  int regRecord = sqlite3GetTempReg(pParse);
85805  sqlite3ExprCacheClear(pParse);
85806  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
85807  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
85808  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
85809  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
85810  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
85811  sqlite3ReleaseTempReg(pParse, regRecord);
85812  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
85813  if( pSelect->iLimit ){
85814    int addr1, addr2;
85815    int iLimit;
85816    if( pSelect->iOffset ){
85817      iLimit = pSelect->iOffset+1;
85818    }else{
85819      iLimit = pSelect->iLimit;
85820    }
85821    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
85822    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
85823    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
85824    sqlite3VdbeJumpHere(v, addr1);
85825    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
85826    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
85827    sqlite3VdbeJumpHere(v, addr2);
85828    pSelect->iLimit = 0;
85829  }
85830}
85831
85832/*
85833** Add code to implement the OFFSET
85834*/
85835static void codeOffset(
85836  Vdbe *v,          /* Generate code into this VM */
85837  Select *p,        /* The SELECT statement being coded */
85838  int iContinue     /* Jump here to skip the current record */
85839){
85840  if( p->iOffset && iContinue!=0 ){
85841    int addr;
85842    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
85843    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
85844    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
85845    VdbeComment((v, "skip OFFSET records"));
85846    sqlite3VdbeJumpHere(v, addr);
85847  }
85848}
85849
85850/*
85851** Add code that will check to make sure the N registers starting at iMem
85852** form a distinct entry.  iTab is a sorting index that holds previously
85853** seen combinations of the N values.  A new entry is made in iTab
85854** if the current N values are new.
85855**
85856** A jump to addrRepeat is made and the N+1 values are popped from the
85857** stack if the top N elements are not distinct.
85858*/
85859static void codeDistinct(
85860  Parse *pParse,     /* Parsing and code generating context */
85861  int iTab,          /* A sorting index used to test for distinctness */
85862  int addrRepeat,    /* Jump to here if not distinct */
85863  int N,             /* Number of elements */
85864  int iMem           /* First element */
85865){
85866  Vdbe *v;
85867  int r1;
85868
85869  v = pParse->pVdbe;
85870  r1 = sqlite3GetTempReg(pParse);
85871  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
85872  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
85873  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
85874  sqlite3ReleaseTempReg(pParse, r1);
85875}
85876
85877/*
85878** Generate an error message when a SELECT is used within a subexpression
85879** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
85880** column.  We do this in a subroutine because the error occurs in multiple
85881** places.
85882*/
85883static int checkForMultiColumnSelectError(
85884  Parse *pParse,       /* Parse context. */
85885  SelectDest *pDest,   /* Destination of SELECT results */
85886  int nExpr            /* Number of result columns returned by SELECT */
85887){
85888  int eDest = pDest->eDest;
85889  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
85890    sqlite3ErrorMsg(pParse, "only a single result allowed for "
85891       "a SELECT that is part of an expression");
85892    return 1;
85893  }else{
85894    return 0;
85895  }
85896}
85897
85898/*
85899** This routine generates the code for the inside of the inner loop
85900** of a SELECT.
85901**
85902** If srcTab and nColumn are both zero, then the pEList expressions
85903** are evaluated in order to get the data for this row.  If nColumn>0
85904** then data is pulled from srcTab and pEList is used only to get the
85905** datatypes for each column.
85906*/
85907static void selectInnerLoop(
85908  Parse *pParse,          /* The parser context */
85909  Select *p,              /* The complete select statement being coded */
85910  ExprList *pEList,       /* List of values being extracted */
85911  int srcTab,             /* Pull data from this table */
85912  int nColumn,            /* Number of columns in the source table */
85913  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
85914  int distinct,           /* If >=0, make sure results are distinct */
85915  SelectDest *pDest,      /* How to dispose of the results */
85916  int iContinue,          /* Jump here to continue with next row */
85917  int iBreak              /* Jump here to break out of the inner loop */
85918){
85919  Vdbe *v = pParse->pVdbe;
85920  int i;
85921  int hasDistinct;        /* True if the DISTINCT keyword is present */
85922  int regResult;              /* Start of memory holding result set */
85923  int eDest = pDest->eDest;   /* How to dispose of results */
85924  int iParm = pDest->iParm;   /* First argument to disposal method */
85925  int nResultCol;             /* Number of result columns */
85926
85927  assert( v );
85928  if( NEVER(v==0) ) return;
85929  assert( pEList!=0 );
85930  hasDistinct = distinct>=0;
85931  if( pOrderBy==0 && !hasDistinct ){
85932    codeOffset(v, p, iContinue);
85933  }
85934
85935  /* Pull the requested columns.
85936  */
85937  if( nColumn>0 ){
85938    nResultCol = nColumn;
85939  }else{
85940    nResultCol = pEList->nExpr;
85941  }
85942  if( pDest->iMem==0 ){
85943    pDest->iMem = pParse->nMem+1;
85944    pDest->nMem = nResultCol;
85945    pParse->nMem += nResultCol;
85946  }else{
85947    assert( pDest->nMem==nResultCol );
85948  }
85949  regResult = pDest->iMem;
85950  if( nColumn>0 ){
85951    for(i=0; i<nColumn; i++){
85952      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
85953    }
85954  }else if( eDest!=SRT_Exists ){
85955    /* If the destination is an EXISTS(...) expression, the actual
85956    ** values returned by the SELECT are not required.
85957    */
85958    sqlite3ExprCacheClear(pParse);
85959    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
85960  }
85961  nColumn = nResultCol;
85962
85963  /* If the DISTINCT keyword was present on the SELECT statement
85964  ** and this row has been seen before, then do not make this row
85965  ** part of the result.
85966  */
85967  if( hasDistinct ){
85968    assert( pEList!=0 );
85969    assert( pEList->nExpr==nColumn );
85970    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
85971    if( pOrderBy==0 ){
85972      codeOffset(v, p, iContinue);
85973    }
85974  }
85975
85976  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
85977    return;
85978  }
85979
85980  switch( eDest ){
85981    /* In this mode, write each query result to the key of the temporary
85982    ** table iParm.
85983    */
85984#ifndef SQLITE_OMIT_COMPOUND_SELECT
85985    case SRT_Union: {
85986      int r1;
85987      r1 = sqlite3GetTempReg(pParse);
85988      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
85989      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
85990      sqlite3ReleaseTempReg(pParse, r1);
85991      break;
85992    }
85993
85994    /* Construct a record from the query result, but instead of
85995    ** saving that record, use it as a key to delete elements from
85996    ** the temporary table iParm.
85997    */
85998    case SRT_Except: {
85999      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
86000      break;
86001    }
86002#endif
86003
86004    /* Store the result as data using a unique key.
86005    */
86006    case SRT_Table:
86007    case SRT_EphemTab: {
86008      int r1 = sqlite3GetTempReg(pParse);
86009      testcase( eDest==SRT_Table );
86010      testcase( eDest==SRT_EphemTab );
86011      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86012      if( pOrderBy ){
86013        pushOntoSorter(pParse, pOrderBy, p, r1);
86014      }else{
86015        int r2 = sqlite3GetTempReg(pParse);
86016        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
86017        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
86018        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86019        sqlite3ReleaseTempReg(pParse, r2);
86020      }
86021      sqlite3ReleaseTempReg(pParse, r1);
86022      break;
86023    }
86024
86025#ifndef SQLITE_OMIT_SUBQUERY
86026    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
86027    ** then there should be a single item on the stack.  Write this
86028    ** item into the set table with bogus data.
86029    */
86030    case SRT_Set: {
86031      assert( nColumn==1 );
86032      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
86033      if( pOrderBy ){
86034        /* At first glance you would think we could optimize out the
86035        ** ORDER BY in this case since the order of entries in the set
86036        ** does not matter.  But there might be a LIMIT clause, in which
86037        ** case the order does matter */
86038        pushOntoSorter(pParse, pOrderBy, p, regResult);
86039      }else{
86040        int r1 = sqlite3GetTempReg(pParse);
86041        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
86042        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
86043        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
86044        sqlite3ReleaseTempReg(pParse, r1);
86045      }
86046      break;
86047    }
86048
86049    /* If any row exist in the result set, record that fact and abort.
86050    */
86051    case SRT_Exists: {
86052      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
86053      /* The LIMIT clause will terminate the loop for us */
86054      break;
86055    }
86056
86057    /* If this is a scalar select that is part of an expression, then
86058    ** store the results in the appropriate memory cell and break out
86059    ** of the scan loop.
86060    */
86061    case SRT_Mem: {
86062      assert( nColumn==1 );
86063      if( pOrderBy ){
86064        pushOntoSorter(pParse, pOrderBy, p, regResult);
86065      }else{
86066        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
86067        /* The LIMIT clause will jump out of the loop for us */
86068      }
86069      break;
86070    }
86071#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
86072
86073    /* Send the data to the callback function or to a subroutine.  In the
86074    ** case of a subroutine, the subroutine itself is responsible for
86075    ** popping the data from the stack.
86076    */
86077    case SRT_Coroutine:
86078    case SRT_Output: {
86079      testcase( eDest==SRT_Coroutine );
86080      testcase( eDest==SRT_Output );
86081      if( pOrderBy ){
86082        int r1 = sqlite3GetTempReg(pParse);
86083        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86084        pushOntoSorter(pParse, pOrderBy, p, r1);
86085        sqlite3ReleaseTempReg(pParse, r1);
86086      }else if( eDest==SRT_Coroutine ){
86087        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86088      }else{
86089        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
86090        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
86091      }
86092      break;
86093    }
86094
86095#if !defined(SQLITE_OMIT_TRIGGER)
86096    /* Discard the results.  This is used for SELECT statements inside
86097    ** the body of a TRIGGER.  The purpose of such selects is to call
86098    ** user-defined functions that have side effects.  We do not care
86099    ** about the actual results of the select.
86100    */
86101    default: {
86102      assert( eDest==SRT_Discard );
86103      break;
86104    }
86105#endif
86106  }
86107
86108  /* Jump to the end of the loop if the LIMIT is reached.
86109  */
86110  if( p->iLimit ){
86111    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
86112                            ** pushOntoSorter() would have cleared p->iLimit */
86113    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
86114  }
86115}
86116
86117/*
86118** Given an expression list, generate a KeyInfo structure that records
86119** the collating sequence for each expression in that expression list.
86120**
86121** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
86122** KeyInfo structure is appropriate for initializing a virtual index to
86123** implement that clause.  If the ExprList is the result set of a SELECT
86124** then the KeyInfo structure is appropriate for initializing a virtual
86125** index to implement a DISTINCT test.
86126**
86127** Space to hold the KeyInfo structure is obtain from malloc.  The calling
86128** function is responsible for seeing that this structure is eventually
86129** freed.  Add the KeyInfo structure to the P4 field of an opcode using
86130** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
86131*/
86132static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
86133  sqlite3 *db = pParse->db;
86134  int nExpr;
86135  KeyInfo *pInfo;
86136  struct ExprList_item *pItem;
86137  int i;
86138
86139  nExpr = pList->nExpr;
86140  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
86141  if( pInfo ){
86142    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
86143    pInfo->nField = (u16)nExpr;
86144    pInfo->enc = ENC(db);
86145    pInfo->db = db;
86146    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
86147      CollSeq *pColl;
86148      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
86149      if( !pColl ){
86150        pColl = db->pDfltColl;
86151      }
86152      pInfo->aColl[i] = pColl;
86153      pInfo->aSortOrder[i] = pItem->sortOrder;
86154    }
86155  }
86156  return pInfo;
86157}
86158
86159
86160/*
86161** If the inner loop was generated using a non-null pOrderBy argument,
86162** then the results were placed in a sorter.  After the loop is terminated
86163** we need to run the sorter and output the results.  The following
86164** routine generates the code needed to do that.
86165*/
86166static void generateSortTail(
86167  Parse *pParse,    /* Parsing context */
86168  Select *p,        /* The SELECT statement */
86169  Vdbe *v,          /* Generate code into this VDBE */
86170  int nColumn,      /* Number of columns of data */
86171  SelectDest *pDest /* Write the sorted results here */
86172){
86173  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
86174  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
86175  int addr;
86176  int iTab;
86177  int pseudoTab = 0;
86178  ExprList *pOrderBy = p->pOrderBy;
86179
86180  int eDest = pDest->eDest;
86181  int iParm = pDest->iParm;
86182
86183  int regRow;
86184  int regRowid;
86185
86186  iTab = pOrderBy->iECursor;
86187  regRow = sqlite3GetTempReg(pParse);
86188  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86189    pseudoTab = pParse->nTab++;
86190    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
86191    regRowid = 0;
86192  }else{
86193    regRowid = sqlite3GetTempReg(pParse);
86194  }
86195  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
86196  codeOffset(v, p, addrContinue);
86197  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
86198  switch( eDest ){
86199    case SRT_Table:
86200    case SRT_EphemTab: {
86201      testcase( eDest==SRT_Table );
86202      testcase( eDest==SRT_EphemTab );
86203      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
86204      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
86205      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86206      break;
86207    }
86208#ifndef SQLITE_OMIT_SUBQUERY
86209    case SRT_Set: {
86210      assert( nColumn==1 );
86211      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
86212      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
86213      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
86214      break;
86215    }
86216    case SRT_Mem: {
86217      assert( nColumn==1 );
86218      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
86219      /* The LIMIT clause will terminate the loop for us */
86220      break;
86221    }
86222#endif
86223    default: {
86224      int i;
86225      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
86226      testcase( eDest==SRT_Output );
86227      testcase( eDest==SRT_Coroutine );
86228      for(i=0; i<nColumn; i++){
86229        assert( regRow!=pDest->iMem+i );
86230        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
86231        if( i==0 ){
86232          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
86233        }
86234      }
86235      if( eDest==SRT_Output ){
86236        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
86237        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
86238      }else{
86239        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86240      }
86241      break;
86242    }
86243  }
86244  sqlite3ReleaseTempReg(pParse, regRow);
86245  sqlite3ReleaseTempReg(pParse, regRowid);
86246
86247  /* LIMIT has been implemented by the pushOntoSorter() routine.
86248  */
86249  assert( p->iLimit==0 );
86250
86251  /* The bottom of the loop
86252  */
86253  sqlite3VdbeResolveLabel(v, addrContinue);
86254  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
86255  sqlite3VdbeResolveLabel(v, addrBreak);
86256  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86257    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
86258  }
86259}
86260
86261/*
86262** Return a pointer to a string containing the 'declaration type' of the
86263** expression pExpr. The string may be treated as static by the caller.
86264**
86265** The declaration type is the exact datatype definition extracted from the
86266** original CREATE TABLE statement if the expression is a column. The
86267** declaration type for a ROWID field is INTEGER. Exactly when an expression
86268** is considered a column can be complex in the presence of subqueries. The
86269** result-set expression in all of the following SELECT statements is
86270** considered a column by this function.
86271**
86272**   SELECT col FROM tbl;
86273**   SELECT (SELECT col FROM tbl;
86274**   SELECT (SELECT col FROM tbl);
86275**   SELECT abc FROM (SELECT col AS abc FROM tbl);
86276**
86277** The declaration type for any expression other than a column is NULL.
86278*/
86279static const char *columnType(
86280  NameContext *pNC,
86281  Expr *pExpr,
86282  const char **pzOriginDb,
86283  const char **pzOriginTab,
86284  const char **pzOriginCol
86285){
86286  char const *zType = 0;
86287  char const *zOriginDb = 0;
86288  char const *zOriginTab = 0;
86289  char const *zOriginCol = 0;
86290  int j;
86291  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
86292
86293  switch( pExpr->op ){
86294    case TK_AGG_COLUMN:
86295    case TK_COLUMN: {
86296      /* The expression is a column. Locate the table the column is being
86297      ** extracted from in NameContext.pSrcList. This table may be real
86298      ** database table or a subquery.
86299      */
86300      Table *pTab = 0;            /* Table structure column is extracted from */
86301      Select *pS = 0;             /* Select the column is extracted from */
86302      int iCol = pExpr->iColumn;  /* Index of column in pTab */
86303      testcase( pExpr->op==TK_AGG_COLUMN );
86304      testcase( pExpr->op==TK_COLUMN );
86305      while( pNC && !pTab ){
86306        SrcList *pTabList = pNC->pSrcList;
86307        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
86308        if( j<pTabList->nSrc ){
86309          pTab = pTabList->a[j].pTab;
86310          pS = pTabList->a[j].pSelect;
86311        }else{
86312          pNC = pNC->pNext;
86313        }
86314      }
86315
86316      if( pTab==0 ){
86317        /* At one time, code such as "SELECT new.x" within a trigger would
86318        ** cause this condition to run.  Since then, we have restructured how
86319        ** trigger code is generated and so this condition is no longer
86320        ** possible. However, it can still be true for statements like
86321        ** the following:
86322        **
86323        **   CREATE TABLE t1(col INTEGER);
86324        **   SELECT (SELECT t1.col) FROM FROM t1;
86325        **
86326        ** when columnType() is called on the expression "t1.col" in the
86327        ** sub-select. In this case, set the column type to NULL, even
86328        ** though it should really be "INTEGER".
86329        **
86330        ** This is not a problem, as the column type of "t1.col" is never
86331        ** used. When columnType() is called on the expression
86332        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
86333        ** branch below.  */
86334        break;
86335      }
86336
86337      assert( pTab && pExpr->pTab==pTab );
86338      if( pS ){
86339        /* The "table" is actually a sub-select or a view in the FROM clause
86340        ** of the SELECT statement. Return the declaration type and origin
86341        ** data for the result-set column of the sub-select.
86342        */
86343        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
86344          /* If iCol is less than zero, then the expression requests the
86345          ** rowid of the sub-select or view. This expression is legal (see
86346          ** test case misc2.2.2) - it always evaluates to NULL.
86347          */
86348          NameContext sNC;
86349          Expr *p = pS->pEList->a[iCol].pExpr;
86350          sNC.pSrcList = pS->pSrc;
86351          sNC.pNext = pNC;
86352          sNC.pParse = pNC->pParse;
86353          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
86354        }
86355      }else if( ALWAYS(pTab->pSchema) ){
86356        /* A real table */
86357        assert( !pS );
86358        if( iCol<0 ) iCol = pTab->iPKey;
86359        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86360        if( iCol<0 ){
86361          zType = "INTEGER";
86362          zOriginCol = "rowid";
86363        }else{
86364          zType = pTab->aCol[iCol].zType;
86365          zOriginCol = pTab->aCol[iCol].zName;
86366        }
86367        zOriginTab = pTab->zName;
86368        if( pNC->pParse ){
86369          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
86370          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
86371        }
86372      }
86373      break;
86374    }
86375#ifndef SQLITE_OMIT_SUBQUERY
86376    case TK_SELECT: {
86377      /* The expression is a sub-select. Return the declaration type and
86378      ** origin info for the single column in the result set of the SELECT
86379      ** statement.
86380      */
86381      NameContext sNC;
86382      Select *pS = pExpr->x.pSelect;
86383      Expr *p = pS->pEList->a[0].pExpr;
86384      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
86385      sNC.pSrcList = pS->pSrc;
86386      sNC.pNext = pNC;
86387      sNC.pParse = pNC->pParse;
86388      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
86389      break;
86390    }
86391#endif
86392  }
86393
86394  if( pzOriginDb ){
86395    assert( pzOriginTab && pzOriginCol );
86396    *pzOriginDb = zOriginDb;
86397    *pzOriginTab = zOriginTab;
86398    *pzOriginCol = zOriginCol;
86399  }
86400  return zType;
86401}
86402
86403/*
86404** Generate code that will tell the VDBE the declaration types of columns
86405** in the result set.
86406*/
86407static void generateColumnTypes(
86408  Parse *pParse,      /* Parser context */
86409  SrcList *pTabList,  /* List of tables */
86410  ExprList *pEList    /* Expressions defining the result set */
86411){
86412#ifndef SQLITE_OMIT_DECLTYPE
86413  Vdbe *v = pParse->pVdbe;
86414  int i;
86415  NameContext sNC;
86416  sNC.pSrcList = pTabList;
86417  sNC.pParse = pParse;
86418  for(i=0; i<pEList->nExpr; i++){
86419    Expr *p = pEList->a[i].pExpr;
86420    const char *zType;
86421#ifdef SQLITE_ENABLE_COLUMN_METADATA
86422    const char *zOrigDb = 0;
86423    const char *zOrigTab = 0;
86424    const char *zOrigCol = 0;
86425    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
86426
86427    /* The vdbe must make its own copy of the column-type and other
86428    ** column specific strings, in case the schema is reset before this
86429    ** virtual machine is deleted.
86430    */
86431    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
86432    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
86433    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
86434#else
86435    zType = columnType(&sNC, p, 0, 0, 0);
86436#endif
86437    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
86438  }
86439#endif /* SQLITE_OMIT_DECLTYPE */
86440}
86441
86442/*
86443** Generate code that will tell the VDBE the names of columns
86444** in the result set.  This information is used to provide the
86445** azCol[] values in the callback.
86446*/
86447static void generateColumnNames(
86448  Parse *pParse,      /* Parser context */
86449  SrcList *pTabList,  /* List of tables */
86450  ExprList *pEList    /* Expressions defining the result set */
86451){
86452  Vdbe *v = pParse->pVdbe;
86453  int i, j;
86454  sqlite3 *db = pParse->db;
86455  int fullNames, shortNames;
86456
86457#ifndef SQLITE_OMIT_EXPLAIN
86458  /* If this is an EXPLAIN, skip this step */
86459  if( pParse->explain ){
86460    return;
86461  }
86462#endif
86463
86464  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
86465  pParse->colNamesSet = 1;
86466  fullNames = (db->flags & SQLITE_FullColNames)!=0;
86467  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
86468  sqlite3VdbeSetNumCols(v, pEList->nExpr);
86469  for(i=0; i<pEList->nExpr; i++){
86470    Expr *p;
86471    p = pEList->a[i].pExpr;
86472    if( NEVER(p==0) ) continue;
86473    if( pEList->a[i].zName ){
86474      char *zName = pEList->a[i].zName;
86475      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
86476    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
86477      Table *pTab;
86478      char *zCol;
86479      int iCol = p->iColumn;
86480      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
86481        if( pTabList->a[j].iCursor==p->iTable ) break;
86482      }
86483      assert( j<pTabList->nSrc );
86484      pTab = pTabList->a[j].pTab;
86485      if( iCol<0 ) iCol = pTab->iPKey;
86486      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86487      if( iCol<0 ){
86488        zCol = "rowid";
86489      }else{
86490        zCol = pTab->aCol[iCol].zName;
86491      }
86492      if( !shortNames && !fullNames ){
86493        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
86494            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86495      }else if( fullNames ){
86496        char *zName = 0;
86497        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
86498        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
86499      }else{
86500        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
86501      }
86502    }else{
86503      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
86504          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86505    }
86506  }
86507  generateColumnTypes(pParse, pTabList, pEList);
86508}
86509
86510#ifndef SQLITE_OMIT_COMPOUND_SELECT
86511/*
86512** Name of the connection operator, used for error messages.
86513*/
86514static const char *selectOpName(int id){
86515  char *z;
86516  switch( id ){
86517    case TK_ALL:       z = "UNION ALL";   break;
86518    case TK_INTERSECT: z = "INTERSECT";   break;
86519    case TK_EXCEPT:    z = "EXCEPT";      break;
86520    default:           z = "UNION";       break;
86521  }
86522  return z;
86523}
86524#endif /* SQLITE_OMIT_COMPOUND_SELECT */
86525
86526/*
86527** Given a an expression list (which is really the list of expressions
86528** that form the result set of a SELECT statement) compute appropriate
86529** column names for a table that would hold the expression list.
86530**
86531** All column names will be unique.
86532**
86533** Only the column names are computed.  Column.zType, Column.zColl,
86534** and other fields of Column are zeroed.
86535**
86536** Return SQLITE_OK on success.  If a memory allocation error occurs,
86537** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
86538*/
86539static int selectColumnsFromExprList(
86540  Parse *pParse,          /* Parsing context */
86541  ExprList *pEList,       /* Expr list from which to derive column names */
86542  int *pnCol,             /* Write the number of columns here */
86543  Column **paCol          /* Write the new column list here */
86544){
86545  sqlite3 *db = pParse->db;   /* Database connection */
86546  int i, j;                   /* Loop counters */
86547  int cnt;                    /* Index added to make the name unique */
86548  Column *aCol, *pCol;        /* For looping over result columns */
86549  int nCol;                   /* Number of columns in the result set */
86550  Expr *p;                    /* Expression for a single result column */
86551  char *zName;                /* Column name */
86552  int nName;                  /* Size of name in zName[] */
86553
86554  *pnCol = nCol = pEList->nExpr;
86555  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
86556  if( aCol==0 ) return SQLITE_NOMEM;
86557  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
86558    /* Get an appropriate name for the column
86559    */
86560    p = pEList->a[i].pExpr;
86561    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
86562               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
86563    if( (zName = pEList->a[i].zName)!=0 ){
86564      /* If the column contains an "AS <name>" phrase, use <name> as the name */
86565      zName = sqlite3DbStrDup(db, zName);
86566    }else{
86567      Expr *pColExpr = p;  /* The expression that is the result column name */
86568      Table *pTab;         /* Table associated with this expression */
86569      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
86570      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
86571        /* For columns use the column name name */
86572        int iCol = pColExpr->iColumn;
86573        pTab = pColExpr->pTab;
86574        if( iCol<0 ) iCol = pTab->iPKey;
86575        zName = sqlite3MPrintf(db, "%s",
86576                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
86577      }else if( pColExpr->op==TK_ID ){
86578        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
86579        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
86580      }else{
86581        /* Use the original text of the column expression as its name */
86582        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
86583      }
86584    }
86585    if( db->mallocFailed ){
86586      sqlite3DbFree(db, zName);
86587      break;
86588    }
86589
86590    /* Make sure the column name is unique.  If the name is not unique,
86591    ** append a integer to the name so that it becomes unique.
86592    */
86593    nName = sqlite3Strlen30(zName);
86594    for(j=cnt=0; j<i; j++){
86595      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
86596        char *zNewName;
86597        zName[nName] = 0;
86598        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
86599        sqlite3DbFree(db, zName);
86600        zName = zNewName;
86601        j = -1;
86602        if( zName==0 ) break;
86603      }
86604    }
86605    pCol->zName = zName;
86606  }
86607  if( db->mallocFailed ){
86608    for(j=0; j<i; j++){
86609      sqlite3DbFree(db, aCol[j].zName);
86610    }
86611    sqlite3DbFree(db, aCol);
86612    *paCol = 0;
86613    *pnCol = 0;
86614    return SQLITE_NOMEM;
86615  }
86616  return SQLITE_OK;
86617}
86618
86619/*
86620** Add type and collation information to a column list based on
86621** a SELECT statement.
86622**
86623** The column list presumably came from selectColumnNamesFromExprList().
86624** The column list has only names, not types or collations.  This
86625** routine goes through and adds the types and collations.
86626**
86627** This routine requires that all identifiers in the SELECT
86628** statement be resolved.
86629*/
86630static void selectAddColumnTypeAndCollation(
86631  Parse *pParse,        /* Parsing contexts */
86632  int nCol,             /* Number of columns */
86633  Column *aCol,         /* List of columns */
86634  Select *pSelect       /* SELECT used to determine types and collations */
86635){
86636  sqlite3 *db = pParse->db;
86637  NameContext sNC;
86638  Column *pCol;
86639  CollSeq *pColl;
86640  int i;
86641  Expr *p;
86642  struct ExprList_item *a;
86643
86644  assert( pSelect!=0 );
86645  assert( (pSelect->selFlags & SF_Resolved)!=0 );
86646  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
86647  if( db->mallocFailed ) return;
86648  memset(&sNC, 0, sizeof(sNC));
86649  sNC.pSrcList = pSelect->pSrc;
86650  a = pSelect->pEList->a;
86651  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
86652    p = a[i].pExpr;
86653    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
86654    pCol->affinity = sqlite3ExprAffinity(p);
86655    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
86656    pColl = sqlite3ExprCollSeq(pParse, p);
86657    if( pColl ){
86658      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
86659    }
86660  }
86661}
86662
86663/*
86664** Given a SELECT statement, generate a Table structure that describes
86665** the result set of that SELECT.
86666*/
86667SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
86668  Table *pTab;
86669  sqlite3 *db = pParse->db;
86670  int savedFlags;
86671
86672  savedFlags = db->flags;
86673  db->flags &= ~SQLITE_FullColNames;
86674  db->flags |= SQLITE_ShortColNames;
86675  sqlite3SelectPrep(pParse, pSelect, 0);
86676  if( pParse->nErr ) return 0;
86677  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
86678  db->flags = savedFlags;
86679  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
86680  if( pTab==0 ){
86681    return 0;
86682  }
86683  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
86684  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
86685  assert( db->lookaside.bEnabled==0 );
86686  pTab->dbMem = 0;
86687  pTab->nRef = 1;
86688  pTab->zName = 0;
86689  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
86690  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
86691  pTab->iPKey = -1;
86692  if( db->mallocFailed ){
86693    sqlite3DeleteTable(pTab);
86694    return 0;
86695  }
86696  return pTab;
86697}
86698
86699/*
86700** Get a VDBE for the given parser context.  Create a new one if necessary.
86701** If an error occurs, return NULL and leave a message in pParse.
86702*/
86703SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
86704  Vdbe *v = pParse->pVdbe;
86705  if( v==0 ){
86706    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
86707#ifndef SQLITE_OMIT_TRACE
86708    if( v ){
86709      sqlite3VdbeAddOp0(v, OP_Trace);
86710    }
86711#endif
86712  }
86713  return v;
86714}
86715
86716
86717/*
86718** Compute the iLimit and iOffset fields of the SELECT based on the
86719** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
86720** that appear in the original SQL statement after the LIMIT and OFFSET
86721** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
86722** are the integer memory register numbers for counters used to compute
86723** the limit and offset.  If there is no limit and/or offset, then
86724** iLimit and iOffset are negative.
86725**
86726** This routine changes the values of iLimit and iOffset only if
86727** a limit or offset is defined by pLimit and pOffset.  iLimit and
86728** iOffset should have been preset to appropriate default values
86729** (usually but not always -1) prior to calling this routine.
86730** Only if pLimit!=0 or pOffset!=0 do the limit registers get
86731** redefined.  The UNION ALL operator uses this property to force
86732** the reuse of the same limit and offset registers across multiple
86733** SELECT statements.
86734*/
86735static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
86736  Vdbe *v = 0;
86737  int iLimit = 0;
86738  int iOffset;
86739  int addr1, n;
86740  if( p->iLimit ) return;
86741
86742  /*
86743  ** "LIMIT -1" always shows all rows.  There is some
86744  ** contraversy about what the correct behavior should be.
86745  ** The current implementation interprets "LIMIT 0" to mean
86746  ** no rows.
86747  */
86748  sqlite3ExprCacheClear(pParse);
86749  assert( p->pOffset==0 || p->pLimit!=0 );
86750  if( p->pLimit ){
86751    p->iLimit = iLimit = ++pParse->nMem;
86752    v = sqlite3GetVdbe(pParse);
86753    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
86754    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
86755      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
86756      VdbeComment((v, "LIMIT counter"));
86757      if( n==0 ){
86758        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
86759      }
86760    }else{
86761      sqlite3ExprCode(pParse, p->pLimit, iLimit);
86762      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
86763      VdbeComment((v, "LIMIT counter"));
86764      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
86765    }
86766    if( p->pOffset ){
86767      p->iOffset = iOffset = ++pParse->nMem;
86768      pParse->nMem++;   /* Allocate an extra register for limit+offset */
86769      sqlite3ExprCode(pParse, p->pOffset, iOffset);
86770      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
86771      VdbeComment((v, "OFFSET counter"));
86772      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
86773      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
86774      sqlite3VdbeJumpHere(v, addr1);
86775      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
86776      VdbeComment((v, "LIMIT+OFFSET"));
86777      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
86778      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
86779      sqlite3VdbeJumpHere(v, addr1);
86780    }
86781  }
86782}
86783
86784#ifndef SQLITE_OMIT_COMPOUND_SELECT
86785/*
86786** Return the appropriate collating sequence for the iCol-th column of
86787** the result set for the compound-select statement "p".  Return NULL if
86788** the column has no default collating sequence.
86789**
86790** The collating sequence for the compound select is taken from the
86791** left-most term of the select that has a collating sequence.
86792*/
86793static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
86794  CollSeq *pRet;
86795  if( p->pPrior ){
86796    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
86797  }else{
86798    pRet = 0;
86799  }
86800  assert( iCol>=0 );
86801  if( pRet==0 && iCol<p->pEList->nExpr ){
86802    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
86803  }
86804  return pRet;
86805}
86806#endif /* SQLITE_OMIT_COMPOUND_SELECT */
86807
86808/* Forward reference */
86809static int multiSelectOrderBy(
86810  Parse *pParse,        /* Parsing context */
86811  Select *p,            /* The right-most of SELECTs to be coded */
86812  SelectDest *pDest     /* What to do with query results */
86813);
86814
86815
86816#ifndef SQLITE_OMIT_COMPOUND_SELECT
86817/*
86818** This routine is called to process a compound query form from
86819** two or more separate queries using UNION, UNION ALL, EXCEPT, or
86820** INTERSECT
86821**
86822** "p" points to the right-most of the two queries.  the query on the
86823** left is p->pPrior.  The left query could also be a compound query
86824** in which case this routine will be called recursively.
86825**
86826** The results of the total query are to be written into a destination
86827** of type eDest with parameter iParm.
86828**
86829** Example 1:  Consider a three-way compound SQL statement.
86830**
86831**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
86832**
86833** This statement is parsed up as follows:
86834**
86835**     SELECT c FROM t3
86836**      |
86837**      `----->  SELECT b FROM t2
86838**                |
86839**                `------>  SELECT a FROM t1
86840**
86841** The arrows in the diagram above represent the Select.pPrior pointer.
86842** So if this routine is called with p equal to the t3 query, then
86843** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
86844**
86845** Notice that because of the way SQLite parses compound SELECTs, the
86846** individual selects always group from left to right.
86847*/
86848static int multiSelect(
86849  Parse *pParse,        /* Parsing context */
86850  Select *p,            /* The right-most of SELECTs to be coded */
86851  SelectDest *pDest     /* What to do with query results */
86852){
86853  int rc = SQLITE_OK;   /* Success code from a subroutine */
86854  Select *pPrior;       /* Another SELECT immediately to our left */
86855  Vdbe *v;              /* Generate code to this VDBE */
86856  SelectDest dest;      /* Alternative data destination */
86857  Select *pDelete = 0;  /* Chain of simple selects to delete */
86858  sqlite3 *db;          /* Database connection */
86859
86860  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
86861  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
86862  */
86863  assert( p && p->pPrior );  /* Calling function guarantees this much */
86864  db = pParse->db;
86865  pPrior = p->pPrior;
86866  assert( pPrior->pRightmost!=pPrior );
86867  assert( pPrior->pRightmost==p->pRightmost );
86868  dest = *pDest;
86869  if( pPrior->pOrderBy ){
86870    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
86871      selectOpName(p->op));
86872    rc = 1;
86873    goto multi_select_end;
86874  }
86875  if( pPrior->pLimit ){
86876    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
86877      selectOpName(p->op));
86878    rc = 1;
86879    goto multi_select_end;
86880  }
86881
86882  v = sqlite3GetVdbe(pParse);
86883  assert( v!=0 );  /* The VDBE already created by calling function */
86884
86885  /* Create the destination temporary table if necessary
86886  */
86887  if( dest.eDest==SRT_EphemTab ){
86888    assert( p->pEList );
86889    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
86890    dest.eDest = SRT_Table;
86891  }
86892
86893  /* Make sure all SELECTs in the statement have the same number of elements
86894  ** in their result sets.
86895  */
86896  assert( p->pEList && pPrior->pEList );
86897  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
86898    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
86899      " do not have the same number of result columns", selectOpName(p->op));
86900    rc = 1;
86901    goto multi_select_end;
86902  }
86903
86904  /* Compound SELECTs that have an ORDER BY clause are handled separately.
86905  */
86906  if( p->pOrderBy ){
86907    return multiSelectOrderBy(pParse, p, pDest);
86908  }
86909
86910  /* Generate code for the left and right SELECT statements.
86911  */
86912  switch( p->op ){
86913    case TK_ALL: {
86914      int addr = 0;
86915      assert( !pPrior->pLimit );
86916      pPrior->pLimit = p->pLimit;
86917      pPrior->pOffset = p->pOffset;
86918      rc = sqlite3Select(pParse, pPrior, &dest);
86919      p->pLimit = 0;
86920      p->pOffset = 0;
86921      if( rc ){
86922        goto multi_select_end;
86923      }
86924      p->pPrior = 0;
86925      p->iLimit = pPrior->iLimit;
86926      p->iOffset = pPrior->iOffset;
86927      if( p->iLimit ){
86928        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
86929        VdbeComment((v, "Jump ahead if LIMIT reached"));
86930      }
86931      rc = sqlite3Select(pParse, p, &dest);
86932      testcase( rc!=SQLITE_OK );
86933      pDelete = p->pPrior;
86934      p->pPrior = pPrior;
86935      if( addr ){
86936        sqlite3VdbeJumpHere(v, addr);
86937      }
86938      break;
86939    }
86940    case TK_EXCEPT:
86941    case TK_UNION: {
86942      int unionTab;    /* Cursor number of the temporary table holding result */
86943      u8 op = 0;       /* One of the SRT_ operations to apply to self */
86944      int priorOp;     /* The SRT_ operation to apply to prior selects */
86945      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
86946      int addr;
86947      SelectDest uniondest;
86948
86949      testcase( p->op==TK_EXCEPT );
86950      testcase( p->op==TK_UNION );
86951      priorOp = SRT_Union;
86952      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
86953        /* We can reuse a temporary table generated by a SELECT to our
86954        ** right.
86955        */
86956        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
86957                                     ** of a 3-way or more compound */
86958        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
86959        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
86960        unionTab = dest.iParm;
86961      }else{
86962        /* We will need to create our own temporary table to hold the
86963        ** intermediate results.
86964        */
86965        unionTab = pParse->nTab++;
86966        assert( p->pOrderBy==0 );
86967        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
86968        assert( p->addrOpenEphm[0] == -1 );
86969        p->addrOpenEphm[0] = addr;
86970        p->pRightmost->selFlags |= SF_UsesEphemeral;
86971        assert( p->pEList );
86972      }
86973
86974      /* Code the SELECT statements to our left
86975      */
86976      assert( !pPrior->pOrderBy );
86977      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
86978      rc = sqlite3Select(pParse, pPrior, &uniondest);
86979      if( rc ){
86980        goto multi_select_end;
86981      }
86982
86983      /* Code the current SELECT statement
86984      */
86985      if( p->op==TK_EXCEPT ){
86986        op = SRT_Except;
86987      }else{
86988        assert( p->op==TK_UNION );
86989        op = SRT_Union;
86990      }
86991      p->pPrior = 0;
86992      pLimit = p->pLimit;
86993      p->pLimit = 0;
86994      pOffset = p->pOffset;
86995      p->pOffset = 0;
86996      uniondest.eDest = op;
86997      rc = sqlite3Select(pParse, p, &uniondest);
86998      testcase( rc!=SQLITE_OK );
86999      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
87000      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
87001      sqlite3ExprListDelete(db, p->pOrderBy);
87002      pDelete = p->pPrior;
87003      p->pPrior = pPrior;
87004      p->pOrderBy = 0;
87005      sqlite3ExprDelete(db, p->pLimit);
87006      p->pLimit = pLimit;
87007      p->pOffset = pOffset;
87008      p->iLimit = 0;
87009      p->iOffset = 0;
87010
87011      /* Convert the data in the temporary table into whatever form
87012      ** it is that we currently need.
87013      */
87014      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
87015      if( dest.eDest!=priorOp ){
87016        int iCont, iBreak, iStart;
87017        assert( p->pEList );
87018        if( dest.eDest==SRT_Output ){
87019          Select *pFirst = p;
87020          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87021          generateColumnNames(pParse, 0, pFirst->pEList);
87022        }
87023        iBreak = sqlite3VdbeMakeLabel(v);
87024        iCont = sqlite3VdbeMakeLabel(v);
87025        computeLimitRegisters(pParse, p, iBreak);
87026        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
87027        iStart = sqlite3VdbeCurrentAddr(v);
87028        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
87029                        0, -1, &dest, iCont, iBreak);
87030        sqlite3VdbeResolveLabel(v, iCont);
87031        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
87032        sqlite3VdbeResolveLabel(v, iBreak);
87033        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
87034      }
87035      break;
87036    }
87037    default: assert( p->op==TK_INTERSECT ); {
87038      int tab1, tab2;
87039      int iCont, iBreak, iStart;
87040      Expr *pLimit, *pOffset;
87041      int addr;
87042      SelectDest intersectdest;
87043      int r1;
87044
87045      /* INTERSECT is different from the others since it requires
87046      ** two temporary tables.  Hence it has its own case.  Begin
87047      ** by allocating the tables we will need.
87048      */
87049      tab1 = pParse->nTab++;
87050      tab2 = pParse->nTab++;
87051      assert( p->pOrderBy==0 );
87052
87053      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
87054      assert( p->addrOpenEphm[0] == -1 );
87055      p->addrOpenEphm[0] = addr;
87056      p->pRightmost->selFlags |= SF_UsesEphemeral;
87057      assert( p->pEList );
87058
87059      /* Code the SELECTs to our left into temporary table "tab1".
87060      */
87061      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
87062      rc = sqlite3Select(pParse, pPrior, &intersectdest);
87063      if( rc ){
87064        goto multi_select_end;
87065      }
87066
87067      /* Code the current SELECT into temporary table "tab2"
87068      */
87069      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
87070      assert( p->addrOpenEphm[1] == -1 );
87071      p->addrOpenEphm[1] = addr;
87072      p->pPrior = 0;
87073      pLimit = p->pLimit;
87074      p->pLimit = 0;
87075      pOffset = p->pOffset;
87076      p->pOffset = 0;
87077      intersectdest.iParm = tab2;
87078      rc = sqlite3Select(pParse, p, &intersectdest);
87079      testcase( rc!=SQLITE_OK );
87080      pDelete = p->pPrior;
87081      p->pPrior = pPrior;
87082      sqlite3ExprDelete(db, p->pLimit);
87083      p->pLimit = pLimit;
87084      p->pOffset = pOffset;
87085
87086      /* Generate code to take the intersection of the two temporary
87087      ** tables.
87088      */
87089      assert( p->pEList );
87090      if( dest.eDest==SRT_Output ){
87091        Select *pFirst = p;
87092        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87093        generateColumnNames(pParse, 0, pFirst->pEList);
87094      }
87095      iBreak = sqlite3VdbeMakeLabel(v);
87096      iCont = sqlite3VdbeMakeLabel(v);
87097      computeLimitRegisters(pParse, p, iBreak);
87098      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
87099      r1 = sqlite3GetTempReg(pParse);
87100      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
87101      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
87102      sqlite3ReleaseTempReg(pParse, r1);
87103      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
87104                      0, -1, &dest, iCont, iBreak);
87105      sqlite3VdbeResolveLabel(v, iCont);
87106      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
87107      sqlite3VdbeResolveLabel(v, iBreak);
87108      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
87109      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
87110      break;
87111    }
87112  }
87113
87114  /* Compute collating sequences used by
87115  ** temporary tables needed to implement the compound select.
87116  ** Attach the KeyInfo structure to all temporary tables.
87117  **
87118  ** This section is run by the right-most SELECT statement only.
87119  ** SELECT statements to the left always skip this part.  The right-most
87120  ** SELECT might also skip this part if it has no ORDER BY clause and
87121  ** no temp tables are required.
87122  */
87123  if( p->selFlags & SF_UsesEphemeral ){
87124    int i;                        /* Loop counter */
87125    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
87126    Select *pLoop;                /* For looping through SELECT statements */
87127    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
87128    int nCol;                     /* Number of columns in result set */
87129
87130    assert( p->pRightmost==p );
87131    nCol = p->pEList->nExpr;
87132    pKeyInfo = sqlite3DbMallocZero(db,
87133                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
87134    if( !pKeyInfo ){
87135      rc = SQLITE_NOMEM;
87136      goto multi_select_end;
87137    }
87138
87139    pKeyInfo->enc = ENC(db);
87140    pKeyInfo->nField = (u16)nCol;
87141
87142    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
87143      *apColl = multiSelectCollSeq(pParse, p, i);
87144      if( 0==*apColl ){
87145        *apColl = db->pDfltColl;
87146      }
87147    }
87148
87149    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
87150      for(i=0; i<2; i++){
87151        int addr = pLoop->addrOpenEphm[i];
87152        if( addr<0 ){
87153          /* If [0] is unused then [1] is also unused.  So we can
87154          ** always safely abort as soon as the first unused slot is found */
87155          assert( pLoop->addrOpenEphm[1]<0 );
87156          break;
87157        }
87158        sqlite3VdbeChangeP2(v, addr, nCol);
87159        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
87160        pLoop->addrOpenEphm[i] = -1;
87161      }
87162    }
87163    sqlite3DbFree(db, pKeyInfo);
87164  }
87165
87166multi_select_end:
87167  pDest->iMem = dest.iMem;
87168  pDest->nMem = dest.nMem;
87169  sqlite3SelectDelete(db, pDelete);
87170  return rc;
87171}
87172#endif /* SQLITE_OMIT_COMPOUND_SELECT */
87173
87174/*
87175** Code an output subroutine for a coroutine implementation of a
87176** SELECT statment.
87177**
87178** The data to be output is contained in pIn->iMem.  There are
87179** pIn->nMem columns to be output.  pDest is where the output should
87180** be sent.
87181**
87182** regReturn is the number of the register holding the subroutine
87183** return address.
87184**
87185** If regPrev>0 then it is a the first register in a vector that
87186** records the previous output.  mem[regPrev] is a flag that is false
87187** if there has been no previous output.  If regPrev>0 then code is
87188** generated to suppress duplicates.  pKeyInfo is used for comparing
87189** keys.
87190**
87191** If the LIMIT found in p->iLimit is reached, jump immediately to
87192** iBreak.
87193*/
87194static int generateOutputSubroutine(
87195  Parse *pParse,          /* Parsing context */
87196  Select *p,              /* The SELECT statement */
87197  SelectDest *pIn,        /* Coroutine supplying data */
87198  SelectDest *pDest,      /* Where to send the data */
87199  int regReturn,          /* The return address register */
87200  int regPrev,            /* Previous result register.  No uniqueness if 0 */
87201  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
87202  int p4type,             /* The p4 type for pKeyInfo */
87203  int iBreak              /* Jump here if we hit the LIMIT */
87204){
87205  Vdbe *v = pParse->pVdbe;
87206  int iContinue;
87207  int addr;
87208
87209  addr = sqlite3VdbeCurrentAddr(v);
87210  iContinue = sqlite3VdbeMakeLabel(v);
87211
87212  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
87213  */
87214  if( regPrev ){
87215    int j1, j2;
87216    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
87217    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
87218                              (char*)pKeyInfo, p4type);
87219    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
87220    sqlite3VdbeJumpHere(v, j1);
87221    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
87222    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
87223  }
87224  if( pParse->db->mallocFailed ) return 0;
87225
87226  /* Suppress the the first OFFSET entries if there is an OFFSET clause
87227  */
87228  codeOffset(v, p, iContinue);
87229
87230  switch( pDest->eDest ){
87231    /* Store the result as data using a unique key.
87232    */
87233    case SRT_Table:
87234    case SRT_EphemTab: {
87235      int r1 = sqlite3GetTempReg(pParse);
87236      int r2 = sqlite3GetTempReg(pParse);
87237      testcase( pDest->eDest==SRT_Table );
87238      testcase( pDest->eDest==SRT_EphemTab );
87239      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
87240      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
87241      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
87242      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87243      sqlite3ReleaseTempReg(pParse, r2);
87244      sqlite3ReleaseTempReg(pParse, r1);
87245      break;
87246    }
87247
87248#ifndef SQLITE_OMIT_SUBQUERY
87249    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
87250    ** then there should be a single item on the stack.  Write this
87251    ** item into the set table with bogus data.
87252    */
87253    case SRT_Set: {
87254      int r1;
87255      assert( pIn->nMem==1 );
87256      p->affinity =
87257         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
87258      r1 = sqlite3GetTempReg(pParse);
87259      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
87260      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
87261      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
87262      sqlite3ReleaseTempReg(pParse, r1);
87263      break;
87264    }
87265
87266#if 0  /* Never occurs on an ORDER BY query */
87267    /* If any row exist in the result set, record that fact and abort.
87268    */
87269    case SRT_Exists: {
87270      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
87271      /* The LIMIT clause will terminate the loop for us */
87272      break;
87273    }
87274#endif
87275
87276    /* If this is a scalar select that is part of an expression, then
87277    ** store the results in the appropriate memory cell and break out
87278    ** of the scan loop.
87279    */
87280    case SRT_Mem: {
87281      assert( pIn->nMem==1 );
87282      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
87283      /* The LIMIT clause will jump out of the loop for us */
87284      break;
87285    }
87286#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
87287
87288    /* The results are stored in a sequence of registers
87289    ** starting at pDest->iMem.  Then the co-routine yields.
87290    */
87291    case SRT_Coroutine: {
87292      if( pDest->iMem==0 ){
87293        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
87294        pDest->nMem = pIn->nMem;
87295      }
87296      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
87297      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87298      break;
87299    }
87300
87301    /* If none of the above, then the result destination must be
87302    ** SRT_Output.  This routine is never called with any other
87303    ** destination other than the ones handled above or SRT_Output.
87304    **
87305    ** For SRT_Output, results are stored in a sequence of registers.
87306    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
87307    ** return the next row of result.
87308    */
87309    default: {
87310      assert( pDest->eDest==SRT_Output );
87311      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
87312      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
87313      break;
87314    }
87315  }
87316
87317  /* Jump to the end of the loop if the LIMIT is reached.
87318  */
87319  if( p->iLimit ){
87320    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
87321  }
87322
87323  /* Generate the subroutine return
87324  */
87325  sqlite3VdbeResolveLabel(v, iContinue);
87326  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
87327
87328  return addr;
87329}
87330
87331/*
87332** Alternative compound select code generator for cases when there
87333** is an ORDER BY clause.
87334**
87335** We assume a query of the following form:
87336**
87337**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
87338**
87339** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
87340** is to code both <selectA> and <selectB> with the ORDER BY clause as
87341** co-routines.  Then run the co-routines in parallel and merge the results
87342** into the output.  In addition to the two coroutines (called selectA and
87343** selectB) there are 7 subroutines:
87344**
87345**    outA:    Move the output of the selectA coroutine into the output
87346**             of the compound query.
87347**
87348**    outB:    Move the output of the selectB coroutine into the output
87349**             of the compound query.  (Only generated for UNION and
87350**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
87351**             appears only in B.)
87352**
87353**    AltB:    Called when there is data from both coroutines and A<B.
87354**
87355**    AeqB:    Called when there is data from both coroutines and A==B.
87356**
87357**    AgtB:    Called when there is data from both coroutines and A>B.
87358**
87359**    EofA:    Called when data is exhausted from selectA.
87360**
87361**    EofB:    Called when data is exhausted from selectB.
87362**
87363** The implementation of the latter five subroutines depend on which
87364** <operator> is used:
87365**
87366**
87367**             UNION ALL         UNION            EXCEPT          INTERSECT
87368**          -------------  -----------------  --------------  -----------------
87369**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
87370**
87371**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
87372**
87373**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
87374**
87375**   EofA:   outB, nextB      outB, nextB          halt             halt
87376**
87377**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
87378**
87379** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
87380** causes an immediate jump to EofA and an EOF on B following nextB causes
87381** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
87382** following nextX causes a jump to the end of the select processing.
87383**
87384** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
87385** within the output subroutine.  The regPrev register set holds the previously
87386** output value.  A comparison is made against this value and the output
87387** is skipped if the next results would be the same as the previous.
87388**
87389** The implementation plan is to implement the two coroutines and seven
87390** subroutines first, then put the control logic at the bottom.  Like this:
87391**
87392**          goto Init
87393**     coA: coroutine for left query (A)
87394**     coB: coroutine for right query (B)
87395**    outA: output one row of A
87396**    outB: output one row of B (UNION and UNION ALL only)
87397**    EofA: ...
87398**    EofB: ...
87399**    AltB: ...
87400**    AeqB: ...
87401**    AgtB: ...
87402**    Init: initialize coroutine registers
87403**          yield coA
87404**          if eof(A) goto EofA
87405**          yield coB
87406**          if eof(B) goto EofB
87407**    Cmpr: Compare A, B
87408**          Jump AltB, AeqB, AgtB
87409**     End: ...
87410**
87411** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
87412** actually called using Gosub and they do not Return.  EofA and EofB loop
87413** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
87414** and AgtB jump to either L2 or to one of EofA or EofB.
87415*/
87416#ifndef SQLITE_OMIT_COMPOUND_SELECT
87417static int multiSelectOrderBy(
87418  Parse *pParse,        /* Parsing context */
87419  Select *p,            /* The right-most of SELECTs to be coded */
87420  SelectDest *pDest     /* What to do with query results */
87421){
87422  int i, j;             /* Loop counters */
87423  Select *pPrior;       /* Another SELECT immediately to our left */
87424  Vdbe *v;              /* Generate code to this VDBE */
87425  SelectDest destA;     /* Destination for coroutine A */
87426  SelectDest destB;     /* Destination for coroutine B */
87427  int regAddrA;         /* Address register for select-A coroutine */
87428  int regEofA;          /* Flag to indicate when select-A is complete */
87429  int regAddrB;         /* Address register for select-B coroutine */
87430  int regEofB;          /* Flag to indicate when select-B is complete */
87431  int addrSelectA;      /* Address of the select-A coroutine */
87432  int addrSelectB;      /* Address of the select-B coroutine */
87433  int regOutA;          /* Address register for the output-A subroutine */
87434  int regOutB;          /* Address register for the output-B subroutine */
87435  int addrOutA;         /* Address of the output-A subroutine */
87436  int addrOutB = 0;     /* Address of the output-B subroutine */
87437  int addrEofA;         /* Address of the select-A-exhausted subroutine */
87438  int addrEofB;         /* Address of the select-B-exhausted subroutine */
87439  int addrAltB;         /* Address of the A<B subroutine */
87440  int addrAeqB;         /* Address of the A==B subroutine */
87441  int addrAgtB;         /* Address of the A>B subroutine */
87442  int regLimitA;        /* Limit register for select-A */
87443  int regLimitB;        /* Limit register for select-A */
87444  int regPrev;          /* A range of registers to hold previous output */
87445  int savedLimit;       /* Saved value of p->iLimit */
87446  int savedOffset;      /* Saved value of p->iOffset */
87447  int labelCmpr;        /* Label for the start of the merge algorithm */
87448  int labelEnd;         /* Label for the end of the overall SELECT stmt */
87449  int j1;               /* Jump instructions that get retargetted */
87450  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
87451  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
87452  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
87453  sqlite3 *db;          /* Database connection */
87454  ExprList *pOrderBy;   /* The ORDER BY clause */
87455  int nOrderBy;         /* Number of terms in the ORDER BY clause */
87456  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
87457
87458  assert( p->pOrderBy!=0 );
87459  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
87460  db = pParse->db;
87461  v = pParse->pVdbe;
87462  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
87463  labelEnd = sqlite3VdbeMakeLabel(v);
87464  labelCmpr = sqlite3VdbeMakeLabel(v);
87465
87466
87467  /* Patch up the ORDER BY clause
87468  */
87469  op = p->op;
87470  pPrior = p->pPrior;
87471  assert( pPrior->pOrderBy==0 );
87472  pOrderBy = p->pOrderBy;
87473  assert( pOrderBy );
87474  nOrderBy = pOrderBy->nExpr;
87475
87476  /* For operators other than UNION ALL we have to make sure that
87477  ** the ORDER BY clause covers every term of the result set.  Add
87478  ** terms to the ORDER BY clause as necessary.
87479  */
87480  if( op!=TK_ALL ){
87481    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
87482      struct ExprList_item *pItem;
87483      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
87484        assert( pItem->iCol>0 );
87485        if( pItem->iCol==i ) break;
87486      }
87487      if( j==nOrderBy ){
87488        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
87489        if( pNew==0 ) return SQLITE_NOMEM;
87490        pNew->flags |= EP_IntValue;
87491        pNew->u.iValue = i;
87492        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
87493        pOrderBy->a[nOrderBy++].iCol = (u16)i;
87494      }
87495    }
87496  }
87497
87498  /* Compute the comparison permutation and keyinfo that is used with
87499  ** the permutation used to determine if the next
87500  ** row of results comes from selectA or selectB.  Also add explicit
87501  ** collations to the ORDER BY clause terms so that when the subqueries
87502  ** to the right and the left are evaluated, they use the correct
87503  ** collation.
87504  */
87505  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
87506  if( aPermute ){
87507    struct ExprList_item *pItem;
87508    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
87509      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
87510      aPermute[i] = pItem->iCol - 1;
87511    }
87512    pKeyMerge =
87513      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
87514    if( pKeyMerge ){
87515      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
87516      pKeyMerge->nField = (u16)nOrderBy;
87517      pKeyMerge->enc = ENC(db);
87518      for(i=0; i<nOrderBy; i++){
87519        CollSeq *pColl;
87520        Expr *pTerm = pOrderBy->a[i].pExpr;
87521        if( pTerm->flags & EP_ExpCollate ){
87522          pColl = pTerm->pColl;
87523        }else{
87524          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
87525          pTerm->flags |= EP_ExpCollate;
87526          pTerm->pColl = pColl;
87527        }
87528        pKeyMerge->aColl[i] = pColl;
87529        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
87530      }
87531    }
87532  }else{
87533    pKeyMerge = 0;
87534  }
87535
87536  /* Reattach the ORDER BY clause to the query.
87537  */
87538  p->pOrderBy = pOrderBy;
87539  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
87540
87541  /* Allocate a range of temporary registers and the KeyInfo needed
87542  ** for the logic that removes duplicate result rows when the
87543  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
87544  */
87545  if( op==TK_ALL ){
87546    regPrev = 0;
87547  }else{
87548    int nExpr = p->pEList->nExpr;
87549    assert( nOrderBy>=nExpr || db->mallocFailed );
87550    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
87551    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
87552    pKeyDup = sqlite3DbMallocZero(db,
87553                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
87554    if( pKeyDup ){
87555      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
87556      pKeyDup->nField = (u16)nExpr;
87557      pKeyDup->enc = ENC(db);
87558      for(i=0; i<nExpr; i++){
87559        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
87560        pKeyDup->aSortOrder[i] = 0;
87561      }
87562    }
87563  }
87564
87565  /* Separate the left and the right query from one another
87566  */
87567  p->pPrior = 0;
87568  pPrior->pRightmost = 0;
87569  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
87570  if( pPrior->pPrior==0 ){
87571    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
87572  }
87573
87574  /* Compute the limit registers */
87575  computeLimitRegisters(pParse, p, labelEnd);
87576  if( p->iLimit && op==TK_ALL ){
87577    regLimitA = ++pParse->nMem;
87578    regLimitB = ++pParse->nMem;
87579    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
87580                                  regLimitA);
87581    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
87582  }else{
87583    regLimitA = regLimitB = 0;
87584  }
87585  sqlite3ExprDelete(db, p->pLimit);
87586  p->pLimit = 0;
87587  sqlite3ExprDelete(db, p->pOffset);
87588  p->pOffset = 0;
87589
87590  regAddrA = ++pParse->nMem;
87591  regEofA = ++pParse->nMem;
87592  regAddrB = ++pParse->nMem;
87593  regEofB = ++pParse->nMem;
87594  regOutA = ++pParse->nMem;
87595  regOutB = ++pParse->nMem;
87596  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
87597  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
87598
87599  /* Jump past the various subroutines and coroutines to the main
87600  ** merge loop
87601  */
87602  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
87603  addrSelectA = sqlite3VdbeCurrentAddr(v);
87604
87605
87606  /* Generate a coroutine to evaluate the SELECT statement to the
87607  ** left of the compound operator - the "A" select.
87608  */
87609  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
87610  pPrior->iLimit = regLimitA;
87611  sqlite3Select(pParse, pPrior, &destA);
87612  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
87613  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87614  VdbeNoopComment((v, "End coroutine for left SELECT"));
87615
87616  /* Generate a coroutine to evaluate the SELECT statement on
87617  ** the right - the "B" select
87618  */
87619  addrSelectB = sqlite3VdbeCurrentAddr(v);
87620  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
87621  savedLimit = p->iLimit;
87622  savedOffset = p->iOffset;
87623  p->iLimit = regLimitB;
87624  p->iOffset = 0;
87625  sqlite3Select(pParse, p, &destB);
87626  p->iLimit = savedLimit;
87627  p->iOffset = savedOffset;
87628  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
87629  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87630  VdbeNoopComment((v, "End coroutine for right SELECT"));
87631
87632  /* Generate a subroutine that outputs the current row of the A
87633  ** select as the next output row of the compound select.
87634  */
87635  VdbeNoopComment((v, "Output routine for A"));
87636  addrOutA = generateOutputSubroutine(pParse,
87637                 p, &destA, pDest, regOutA,
87638                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
87639
87640  /* Generate a subroutine that outputs the current row of the B
87641  ** select as the next output row of the compound select.
87642  */
87643  if( op==TK_ALL || op==TK_UNION ){
87644    VdbeNoopComment((v, "Output routine for B"));
87645    addrOutB = generateOutputSubroutine(pParse,
87646                 p, &destB, pDest, regOutB,
87647                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
87648  }
87649
87650  /* Generate a subroutine to run when the results from select A
87651  ** are exhausted and only data in select B remains.
87652  */
87653  VdbeNoopComment((v, "eof-A subroutine"));
87654  if( op==TK_EXCEPT || op==TK_INTERSECT ){
87655    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
87656  }else{
87657    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
87658    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
87659    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87660    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
87661  }
87662
87663  /* Generate a subroutine to run when the results from select B
87664  ** are exhausted and only data in select A remains.
87665  */
87666  if( op==TK_INTERSECT ){
87667    addrEofB = addrEofA;
87668  }else{
87669    VdbeNoopComment((v, "eof-B subroutine"));
87670    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
87671    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
87672    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87673    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
87674  }
87675
87676  /* Generate code to handle the case of A<B
87677  */
87678  VdbeNoopComment((v, "A-lt-B subroutine"));
87679  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
87680  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87681  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
87682  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
87683
87684  /* Generate code to handle the case of A==B
87685  */
87686  if( op==TK_ALL ){
87687    addrAeqB = addrAltB;
87688  }else if( op==TK_INTERSECT ){
87689    addrAeqB = addrAltB;
87690    addrAltB++;
87691  }else{
87692    VdbeNoopComment((v, "A-eq-B subroutine"));
87693    addrAeqB =
87694    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87695    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
87696    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
87697  }
87698
87699  /* Generate code to handle the case of A>B
87700  */
87701  VdbeNoopComment((v, "A-gt-B subroutine"));
87702  addrAgtB = sqlite3VdbeCurrentAddr(v);
87703  if( op==TK_ALL || op==TK_UNION ){
87704    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
87705  }
87706  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87707  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
87708  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
87709
87710  /* This code runs once to initialize everything.
87711  */
87712  sqlite3VdbeJumpHere(v, j1);
87713  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
87714  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
87715  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
87716  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
87717  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
87718  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
87719
87720  /* Implement the main merge loop
87721  */
87722  sqlite3VdbeResolveLabel(v, labelCmpr);
87723  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
87724  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
87725                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
87726  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
87727
87728  /* Release temporary registers
87729  */
87730  if( regPrev ){
87731    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
87732  }
87733
87734  /* Jump to the this point in order to terminate the query.
87735  */
87736  sqlite3VdbeResolveLabel(v, labelEnd);
87737
87738  /* Set the number of output columns
87739  */
87740  if( pDest->eDest==SRT_Output ){
87741    Select *pFirst = pPrior;
87742    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87743    generateColumnNames(pParse, 0, pFirst->pEList);
87744  }
87745
87746  /* Reassembly the compound query so that it will be freed correctly
87747  ** by the calling function */
87748  if( p->pPrior ){
87749    sqlite3SelectDelete(db, p->pPrior);
87750  }
87751  p->pPrior = pPrior;
87752
87753  /*** TBD:  Insert subroutine calls to close cursors on incomplete
87754  **** subqueries ****/
87755  return SQLITE_OK;
87756}
87757#endif
87758
87759#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
87760/* Forward Declarations */
87761static void substExprList(sqlite3*, ExprList*, int, ExprList*);
87762static void substSelect(sqlite3*, Select *, int, ExprList *);
87763
87764/*
87765** Scan through the expression pExpr.  Replace every reference to
87766** a column in table number iTable with a copy of the iColumn-th
87767** entry in pEList.  (But leave references to the ROWID column
87768** unchanged.)
87769**
87770** This routine is part of the flattening procedure.  A subquery
87771** whose result set is defined by pEList appears as entry in the
87772** FROM clause of a SELECT such that the VDBE cursor assigned to that
87773** FORM clause entry is iTable.  This routine make the necessary
87774** changes to pExpr so that it refers directly to the source table
87775** of the subquery rather the result set of the subquery.
87776*/
87777static Expr *substExpr(
87778  sqlite3 *db,        /* Report malloc errors to this connection */
87779  Expr *pExpr,        /* Expr in which substitution occurs */
87780  int iTable,         /* Table to be substituted */
87781  ExprList *pEList    /* Substitute expressions */
87782){
87783  if( pExpr==0 ) return 0;
87784  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
87785    if( pExpr->iColumn<0 ){
87786      pExpr->op = TK_NULL;
87787    }else{
87788      Expr *pNew;
87789      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
87790      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
87791      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
87792      if( pNew && pExpr->pColl ){
87793        pNew->pColl = pExpr->pColl;
87794      }
87795      sqlite3ExprDelete(db, pExpr);
87796      pExpr = pNew;
87797    }
87798  }else{
87799    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
87800    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
87801    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87802      substSelect(db, pExpr->x.pSelect, iTable, pEList);
87803    }else{
87804      substExprList(db, pExpr->x.pList, iTable, pEList);
87805    }
87806  }
87807  return pExpr;
87808}
87809static void substExprList(
87810  sqlite3 *db,         /* Report malloc errors here */
87811  ExprList *pList,     /* List to scan and in which to make substitutes */
87812  int iTable,          /* Table to be substituted */
87813  ExprList *pEList     /* Substitute values */
87814){
87815  int i;
87816  if( pList==0 ) return;
87817  for(i=0; i<pList->nExpr; i++){
87818    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
87819  }
87820}
87821static void substSelect(
87822  sqlite3 *db,         /* Report malloc errors here */
87823  Select *p,           /* SELECT statement in which to make substitutions */
87824  int iTable,          /* Table to be replaced */
87825  ExprList *pEList     /* Substitute values */
87826){
87827  SrcList *pSrc;
87828  struct SrcList_item *pItem;
87829  int i;
87830  if( !p ) return;
87831  substExprList(db, p->pEList, iTable, pEList);
87832  substExprList(db, p->pGroupBy, iTable, pEList);
87833  substExprList(db, p->pOrderBy, iTable, pEList);
87834  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
87835  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
87836  substSelect(db, p->pPrior, iTable, pEList);
87837  pSrc = p->pSrc;
87838  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
87839  if( ALWAYS(pSrc) ){
87840    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
87841      substSelect(db, pItem->pSelect, iTable, pEList);
87842    }
87843  }
87844}
87845#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
87846
87847#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
87848/*
87849** This routine attempts to flatten subqueries in order to speed
87850** execution.  It returns 1 if it makes changes and 0 if no flattening
87851** occurs.
87852**
87853** To understand the concept of flattening, consider the following
87854** query:
87855**
87856**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
87857**
87858** The default way of implementing this query is to execute the
87859** subquery first and store the results in a temporary table, then
87860** run the outer query on that temporary table.  This requires two
87861** passes over the data.  Furthermore, because the temporary table
87862** has no indices, the WHERE clause on the outer query cannot be
87863** optimized.
87864**
87865** This routine attempts to rewrite queries such as the above into
87866** a single flat select, like this:
87867**
87868**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
87869**
87870** The code generated for this simpification gives the same result
87871** but only has to scan the data once.  And because indices might
87872** exist on the table t1, a complete scan of the data might be
87873** avoided.
87874**
87875** Flattening is only attempted if all of the following are true:
87876**
87877**   (1)  The subquery and the outer query do not both use aggregates.
87878**
87879**   (2)  The subquery is not an aggregate or the outer query is not a join.
87880**
87881**   (3)  The subquery is not the right operand of a left outer join
87882**        (Originally ticket #306.  Strenghtened by ticket #3300)
87883**
87884**   (4)  The subquery is not DISTINCT or the outer query is not a join.
87885**
87886**   (5)  The subquery is not DISTINCT or the outer query does not use
87887**        aggregates.
87888**
87889**   (6)  The subquery does not use aggregates or the outer query is not
87890**        DISTINCT.
87891**
87892**   (7)  The subquery has a FROM clause.
87893**
87894**   (8)  The subquery does not use LIMIT or the outer query is not a join.
87895**
87896**   (9)  The subquery does not use LIMIT or the outer query does not use
87897**        aggregates.
87898**
87899**  (10)  The subquery does not use aggregates or the outer query does not
87900**        use LIMIT.
87901**
87902**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
87903**
87904**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
87905**        a separate restriction deriving from ticket #350.
87906**
87907**  (13)  The subquery and outer query do not both use LIMIT
87908**
87909**  (14)  The subquery does not use OFFSET
87910**
87911**  (15)  The outer query is not part of a compound select or the
87912**        subquery does not have a LIMIT clause.
87913**        (See ticket #2339 and ticket [02a8e81d44]).
87914**
87915**  (16)  The outer query is not an aggregate or the subquery does
87916**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
87917**        until we introduced the group_concat() function.
87918**
87919**  (17)  The sub-query is not a compound select, or it is a UNION ALL
87920**        compound clause made up entirely of non-aggregate queries, and
87921**        the parent query:
87922**
87923**          * is not itself part of a compound select,
87924**          * is not an aggregate or DISTINCT query, and
87925**          * has no other tables or sub-selects in the FROM clause.
87926**
87927**        The parent and sub-query may contain WHERE clauses. Subject to
87928**        rules (11), (13) and (14), they may also contain ORDER BY,
87929**        LIMIT and OFFSET clauses.
87930**
87931**  (18)  If the sub-query is a compound select, then all terms of the
87932**        ORDER by clause of the parent must be simple references to
87933**        columns of the sub-query.
87934**
87935**  (19)  The subquery does not use LIMIT or the outer query does not
87936**        have a WHERE clause.
87937**
87938**  (20)  If the sub-query is a compound select, then it must not use
87939**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
87940**        somewhat by saying that the terms of the ORDER BY clause must
87941**        appear as unmodified result columns in the outer query.  But
87942**        have other optimizations in mind to deal with that case.
87943**
87944** In this routine, the "p" parameter is a pointer to the outer query.
87945** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
87946** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
87947**
87948** If flattening is not attempted, this routine is a no-op and returns 0.
87949** If flattening is attempted this routine returns 1.
87950**
87951** All of the expression analysis must occur on both the outer query and
87952** the subquery before this routine runs.
87953*/
87954static int flattenSubquery(
87955  Parse *pParse,       /* Parsing context */
87956  Select *p,           /* The parent or outer SELECT statement */
87957  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
87958  int isAgg,           /* True if outer SELECT uses aggregate functions */
87959  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
87960){
87961  const char *zSavedAuthContext = pParse->zAuthContext;
87962  Select *pParent;
87963  Select *pSub;       /* The inner query or "subquery" */
87964  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
87965  SrcList *pSrc;      /* The FROM clause of the outer query */
87966  SrcList *pSubSrc;   /* The FROM clause of the subquery */
87967  ExprList *pList;    /* The result set of the outer query */
87968  int iParent;        /* VDBE cursor number of the pSub result set temp table */
87969  int i;              /* Loop counter */
87970  Expr *pWhere;                    /* The WHERE clause */
87971  struct SrcList_item *pSubitem;   /* The subquery */
87972  sqlite3 *db = pParse->db;
87973
87974  /* Check to see if flattening is permitted.  Return 0 if not.
87975  */
87976  assert( p!=0 );
87977  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
87978  if( db->flags & SQLITE_QueryFlattener ) return 0;
87979  pSrc = p->pSrc;
87980  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
87981  pSubitem = &pSrc->a[iFrom];
87982  iParent = pSubitem->iCursor;
87983  pSub = pSubitem->pSelect;
87984  assert( pSub!=0 );
87985  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
87986  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
87987  pSubSrc = pSub->pSrc;
87988  assert( pSubSrc );
87989  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
87990  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
87991  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
87992  ** became arbitrary expressions, we were forced to add restrictions (13)
87993  ** and (14). */
87994  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
87995  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
87996  if( p->pRightmost && pSub->pLimit ){
87997    return 0;                                            /* Restriction (15) */
87998  }
87999  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
88000  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
88001         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
88002     return 0;
88003  }
88004  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
88005     return 0;         /* Restriction (6)  */
88006  }
88007  if( p->pOrderBy && pSub->pOrderBy ){
88008     return 0;                                           /* Restriction (11) */
88009  }
88010  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
88011  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
88012
88013  /* OBSOLETE COMMENT 1:
88014  ** Restriction 3:  If the subquery is a join, make sure the subquery is
88015  ** not used as the right operand of an outer join.  Examples of why this
88016  ** is not allowed:
88017  **
88018  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
88019  **
88020  ** If we flatten the above, we would get
88021  **
88022  **         (t1 LEFT OUTER JOIN t2) JOIN t3
88023  **
88024  ** which is not at all the same thing.
88025  **
88026  ** OBSOLETE COMMENT 2:
88027  ** Restriction 12:  If the subquery is the right operand of a left outer
88028  ** join, make sure the subquery has no WHERE clause.
88029  ** An examples of why this is not allowed:
88030  **
88031  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
88032  **
88033  ** If we flatten the above, we would get
88034  **
88035  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
88036  **
88037  ** But the t2.x>0 test will always fail on a NULL row of t2, which
88038  ** effectively converts the OUTER JOIN into an INNER JOIN.
88039  **
88040  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
88041  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
88042  ** is fraught with danger.  Best to avoid the whole thing.  If the
88043  ** subquery is the right term of a LEFT JOIN, then do not flatten.
88044  */
88045  if( (pSubitem->jointype & JT_OUTER)!=0 ){
88046    return 0;
88047  }
88048
88049  /* Restriction 17: If the sub-query is a compound SELECT, then it must
88050  ** use only the UNION ALL operator. And none of the simple select queries
88051  ** that make up the compound SELECT are allowed to be aggregate or distinct
88052  ** queries.
88053  */
88054  if( pSub->pPrior ){
88055    if( pSub->pOrderBy ){
88056      return 0;  /* Restriction 20 */
88057    }
88058    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
88059      return 0;
88060    }
88061    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
88062      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
88063      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
88064      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
88065       || (pSub1->pPrior && pSub1->op!=TK_ALL)
88066       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
88067      ){
88068        return 0;
88069      }
88070    }
88071
88072    /* Restriction 18. */
88073    if( p->pOrderBy ){
88074      int ii;
88075      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
88076        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
88077      }
88078    }
88079  }
88080
88081  /***** If we reach this point, flattening is permitted. *****/
88082
88083  /* Authorize the subquery */
88084  pParse->zAuthContext = pSubitem->zName;
88085  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
88086  pParse->zAuthContext = zSavedAuthContext;
88087
88088  /* If the sub-query is a compound SELECT statement, then (by restrictions
88089  ** 17 and 18 above) it must be a UNION ALL and the parent query must
88090  ** be of the form:
88091  **
88092  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
88093  **
88094  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
88095  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
88096  ** OFFSET clauses and joins them to the left-hand-side of the original
88097  ** using UNION ALL operators. In this case N is the number of simple
88098  ** select statements in the compound sub-query.
88099  **
88100  ** Example:
88101  **
88102  **     SELECT a+1 FROM (
88103  **        SELECT x FROM tab
88104  **        UNION ALL
88105  **        SELECT y FROM tab
88106  **        UNION ALL
88107  **        SELECT abs(z*2) FROM tab2
88108  **     ) WHERE a!=5 ORDER BY 1
88109  **
88110  ** Transformed into:
88111  **
88112  **     SELECT x+1 FROM tab WHERE x+1!=5
88113  **     UNION ALL
88114  **     SELECT y+1 FROM tab WHERE y+1!=5
88115  **     UNION ALL
88116  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
88117  **     ORDER BY 1
88118  **
88119  ** We call this the "compound-subquery flattening".
88120  */
88121  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
88122    Select *pNew;
88123    ExprList *pOrderBy = p->pOrderBy;
88124    Expr *pLimit = p->pLimit;
88125    Select *pPrior = p->pPrior;
88126    p->pOrderBy = 0;
88127    p->pSrc = 0;
88128    p->pPrior = 0;
88129    p->pLimit = 0;
88130    pNew = sqlite3SelectDup(db, p, 0);
88131    p->pLimit = pLimit;
88132    p->pOrderBy = pOrderBy;
88133    p->pSrc = pSrc;
88134    p->op = TK_ALL;
88135    p->pRightmost = 0;
88136    if( pNew==0 ){
88137      pNew = pPrior;
88138    }else{
88139      pNew->pPrior = pPrior;
88140      pNew->pRightmost = 0;
88141    }
88142    p->pPrior = pNew;
88143    if( db->mallocFailed ) return 1;
88144  }
88145
88146  /* Begin flattening the iFrom-th entry of the FROM clause
88147  ** in the outer query.
88148  */
88149  pSub = pSub1 = pSubitem->pSelect;
88150
88151  /* Delete the transient table structure associated with the
88152  ** subquery
88153  */
88154  sqlite3DbFree(db, pSubitem->zDatabase);
88155  sqlite3DbFree(db, pSubitem->zName);
88156  sqlite3DbFree(db, pSubitem->zAlias);
88157  pSubitem->zDatabase = 0;
88158  pSubitem->zName = 0;
88159  pSubitem->zAlias = 0;
88160  pSubitem->pSelect = 0;
88161
88162  /* Defer deleting the Table object associated with the
88163  ** subquery until code generation is
88164  ** complete, since there may still exist Expr.pTab entries that
88165  ** refer to the subquery even after flattening.  Ticket #3346.
88166  **
88167  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
88168  */
88169  if( ALWAYS(pSubitem->pTab!=0) ){
88170    Table *pTabToDel = pSubitem->pTab;
88171    if( pTabToDel->nRef==1 ){
88172      Parse *pToplevel = sqlite3ParseToplevel(pParse);
88173      pTabToDel->pNextZombie = pToplevel->pZombieTab;
88174      pToplevel->pZombieTab = pTabToDel;
88175    }else{
88176      pTabToDel->nRef--;
88177    }
88178    pSubitem->pTab = 0;
88179  }
88180
88181  /* The following loop runs once for each term in a compound-subquery
88182  ** flattening (as described above).  If we are doing a different kind
88183  ** of flattening - a flattening other than a compound-subquery flattening -
88184  ** then this loop only runs once.
88185  **
88186  ** This loop moves all of the FROM elements of the subquery into the
88187  ** the FROM clause of the outer query.  Before doing this, remember
88188  ** the cursor number for the original outer query FROM element in
88189  ** iParent.  The iParent cursor will never be used.  Subsequent code
88190  ** will scan expressions looking for iParent references and replace
88191  ** those references with expressions that resolve to the subquery FROM
88192  ** elements we are now copying in.
88193  */
88194  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
88195    int nSubSrc;
88196    u8 jointype = 0;
88197    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
88198    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
88199    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
88200
88201    if( pSrc ){
88202      assert( pParent==p );  /* First time through the loop */
88203      jointype = pSubitem->jointype;
88204    }else{
88205      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
88206      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88207      if( pSrc==0 ){
88208        assert( db->mallocFailed );
88209        break;
88210      }
88211    }
88212
88213    /* The subquery uses a single slot of the FROM clause of the outer
88214    ** query.  If the subquery has more than one element in its FROM clause,
88215    ** then expand the outer query to make space for it to hold all elements
88216    ** of the subquery.
88217    **
88218    ** Example:
88219    **
88220    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
88221    **
88222    ** The outer query has 3 slots in its FROM clause.  One slot of the
88223    ** outer query (the middle slot) is used by the subquery.  The next
88224    ** block of code will expand the out query to 4 slots.  The middle
88225    ** slot is expanded to two slots in order to make space for the
88226    ** two elements in the FROM clause of the subquery.
88227    */
88228    if( nSubSrc>1 ){
88229      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
88230      if( db->mallocFailed ){
88231        break;
88232      }
88233    }
88234
88235    /* Transfer the FROM clause terms from the subquery into the
88236    ** outer query.
88237    */
88238    for(i=0; i<nSubSrc; i++){
88239      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
88240      pSrc->a[i+iFrom] = pSubSrc->a[i];
88241      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
88242    }
88243    pSrc->a[iFrom].jointype = jointype;
88244
88245    /* Now begin substituting subquery result set expressions for
88246    ** references to the iParent in the outer query.
88247    **
88248    ** Example:
88249    **
88250    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
88251    **   \                     \_____________ subquery __________/          /
88252    **    \_____________________ outer query ______________________________/
88253    **
88254    ** We look at every expression in the outer query and every place we see
88255    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
88256    */
88257    pList = pParent->pEList;
88258    for(i=0; i<pList->nExpr; i++){
88259      if( pList->a[i].zName==0 ){
88260        const char *zSpan = pList->a[i].zSpan;
88261        if( ALWAYS(zSpan) ){
88262          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
88263        }
88264      }
88265    }
88266    substExprList(db, pParent->pEList, iParent, pSub->pEList);
88267    if( isAgg ){
88268      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
88269      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88270    }
88271    if( pSub->pOrderBy ){
88272      assert( pParent->pOrderBy==0 );
88273      pParent->pOrderBy = pSub->pOrderBy;
88274      pSub->pOrderBy = 0;
88275    }else if( pParent->pOrderBy ){
88276      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
88277    }
88278    if( pSub->pWhere ){
88279      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
88280    }else{
88281      pWhere = 0;
88282    }
88283    if( subqueryIsAgg ){
88284      assert( pParent->pHaving==0 );
88285      pParent->pHaving = pParent->pWhere;
88286      pParent->pWhere = pWhere;
88287      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88288      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
88289                                  sqlite3ExprDup(db, pSub->pHaving, 0));
88290      assert( pParent->pGroupBy==0 );
88291      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
88292    }else{
88293      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
88294      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
88295    }
88296
88297    /* The flattened query is distinct if either the inner or the
88298    ** outer query is distinct.
88299    */
88300    pParent->selFlags |= pSub->selFlags & SF_Distinct;
88301
88302    /*
88303    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
88304    **
88305    ** One is tempted to try to add a and b to combine the limits.  But this
88306    ** does not work if either limit is negative.
88307    */
88308    if( pSub->pLimit ){
88309      pParent->pLimit = pSub->pLimit;
88310      pSub->pLimit = 0;
88311    }
88312  }
88313
88314  /* Finially, delete what is left of the subquery and return
88315  ** success.
88316  */
88317  sqlite3SelectDelete(db, pSub1);
88318
88319  return 1;
88320}
88321#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
88322
88323/*
88324** Analyze the SELECT statement passed as an argument to see if it
88325** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
88326** it is, or 0 otherwise. At present, a query is considered to be
88327** a min()/max() query if:
88328**
88329**   1. There is a single object in the FROM clause.
88330**
88331**   2. There is a single expression in the result set, and it is
88332**      either min(x) or max(x), where x is a column reference.
88333*/
88334static u8 minMaxQuery(Select *p){
88335  Expr *pExpr;
88336  ExprList *pEList = p->pEList;
88337
88338  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
88339  pExpr = pEList->a[0].pExpr;
88340  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88341  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
88342  pEList = pExpr->x.pList;
88343  if( pEList==0 || pEList->nExpr!=1 ) return 0;
88344  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
88345  assert( !ExprHasProperty(pExpr, EP_IntValue) );
88346  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
88347    return WHERE_ORDERBY_MIN;
88348  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
88349    return WHERE_ORDERBY_MAX;
88350  }
88351  return WHERE_ORDERBY_NORMAL;
88352}
88353
88354/*
88355** The select statement passed as the first argument is an aggregate query.
88356** The second argment is the associated aggregate-info object. This
88357** function tests if the SELECT is of the form:
88358**
88359**   SELECT count(*) FROM <tbl>
88360**
88361** where table is a database table, not a sub-select or view. If the query
88362** does match this pattern, then a pointer to the Table object representing
88363** <tbl> is returned. Otherwise, 0 is returned.
88364*/
88365static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
88366  Table *pTab;
88367  Expr *pExpr;
88368
88369  assert( !p->pGroupBy );
88370
88371  if( p->pWhere || p->pEList->nExpr!=1
88372   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
88373  ){
88374    return 0;
88375  }
88376  pTab = p->pSrc->a[0].pTab;
88377  pExpr = p->pEList->a[0].pExpr;
88378  assert( pTab && !pTab->pSelect && pExpr );
88379
88380  if( IsVirtual(pTab) ) return 0;
88381  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88382  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
88383  if( pExpr->flags&EP_Distinct ) return 0;
88384
88385  return pTab;
88386}
88387
88388/*
88389** If the source-list item passed as an argument was augmented with an
88390** INDEXED BY clause, then try to locate the specified index. If there
88391** was such a clause and the named index cannot be found, return
88392** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
88393** pFrom->pIndex and return SQLITE_OK.
88394*/
88395SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
88396  if( pFrom->pTab && pFrom->zIndex ){
88397    Table *pTab = pFrom->pTab;
88398    char *zIndex = pFrom->zIndex;
88399    Index *pIdx;
88400    for(pIdx=pTab->pIndex;
88401        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
88402        pIdx=pIdx->pNext
88403    );
88404    if( !pIdx ){
88405      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
88406      pParse->checkSchema = 1;
88407      return SQLITE_ERROR;
88408    }
88409    pFrom->pIndex = pIdx;
88410  }
88411  return SQLITE_OK;
88412}
88413
88414/*
88415** This routine is a Walker callback for "expanding" a SELECT statement.
88416** "Expanding" means to do the following:
88417**
88418**    (1)  Make sure VDBE cursor numbers have been assigned to every
88419**         element of the FROM clause.
88420**
88421**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
88422**         defines FROM clause.  When views appear in the FROM clause,
88423**         fill pTabList->a[].pSelect with a copy of the SELECT statement
88424**         that implements the view.  A copy is made of the view's SELECT
88425**         statement so that we can freely modify or delete that statement
88426**         without worrying about messing up the presistent representation
88427**         of the view.
88428**
88429**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
88430**         on joins and the ON and USING clause of joins.
88431**
88432**    (4)  Scan the list of columns in the result set (pEList) looking
88433**         for instances of the "*" operator or the TABLE.* operator.
88434**         If found, expand each "*" to be every column in every table
88435**         and TABLE.* to be every column in TABLE.
88436**
88437*/
88438static int selectExpander(Walker *pWalker, Select *p){
88439  Parse *pParse = pWalker->pParse;
88440  int i, j, k;
88441  SrcList *pTabList;
88442  ExprList *pEList;
88443  struct SrcList_item *pFrom;
88444  sqlite3 *db = pParse->db;
88445
88446  if( db->mallocFailed  ){
88447    return WRC_Abort;
88448  }
88449  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
88450    return WRC_Prune;
88451  }
88452  p->selFlags |= SF_Expanded;
88453  pTabList = p->pSrc;
88454  pEList = p->pEList;
88455
88456  /* Make sure cursor numbers have been assigned to all entries in
88457  ** the FROM clause of the SELECT statement.
88458  */
88459  sqlite3SrcListAssignCursors(pParse, pTabList);
88460
88461  /* Look up every table named in the FROM clause of the select.  If
88462  ** an entry of the FROM clause is a subquery instead of a table or view,
88463  ** then create a transient table structure to describe the subquery.
88464  */
88465  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88466    Table *pTab;
88467    if( pFrom->pTab!=0 ){
88468      /* This statement has already been prepared.  There is no need
88469      ** to go further. */
88470      assert( i==0 );
88471      return WRC_Prune;
88472    }
88473    if( pFrom->zName==0 ){
88474#ifndef SQLITE_OMIT_SUBQUERY
88475      Select *pSel = pFrom->pSelect;
88476      /* A sub-query in the FROM clause of a SELECT */
88477      assert( pSel!=0 );
88478      assert( pFrom->pTab==0 );
88479      sqlite3WalkSelect(pWalker, pSel);
88480      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
88481      if( pTab==0 ) return WRC_Abort;
88482      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
88483      pTab->nRef = 1;
88484      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
88485      while( pSel->pPrior ){ pSel = pSel->pPrior; }
88486      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
88487      pTab->iPKey = -1;
88488      pTab->tabFlags |= TF_Ephemeral;
88489#endif
88490    }else{
88491      /* An ordinary table or view name in the FROM clause */
88492      assert( pFrom->pTab==0 );
88493      pFrom->pTab = pTab =
88494        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
88495      if( pTab==0 ) return WRC_Abort;
88496      pTab->nRef++;
88497#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
88498      if( pTab->pSelect || IsVirtual(pTab) ){
88499        /* We reach here if the named table is a really a view */
88500        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
88501        assert( pFrom->pSelect==0 );
88502        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
88503        sqlite3WalkSelect(pWalker, pFrom->pSelect);
88504      }
88505#endif
88506    }
88507
88508    /* Locate the index named by the INDEXED BY clause, if any. */
88509    if( sqlite3IndexedByLookup(pParse, pFrom) ){
88510      return WRC_Abort;
88511    }
88512  }
88513
88514  /* Process NATURAL keywords, and ON and USING clauses of joins.
88515  */
88516  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
88517    return WRC_Abort;
88518  }
88519
88520  /* For every "*" that occurs in the column list, insert the names of
88521  ** all columns in all tables.  And for every TABLE.* insert the names
88522  ** of all columns in TABLE.  The parser inserted a special expression
88523  ** with the TK_ALL operator for each "*" that it found in the column list.
88524  ** The following code just has to locate the TK_ALL expressions and expand
88525  ** each one to the list of all columns in all tables.
88526  **
88527  ** The first loop just checks to see if there are any "*" operators
88528  ** that need expanding.
88529  */
88530  for(k=0; k<pEList->nExpr; k++){
88531    Expr *pE = pEList->a[k].pExpr;
88532    if( pE->op==TK_ALL ) break;
88533    assert( pE->op!=TK_DOT || pE->pRight!=0 );
88534    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
88535    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
88536  }
88537  if( k<pEList->nExpr ){
88538    /*
88539    ** If we get here it means the result set contains one or more "*"
88540    ** operators that need to be expanded.  Loop through each expression
88541    ** in the result set and expand them one by one.
88542    */
88543    struct ExprList_item *a = pEList->a;
88544    ExprList *pNew = 0;
88545    int flags = pParse->db->flags;
88546    int longNames = (flags & SQLITE_FullColNames)!=0
88547                      && (flags & SQLITE_ShortColNames)==0;
88548
88549    for(k=0; k<pEList->nExpr; k++){
88550      Expr *pE = a[k].pExpr;
88551      assert( pE->op!=TK_DOT || pE->pRight!=0 );
88552      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
88553        /* This particular expression does not need to be expanded.
88554        */
88555        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
88556        if( pNew ){
88557          pNew->a[pNew->nExpr-1].zName = a[k].zName;
88558          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
88559          a[k].zName = 0;
88560          a[k].zSpan = 0;
88561        }
88562        a[k].pExpr = 0;
88563      }else{
88564        /* This expression is a "*" or a "TABLE.*" and needs to be
88565        ** expanded. */
88566        int tableSeen = 0;      /* Set to 1 when TABLE matches */
88567        char *zTName;            /* text of name of TABLE */
88568        if( pE->op==TK_DOT ){
88569          assert( pE->pLeft!=0 );
88570          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
88571          zTName = pE->pLeft->u.zToken;
88572        }else{
88573          zTName = 0;
88574        }
88575        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88576          Table *pTab = pFrom->pTab;
88577          char *zTabName = pFrom->zAlias;
88578          if( zTabName==0 ){
88579            zTabName = pTab->zName;
88580          }
88581          if( db->mallocFailed ) break;
88582          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
88583            continue;
88584          }
88585          tableSeen = 1;
88586          for(j=0; j<pTab->nCol; j++){
88587            Expr *pExpr, *pRight;
88588            char *zName = pTab->aCol[j].zName;
88589            char *zColname;  /* The computed column name */
88590            char *zToFree;   /* Malloced string that needs to be freed */
88591            Token sColname;  /* Computed column name as a token */
88592
88593            /* If a column is marked as 'hidden' (currently only possible
88594            ** for virtual tables), do not include it in the expanded
88595            ** result-set list.
88596            */
88597            if( IsHiddenColumn(&pTab->aCol[j]) ){
88598              assert(IsVirtual(pTab));
88599              continue;
88600            }
88601
88602            if( i>0 && zTName==0 ){
88603              if( (pFrom->jointype & JT_NATURAL)!=0
88604                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
88605              ){
88606                /* In a NATURAL join, omit the join columns from the
88607                ** table to the right of the join */
88608                continue;
88609              }
88610              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
88611                /* In a join with a USING clause, omit columns in the
88612                ** using clause from the table on the right. */
88613                continue;
88614              }
88615            }
88616            pRight = sqlite3Expr(db, TK_ID, zName);
88617            zColname = zName;
88618            zToFree = 0;
88619            if( longNames || pTabList->nSrc>1 ){
88620              Expr *pLeft;
88621              pLeft = sqlite3Expr(db, TK_ID, zTabName);
88622              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
88623              if( longNames ){
88624                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
88625                zToFree = zColname;
88626              }
88627            }else{
88628              pExpr = pRight;
88629            }
88630            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
88631            sColname.z = zColname;
88632            sColname.n = sqlite3Strlen30(zColname);
88633            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
88634            sqlite3DbFree(db, zToFree);
88635          }
88636        }
88637        if( !tableSeen ){
88638          if( zTName ){
88639            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
88640          }else{
88641            sqlite3ErrorMsg(pParse, "no tables specified");
88642          }
88643        }
88644      }
88645    }
88646    sqlite3ExprListDelete(db, pEList);
88647    p->pEList = pNew;
88648  }
88649#if SQLITE_MAX_COLUMN
88650  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88651    sqlite3ErrorMsg(pParse, "too many columns in result set");
88652  }
88653#endif
88654  return WRC_Continue;
88655}
88656
88657/*
88658** No-op routine for the parse-tree walker.
88659**
88660** When this routine is the Walker.xExprCallback then expression trees
88661** are walked without any actions being taken at each node.  Presumably,
88662** when this routine is used for Walker.xExprCallback then
88663** Walker.xSelectCallback is set to do something useful for every
88664** subquery in the parser tree.
88665*/
88666static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
88667  UNUSED_PARAMETER2(NotUsed, NotUsed2);
88668  return WRC_Continue;
88669}
88670
88671/*
88672** This routine "expands" a SELECT statement and all of its subqueries.
88673** For additional information on what it means to "expand" a SELECT
88674** statement, see the comment on the selectExpand worker callback above.
88675**
88676** Expanding a SELECT statement is the first step in processing a
88677** SELECT statement.  The SELECT statement must be expanded before
88678** name resolution is performed.
88679**
88680** If anything goes wrong, an error message is written into pParse.
88681** The calling function can detect the problem by looking at pParse->nErr
88682** and/or pParse->db->mallocFailed.
88683*/
88684static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
88685  Walker w;
88686  w.xSelectCallback = selectExpander;
88687  w.xExprCallback = exprWalkNoop;
88688  w.pParse = pParse;
88689  sqlite3WalkSelect(&w, pSelect);
88690}
88691
88692
88693#ifndef SQLITE_OMIT_SUBQUERY
88694/*
88695** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
88696** interface.
88697**
88698** For each FROM-clause subquery, add Column.zType and Column.zColl
88699** information to the Table structure that represents the result set
88700** of that subquery.
88701**
88702** The Table structure that represents the result set was constructed
88703** by selectExpander() but the type and collation information was omitted
88704** at that point because identifiers had not yet been resolved.  This
88705** routine is called after identifier resolution.
88706*/
88707static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
88708  Parse *pParse;
88709  int i;
88710  SrcList *pTabList;
88711  struct SrcList_item *pFrom;
88712
88713  assert( p->selFlags & SF_Resolved );
88714  if( (p->selFlags & SF_HasTypeInfo)==0 ){
88715    p->selFlags |= SF_HasTypeInfo;
88716    pParse = pWalker->pParse;
88717    pTabList = p->pSrc;
88718    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88719      Table *pTab = pFrom->pTab;
88720      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
88721        /* A sub-query in the FROM clause of a SELECT */
88722        Select *pSel = pFrom->pSelect;
88723        assert( pSel );
88724        while( pSel->pPrior ) pSel = pSel->pPrior;
88725        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
88726      }
88727    }
88728  }
88729  return WRC_Continue;
88730}
88731#endif
88732
88733
88734/*
88735** This routine adds datatype and collating sequence information to
88736** the Table structures of all FROM-clause subqueries in a
88737** SELECT statement.
88738**
88739** Use this routine after name resolution.
88740*/
88741static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
88742#ifndef SQLITE_OMIT_SUBQUERY
88743  Walker w;
88744  w.xSelectCallback = selectAddSubqueryTypeInfo;
88745  w.xExprCallback = exprWalkNoop;
88746  w.pParse = pParse;
88747  sqlite3WalkSelect(&w, pSelect);
88748#endif
88749}
88750
88751
88752/*
88753** This routine sets of a SELECT statement for processing.  The
88754** following is accomplished:
88755**
88756**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
88757**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
88758**     *  ON and USING clauses are shifted into WHERE statements
88759**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
88760**     *  Identifiers in expression are matched to tables.
88761**
88762** This routine acts recursively on all subqueries within the SELECT.
88763*/
88764SQLITE_PRIVATE void sqlite3SelectPrep(
88765  Parse *pParse,         /* The parser context */
88766  Select *p,             /* The SELECT statement being coded. */
88767  NameContext *pOuterNC  /* Name context for container */
88768){
88769  sqlite3 *db;
88770  if( NEVER(p==0) ) return;
88771  db = pParse->db;
88772  if( p->selFlags & SF_HasTypeInfo ) return;
88773  sqlite3SelectExpand(pParse, p);
88774  if( pParse->nErr || db->mallocFailed ) return;
88775  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
88776  if( pParse->nErr || db->mallocFailed ) return;
88777  sqlite3SelectAddTypeInfo(pParse, p);
88778}
88779
88780/*
88781** Reset the aggregate accumulator.
88782**
88783** The aggregate accumulator is a set of memory cells that hold
88784** intermediate results while calculating an aggregate.  This
88785** routine simply stores NULLs in all of those memory cells.
88786*/
88787static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
88788  Vdbe *v = pParse->pVdbe;
88789  int i;
88790  struct AggInfo_func *pFunc;
88791  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
88792    return;
88793  }
88794  for(i=0; i<pAggInfo->nColumn; i++){
88795    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
88796  }
88797  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
88798    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
88799    if( pFunc->iDistinct>=0 ){
88800      Expr *pE = pFunc->pExpr;
88801      assert( !ExprHasProperty(pE, EP_xIsSelect) );
88802      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
88803        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
88804           "argument");
88805        pFunc->iDistinct = -1;
88806      }else{
88807        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
88808        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
88809                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
88810      }
88811    }
88812  }
88813}
88814
88815/*
88816** Invoke the OP_AggFinalize opcode for every aggregate function
88817** in the AggInfo structure.
88818*/
88819static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
88820  Vdbe *v = pParse->pVdbe;
88821  int i;
88822  struct AggInfo_func *pF;
88823  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
88824    ExprList *pList = pF->pExpr->x.pList;
88825    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
88826    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
88827                      (void*)pF->pFunc, P4_FUNCDEF);
88828  }
88829}
88830
88831/*
88832** Update the accumulator memory cells for an aggregate based on
88833** the current cursor position.
88834*/
88835static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
88836  Vdbe *v = pParse->pVdbe;
88837  int i;
88838  struct AggInfo_func *pF;
88839  struct AggInfo_col *pC;
88840
88841  pAggInfo->directMode = 1;
88842  sqlite3ExprCacheClear(pParse);
88843  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
88844    int nArg;
88845    int addrNext = 0;
88846    int regAgg;
88847    ExprList *pList = pF->pExpr->x.pList;
88848    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
88849    if( pList ){
88850      nArg = pList->nExpr;
88851      regAgg = sqlite3GetTempRange(pParse, nArg);
88852      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
88853    }else{
88854      nArg = 0;
88855      regAgg = 0;
88856    }
88857    if( pF->iDistinct>=0 ){
88858      addrNext = sqlite3VdbeMakeLabel(v);
88859      assert( nArg==1 );
88860      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
88861    }
88862    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
88863      CollSeq *pColl = 0;
88864      struct ExprList_item *pItem;
88865      int j;
88866      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
88867      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
88868        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
88869      }
88870      if( !pColl ){
88871        pColl = pParse->db->pDfltColl;
88872      }
88873      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
88874    }
88875    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
88876                      (void*)pF->pFunc, P4_FUNCDEF);
88877    sqlite3VdbeChangeP5(v, (u8)nArg);
88878    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
88879    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
88880    if( addrNext ){
88881      sqlite3VdbeResolveLabel(v, addrNext);
88882      sqlite3ExprCacheClear(pParse);
88883    }
88884  }
88885
88886  /* Before populating the accumulator registers, clear the column cache.
88887  ** Otherwise, if any of the required column values are already present
88888  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
88889  ** to pC->iMem. But by the time the value is used, the original register
88890  ** may have been used, invalidating the underlying buffer holding the
88891  ** text or blob value. See ticket [883034dcb5].
88892  **
88893  ** Another solution would be to change the OP_SCopy used to copy cached
88894  ** values to an OP_Copy.
88895  */
88896  sqlite3ExprCacheClear(pParse);
88897  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
88898    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
88899  }
88900  pAggInfo->directMode = 0;
88901  sqlite3ExprCacheClear(pParse);
88902}
88903
88904/*
88905** Generate code for the SELECT statement given in the p argument.
88906**
88907** The results are distributed in various ways depending on the
88908** contents of the SelectDest structure pointed to by argument pDest
88909** as follows:
88910**
88911**     pDest->eDest    Result
88912**     ------------    -------------------------------------------
88913**     SRT_Output      Generate a row of output (using the OP_ResultRow
88914**                     opcode) for each row in the result set.
88915**
88916**     SRT_Mem         Only valid if the result is a single column.
88917**                     Store the first column of the first result row
88918**                     in register pDest->iParm then abandon the rest
88919**                     of the query.  This destination implies "LIMIT 1".
88920**
88921**     SRT_Set         The result must be a single column.  Store each
88922**                     row of result as the key in table pDest->iParm.
88923**                     Apply the affinity pDest->affinity before storing
88924**                     results.  Used to implement "IN (SELECT ...)".
88925**
88926**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
88927**
88928**     SRT_Except      Remove results from the temporary table pDest->iParm.
88929**
88930**     SRT_Table       Store results in temporary table pDest->iParm.
88931**                     This is like SRT_EphemTab except that the table
88932**                     is assumed to already be open.
88933**
88934**     SRT_EphemTab    Create an temporary table pDest->iParm and store
88935**                     the result there. The cursor is left open after
88936**                     returning.  This is like SRT_Table except that
88937**                     this destination uses OP_OpenEphemeral to create
88938**                     the table first.
88939**
88940**     SRT_Coroutine   Generate a co-routine that returns a new row of
88941**                     results each time it is invoked.  The entry point
88942**                     of the co-routine is stored in register pDest->iParm.
88943**
88944**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
88945**                     set is not empty.
88946**
88947**     SRT_Discard     Throw the results away.  This is used by SELECT
88948**                     statements within triggers whose only purpose is
88949**                     the side-effects of functions.
88950**
88951** This routine returns the number of errors.  If any errors are
88952** encountered, then an appropriate error message is left in
88953** pParse->zErrMsg.
88954**
88955** This routine does NOT free the Select structure passed in.  The
88956** calling function needs to do that.
88957*/
88958SQLITE_PRIVATE int sqlite3Select(
88959  Parse *pParse,         /* The parser context */
88960  Select *p,             /* The SELECT statement being coded. */
88961  SelectDest *pDest      /* What to do with the query results */
88962){
88963  int i, j;              /* Loop counters */
88964  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
88965  Vdbe *v;               /* The virtual machine under construction */
88966  int isAgg;             /* True for select lists like "count(*)" */
88967  ExprList *pEList;      /* List of columns to extract. */
88968  SrcList *pTabList;     /* List of tables to select from */
88969  Expr *pWhere;          /* The WHERE clause.  May be NULL */
88970  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
88971  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
88972  Expr *pHaving;         /* The HAVING clause.  May be NULL */
88973  int isDistinct;        /* True if the DISTINCT keyword is present */
88974  int distinct;          /* Table to use for the distinct set */
88975  int rc = 1;            /* Value to return from this function */
88976  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
88977  AggInfo sAggInfo;      /* Information used by aggregate queries */
88978  int iEnd;              /* Address of the end of the query */
88979  sqlite3 *db;           /* The database connection */
88980
88981  db = pParse->db;
88982  if( p==0 || db->mallocFailed || pParse->nErr ){
88983    return 1;
88984  }
88985  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
88986  memset(&sAggInfo, 0, sizeof(sAggInfo));
88987
88988  if( IgnorableOrderby(pDest) ){
88989    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
88990           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
88991    /* If ORDER BY makes no difference in the output then neither does
88992    ** DISTINCT so it can be removed too. */
88993    sqlite3ExprListDelete(db, p->pOrderBy);
88994    p->pOrderBy = 0;
88995    p->selFlags &= ~SF_Distinct;
88996  }
88997  sqlite3SelectPrep(pParse, p, 0);
88998  pOrderBy = p->pOrderBy;
88999  pTabList = p->pSrc;
89000  pEList = p->pEList;
89001  if( pParse->nErr || db->mallocFailed ){
89002    goto select_end;
89003  }
89004  isAgg = (p->selFlags & SF_Aggregate)!=0;
89005  assert( pEList!=0 );
89006
89007  /* Begin generating code.
89008  */
89009  v = sqlite3GetVdbe(pParse);
89010  if( v==0 ) goto select_end;
89011
89012  /* Generate code for all sub-queries in the FROM clause
89013  */
89014#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89015  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
89016    struct SrcList_item *pItem = &pTabList->a[i];
89017    SelectDest dest;
89018    Select *pSub = pItem->pSelect;
89019    int isAggSub;
89020
89021    if( pSub==0 || pItem->isPopulated ) continue;
89022
89023    /* Increment Parse.nHeight by the height of the largest expression
89024    ** tree refered to by this, the parent select. The child select
89025    ** may contain expression trees of at most
89026    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
89027    ** more conservative than necessary, but much easier than enforcing
89028    ** an exact limit.
89029    */
89030    pParse->nHeight += sqlite3SelectExprHeight(p);
89031
89032    /* Check to see if the subquery can be absorbed into the parent. */
89033    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
89034    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
89035      if( isAggSub ){
89036        isAgg = 1;
89037        p->selFlags |= SF_Aggregate;
89038      }
89039      i = -1;
89040    }else{
89041      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
89042      assert( pItem->isPopulated==0 );
89043      sqlite3Select(pParse, pSub, &dest);
89044      pItem->isPopulated = 1;
89045    }
89046    if( /*pParse->nErr ||*/ db->mallocFailed ){
89047      goto select_end;
89048    }
89049    pParse->nHeight -= sqlite3SelectExprHeight(p);
89050    pTabList = p->pSrc;
89051    if( !IgnorableOrderby(pDest) ){
89052      pOrderBy = p->pOrderBy;
89053    }
89054  }
89055  pEList = p->pEList;
89056#endif
89057  pWhere = p->pWhere;
89058  pGroupBy = p->pGroupBy;
89059  pHaving = p->pHaving;
89060  isDistinct = (p->selFlags & SF_Distinct)!=0;
89061
89062#ifndef SQLITE_OMIT_COMPOUND_SELECT
89063  /* If there is are a sequence of queries, do the earlier ones first.
89064  */
89065  if( p->pPrior ){
89066    if( p->pRightmost==0 ){
89067      Select *pLoop, *pRight = 0;
89068      int cnt = 0;
89069      int mxSelect;
89070      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
89071        pLoop->pRightmost = p;
89072        pLoop->pNext = pRight;
89073        pRight = pLoop;
89074      }
89075      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
89076      if( mxSelect && cnt>mxSelect ){
89077        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
89078        return 1;
89079      }
89080    }
89081    return multiSelect(pParse, p, pDest);
89082  }
89083#endif
89084
89085  /* If writing to memory or generating a set
89086  ** only a single column may be output.
89087  */
89088#ifndef SQLITE_OMIT_SUBQUERY
89089  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
89090    goto select_end;
89091  }
89092#endif
89093
89094  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
89095  ** GROUP BY might use an index, DISTINCT never does.
89096  */
89097  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
89098  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
89099    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
89100    pGroupBy = p->pGroupBy;
89101    p->selFlags &= ~SF_Distinct;
89102    isDistinct = 0;
89103  }
89104
89105  /* If there is both a GROUP BY and an ORDER BY clause and they are
89106  ** identical, then disable the ORDER BY clause since the GROUP BY
89107  ** will cause elements to come out in the correct order.  This is
89108  ** an optimization - the correct answer should result regardless.
89109  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
89110  ** to disable this optimization for testing purposes.
89111  */
89112  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
89113         && (db->flags & SQLITE_GroupByOrder)==0 ){
89114    pOrderBy = 0;
89115  }
89116
89117  /* If there is an ORDER BY clause, then this sorting
89118  ** index might end up being unused if the data can be
89119  ** extracted in pre-sorted order.  If that is the case, then the
89120  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
89121  ** we figure out that the sorting index is not needed.  The addrSortIndex
89122  ** variable is used to facilitate that change.
89123  */
89124  if( pOrderBy ){
89125    KeyInfo *pKeyInfo;
89126    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
89127    pOrderBy->iECursor = pParse->nTab++;
89128    p->addrOpenEphm[2] = addrSortIndex =
89129      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
89130                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
89131                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89132  }else{
89133    addrSortIndex = -1;
89134  }
89135
89136  /* If the output is destined for a temporary table, open that table.
89137  */
89138  if( pDest->eDest==SRT_EphemTab ){
89139    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
89140  }
89141
89142  /* Set the limiter.
89143  */
89144  iEnd = sqlite3VdbeMakeLabel(v);
89145  computeLimitRegisters(pParse, p, iEnd);
89146
89147  /* Open a virtual index to use for the distinct set.
89148  */
89149  if( isDistinct ){
89150    KeyInfo *pKeyInfo;
89151    assert( isAgg || pGroupBy );
89152    distinct = pParse->nTab++;
89153    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
89154    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
89155                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89156  }else{
89157    distinct = -1;
89158  }
89159
89160  /* Aggregate and non-aggregate queries are handled differently */
89161  if( !isAgg && pGroupBy==0 ){
89162    /* This case is for non-aggregate queries
89163    ** Begin the database scan
89164    */
89165    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
89166    if( pWInfo==0 ) goto select_end;
89167
89168    /* If sorting index that was created by a prior OP_OpenEphemeral
89169    ** instruction ended up not being needed, then change the OP_OpenEphemeral
89170    ** into an OP_Noop.
89171    */
89172    if( addrSortIndex>=0 && pOrderBy==0 ){
89173      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
89174      p->addrOpenEphm[2] = -1;
89175    }
89176
89177    /* Use the standard inner loop
89178    */
89179    assert(!isDistinct);
89180    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
89181                    pWInfo->iContinue, pWInfo->iBreak);
89182
89183    /* End the database scan loop.
89184    */
89185    sqlite3WhereEnd(pWInfo);
89186  }else{
89187    /* This is the processing for aggregate queries */
89188    NameContext sNC;    /* Name context for processing aggregate information */
89189    int iAMem;          /* First Mem address for storing current GROUP BY */
89190    int iBMem;          /* First Mem address for previous GROUP BY */
89191    int iUseFlag;       /* Mem address holding flag indicating that at least
89192                        ** one row of the input to the aggregator has been
89193                        ** processed */
89194    int iAbortFlag;     /* Mem address which causes query abort if positive */
89195    int groupBySort;    /* Rows come from source in GROUP BY order */
89196    int addrEnd;        /* End of processing for this SELECT */
89197
89198    /* Remove any and all aliases between the result set and the
89199    ** GROUP BY clause.
89200    */
89201    if( pGroupBy ){
89202      int k;                        /* Loop counter */
89203      struct ExprList_item *pItem;  /* For looping over expression in a list */
89204
89205      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
89206        pItem->iAlias = 0;
89207      }
89208      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
89209        pItem->iAlias = 0;
89210      }
89211    }
89212
89213
89214    /* Create a label to jump to when we want to abort the query */
89215    addrEnd = sqlite3VdbeMakeLabel(v);
89216
89217    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
89218    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
89219    ** SELECT statement.
89220    */
89221    memset(&sNC, 0, sizeof(sNC));
89222    sNC.pParse = pParse;
89223    sNC.pSrcList = pTabList;
89224    sNC.pAggInfo = &sAggInfo;
89225    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
89226    sAggInfo.pGroupBy = pGroupBy;
89227    sqlite3ExprAnalyzeAggList(&sNC, pEList);
89228    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
89229    if( pHaving ){
89230      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
89231    }
89232    sAggInfo.nAccumulator = sAggInfo.nColumn;
89233    for(i=0; i<sAggInfo.nFunc; i++){
89234      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
89235      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
89236    }
89237    if( db->mallocFailed ) goto select_end;
89238
89239    /* Processing for aggregates with GROUP BY is very different and
89240    ** much more complex than aggregates without a GROUP BY.
89241    */
89242    if( pGroupBy ){
89243      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
89244      int j1;             /* A-vs-B comparision jump */
89245      int addrOutputRow;  /* Start of subroutine that outputs a result row */
89246      int regOutputRow;   /* Return address register for output subroutine */
89247      int addrSetAbort;   /* Set the abort flag and return */
89248      int addrTopOfLoop;  /* Top of the input loop */
89249      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
89250      int addrReset;      /* Subroutine for resetting the accumulator */
89251      int regReset;       /* Return address register for reset subroutine */
89252
89253      /* If there is a GROUP BY clause we might need a sorting index to
89254      ** implement it.  Allocate that sorting index now.  If it turns out
89255      ** that we do not need it after all, the OpenEphemeral instruction
89256      ** will be converted into a Noop.
89257      */
89258      sAggInfo.sortingIdx = pParse->nTab++;
89259      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
89260      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
89261          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
89262          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89263
89264      /* Initialize memory locations used by GROUP BY aggregate processing
89265      */
89266      iUseFlag = ++pParse->nMem;
89267      iAbortFlag = ++pParse->nMem;
89268      regOutputRow = ++pParse->nMem;
89269      addrOutputRow = sqlite3VdbeMakeLabel(v);
89270      regReset = ++pParse->nMem;
89271      addrReset = sqlite3VdbeMakeLabel(v);
89272      iAMem = pParse->nMem + 1;
89273      pParse->nMem += pGroupBy->nExpr;
89274      iBMem = pParse->nMem + 1;
89275      pParse->nMem += pGroupBy->nExpr;
89276      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
89277      VdbeComment((v, "clear abort flag"));
89278      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
89279      VdbeComment((v, "indicate accumulator empty"));
89280
89281      /* Begin a loop that will extract all source rows in GROUP BY order.
89282      ** This might involve two separate loops with an OP_Sort in between, or
89283      ** it might be a single loop that uses an index to extract information
89284      ** in the right order to begin with.
89285      */
89286      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89287      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
89288      if( pWInfo==0 ) goto select_end;
89289      if( pGroupBy==0 ){
89290        /* The optimizer is able to deliver rows in group by order so
89291        ** we do not have to sort.  The OP_OpenEphemeral table will be
89292        ** cancelled later because we still need to use the pKeyInfo
89293        */
89294        pGroupBy = p->pGroupBy;
89295        groupBySort = 0;
89296      }else{
89297        /* Rows are coming out in undetermined order.  We have to push
89298        ** each row into a sorting index, terminate the first loop,
89299        ** then loop over the sorting index in order to get the output
89300        ** in sorted order
89301        */
89302        int regBase;
89303        int regRecord;
89304        int nCol;
89305        int nGroupBy;
89306
89307        groupBySort = 1;
89308        nGroupBy = pGroupBy->nExpr;
89309        nCol = nGroupBy + 1;
89310        j = nGroupBy+1;
89311        for(i=0; i<sAggInfo.nColumn; i++){
89312          if( sAggInfo.aCol[i].iSorterColumn>=j ){
89313            nCol++;
89314            j++;
89315          }
89316        }
89317        regBase = sqlite3GetTempRange(pParse, nCol);
89318        sqlite3ExprCacheClear(pParse);
89319        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
89320        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
89321        j = nGroupBy+1;
89322        for(i=0; i<sAggInfo.nColumn; i++){
89323          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
89324          if( pCol->iSorterColumn>=j ){
89325            int r1 = j + regBase;
89326            int r2;
89327
89328            r2 = sqlite3ExprCodeGetColumn(pParse,
89329                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
89330            if( r1!=r2 ){
89331              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
89332            }
89333            j++;
89334          }
89335        }
89336        regRecord = sqlite3GetTempReg(pParse);
89337        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
89338        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
89339        sqlite3ReleaseTempReg(pParse, regRecord);
89340        sqlite3ReleaseTempRange(pParse, regBase, nCol);
89341        sqlite3WhereEnd(pWInfo);
89342        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
89343        VdbeComment((v, "GROUP BY sort"));
89344        sAggInfo.useSortingIdx = 1;
89345        sqlite3ExprCacheClear(pParse);
89346      }
89347
89348      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
89349      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
89350      ** Then compare the current GROUP BY terms against the GROUP BY terms
89351      ** from the previous row currently stored in a0, a1, a2...
89352      */
89353      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
89354      sqlite3ExprCacheClear(pParse);
89355      for(j=0; j<pGroupBy->nExpr; j++){
89356        if( groupBySort ){
89357          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
89358        }else{
89359          sAggInfo.directMode = 1;
89360          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
89361        }
89362      }
89363      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
89364                          (char*)pKeyInfo, P4_KEYINFO);
89365      j1 = sqlite3VdbeCurrentAddr(v);
89366      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
89367
89368      /* Generate code that runs whenever the GROUP BY changes.
89369      ** Changes in the GROUP BY are detected by the previous code
89370      ** block.  If there were no changes, this block is skipped.
89371      **
89372      ** This code copies current group by terms in b0,b1,b2,...
89373      ** over to a0,a1,a2.  It then calls the output subroutine
89374      ** and resets the aggregate accumulator registers in preparation
89375      ** for the next GROUP BY batch.
89376      */
89377      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
89378      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89379      VdbeComment((v, "output one row"));
89380      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
89381      VdbeComment((v, "check abort flag"));
89382      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89383      VdbeComment((v, "reset accumulator"));
89384
89385      /* Update the aggregate accumulators based on the content of
89386      ** the current row
89387      */
89388      sqlite3VdbeJumpHere(v, j1);
89389      updateAccumulator(pParse, &sAggInfo);
89390      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
89391      VdbeComment((v, "indicate data in accumulator"));
89392
89393      /* End of the loop
89394      */
89395      if( groupBySort ){
89396        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
89397      }else{
89398        sqlite3WhereEnd(pWInfo);
89399        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
89400      }
89401
89402      /* Output the final row of result
89403      */
89404      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89405      VdbeComment((v, "output final row"));
89406
89407      /* Jump over the subroutines
89408      */
89409      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
89410
89411      /* Generate a subroutine that outputs a single row of the result
89412      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
89413      ** is less than or equal to zero, the subroutine is a no-op.  If
89414      ** the processing calls for the query to abort, this subroutine
89415      ** increments the iAbortFlag memory location before returning in
89416      ** order to signal the caller to abort.
89417      */
89418      addrSetAbort = sqlite3VdbeCurrentAddr(v);
89419      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
89420      VdbeComment((v, "set abort flag"));
89421      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89422      sqlite3VdbeResolveLabel(v, addrOutputRow);
89423      addrOutputRow = sqlite3VdbeCurrentAddr(v);
89424      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
89425      VdbeComment((v, "Groupby result generator entry point"));
89426      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89427      finalizeAggFunctions(pParse, &sAggInfo);
89428      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
89429      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
89430                      distinct, pDest,
89431                      addrOutputRow+1, addrSetAbort);
89432      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89433      VdbeComment((v, "end groupby result generator"));
89434
89435      /* Generate a subroutine that will reset the group-by accumulator
89436      */
89437      sqlite3VdbeResolveLabel(v, addrReset);
89438      resetAccumulator(pParse, &sAggInfo);
89439      sqlite3VdbeAddOp1(v, OP_Return, regReset);
89440
89441    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
89442    else {
89443      ExprList *pDel = 0;
89444#ifndef SQLITE_OMIT_BTREECOUNT
89445      Table *pTab;
89446      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
89447        /* If isSimpleCount() returns a pointer to a Table structure, then
89448        ** the SQL statement is of the form:
89449        **
89450        **   SELECT count(*) FROM <tbl>
89451        **
89452        ** where the Table structure returned represents table <tbl>.
89453        **
89454        ** This statement is so common that it is optimized specially. The
89455        ** OP_Count instruction is executed either on the intkey table that
89456        ** contains the data for table <tbl> or on one of its indexes. It
89457        ** is better to execute the op on an index, as indexes are almost
89458        ** always spread across less pages than their corresponding tables.
89459        */
89460        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89461        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
89462        Index *pIdx;                         /* Iterator variable */
89463        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
89464        Index *pBest = 0;                    /* Best index found so far */
89465        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
89466
89467        sqlite3CodeVerifySchema(pParse, iDb);
89468        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
89469
89470        /* Search for the index that has the least amount of columns. If
89471        ** there is such an index, and it has less columns than the table
89472        ** does, then we can assume that it consumes less space on disk and
89473        ** will therefore be cheaper to scan to determine the query result.
89474        ** In this case set iRoot to the root page number of the index b-tree
89475        ** and pKeyInfo to the KeyInfo structure required to navigate the
89476        ** index.
89477        **
89478        ** In practice the KeyInfo structure will not be used. It is only
89479        ** passed to keep OP_OpenRead happy.
89480        */
89481        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89482          if( !pBest || pIdx->nColumn<pBest->nColumn ){
89483            pBest = pIdx;
89484          }
89485        }
89486        if( pBest && pBest->nColumn<pTab->nCol ){
89487          iRoot = pBest->tnum;
89488          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
89489        }
89490
89491        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
89492        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
89493        if( pKeyInfo ){
89494          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
89495        }
89496        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
89497        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
89498      }else
89499#endif /* SQLITE_OMIT_BTREECOUNT */
89500      {
89501        /* Check if the query is of one of the following forms:
89502        **
89503        **   SELECT min(x) FROM ...
89504        **   SELECT max(x) FROM ...
89505        **
89506        ** If it is, then ask the code in where.c to attempt to sort results
89507        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
89508        ** If where.c is able to produce results sorted in this order, then
89509        ** add vdbe code to break out of the processing loop after the
89510        ** first iteration (since the first iteration of the loop is
89511        ** guaranteed to operate on the row with the minimum or maximum
89512        ** value of x, the only row required).
89513        **
89514        ** A special flag must be passed to sqlite3WhereBegin() to slightly
89515        ** modify behaviour as follows:
89516        **
89517        **   + If the query is a "SELECT min(x)", then the loop coded by
89518        **     where.c should not iterate over any values with a NULL value
89519        **     for x.
89520        **
89521        **   + The optimizer code in where.c (the thing that decides which
89522        **     index or indices to use) should place a different priority on
89523        **     satisfying the 'ORDER BY' clause than it does in other cases.
89524        **     Refer to code and comments in where.c for details.
89525        */
89526        ExprList *pMinMax = 0;
89527        u8 flag = minMaxQuery(p);
89528        if( flag ){
89529          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
89530          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
89531          pDel = pMinMax;
89532          if( pMinMax && !db->mallocFailed ){
89533            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
89534            pMinMax->a[0].pExpr->op = TK_COLUMN;
89535          }
89536        }
89537
89538        /* This case runs if the aggregate has no GROUP BY clause.  The
89539        ** processing is much simpler since there is only a single row
89540        ** of output.
89541        */
89542        resetAccumulator(pParse, &sAggInfo);
89543        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
89544        if( pWInfo==0 ){
89545          sqlite3ExprListDelete(db, pDel);
89546          goto select_end;
89547        }
89548        updateAccumulator(pParse, &sAggInfo);
89549        if( !pMinMax && flag ){
89550          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
89551          VdbeComment((v, "%s() by index",
89552                (flag==WHERE_ORDERBY_MIN?"min":"max")));
89553        }
89554        sqlite3WhereEnd(pWInfo);
89555        finalizeAggFunctions(pParse, &sAggInfo);
89556      }
89557
89558      pOrderBy = 0;
89559      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
89560      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
89561                      pDest, addrEnd, addrEnd);
89562      sqlite3ExprListDelete(db, pDel);
89563    }
89564    sqlite3VdbeResolveLabel(v, addrEnd);
89565
89566  } /* endif aggregate query */
89567
89568  /* If there is an ORDER BY clause, then we need to sort the results
89569  ** and send them to the callback one by one.
89570  */
89571  if( pOrderBy ){
89572    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
89573  }
89574
89575  /* Jump here to skip this query
89576  */
89577  sqlite3VdbeResolveLabel(v, iEnd);
89578
89579  /* The SELECT was successfully coded.   Set the return code to 0
89580  ** to indicate no errors.
89581  */
89582  rc = 0;
89583
89584  /* Control jumps to here if an error is encountered above, or upon
89585  ** successful coding of the SELECT.
89586  */
89587select_end:
89588
89589  /* Identify column names if results of the SELECT are to be output.
89590  */
89591  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
89592    generateColumnNames(pParse, pTabList, pEList);
89593  }
89594
89595  sqlite3DbFree(db, sAggInfo.aCol);
89596  sqlite3DbFree(db, sAggInfo.aFunc);
89597  return rc;
89598}
89599
89600#if defined(SQLITE_DEBUG)
89601/*
89602*******************************************************************************
89603** The following code is used for testing and debugging only.  The code
89604** that follows does not appear in normal builds.
89605**
89606** These routines are used to print out the content of all or part of a
89607** parse structures such as Select or Expr.  Such printouts are useful
89608** for helping to understand what is happening inside the code generator
89609** during the execution of complex SELECT statements.
89610**
89611** These routine are not called anywhere from within the normal
89612** code base.  Then are intended to be called from within the debugger
89613** or from temporary "printf" statements inserted for debugging.
89614*/
89615SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
89616  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89617    sqlite3DebugPrintf("(%s", p->u.zToken);
89618  }else{
89619    sqlite3DebugPrintf("(%d", p->op);
89620  }
89621  if( p->pLeft ){
89622    sqlite3DebugPrintf(" ");
89623    sqlite3PrintExpr(p->pLeft);
89624  }
89625  if( p->pRight ){
89626    sqlite3DebugPrintf(" ");
89627    sqlite3PrintExpr(p->pRight);
89628  }
89629  sqlite3DebugPrintf(")");
89630}
89631SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
89632  int i;
89633  for(i=0; i<pList->nExpr; i++){
89634    sqlite3PrintExpr(pList->a[i].pExpr);
89635    if( i<pList->nExpr-1 ){
89636      sqlite3DebugPrintf(", ");
89637    }
89638  }
89639}
89640SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
89641  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
89642  sqlite3PrintExprList(p->pEList);
89643  sqlite3DebugPrintf("\n");
89644  if( p->pSrc ){
89645    char *zPrefix;
89646    int i;
89647    zPrefix = "FROM";
89648    for(i=0; i<p->pSrc->nSrc; i++){
89649      struct SrcList_item *pItem = &p->pSrc->a[i];
89650      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
89651      zPrefix = "";
89652      if( pItem->pSelect ){
89653        sqlite3DebugPrintf("(\n");
89654        sqlite3PrintSelect(pItem->pSelect, indent+10);
89655        sqlite3DebugPrintf("%*s)", indent+8, "");
89656      }else if( pItem->zName ){
89657        sqlite3DebugPrintf("%s", pItem->zName);
89658      }
89659      if( pItem->pTab ){
89660        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
89661      }
89662      if( pItem->zAlias ){
89663        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
89664      }
89665      if( i<p->pSrc->nSrc-1 ){
89666        sqlite3DebugPrintf(",");
89667      }
89668      sqlite3DebugPrintf("\n");
89669    }
89670  }
89671  if( p->pWhere ){
89672    sqlite3DebugPrintf("%*s WHERE ", indent, "");
89673    sqlite3PrintExpr(p->pWhere);
89674    sqlite3DebugPrintf("\n");
89675  }
89676  if( p->pGroupBy ){
89677    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
89678    sqlite3PrintExprList(p->pGroupBy);
89679    sqlite3DebugPrintf("\n");
89680  }
89681  if( p->pHaving ){
89682    sqlite3DebugPrintf("%*s HAVING ", indent, "");
89683    sqlite3PrintExpr(p->pHaving);
89684    sqlite3DebugPrintf("\n");
89685  }
89686  if( p->pOrderBy ){
89687    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
89688    sqlite3PrintExprList(p->pOrderBy);
89689    sqlite3DebugPrintf("\n");
89690  }
89691}
89692/* End of the structure debug printing code
89693*****************************************************************************/
89694#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
89695
89696/************** End of select.c **********************************************/
89697/************** Begin file table.c *******************************************/
89698/*
89699** 2001 September 15
89700**
89701** The author disclaims copyright to this source code.  In place of
89702** a legal notice, here is a blessing:
89703**
89704**    May you do good and not evil.
89705**    May you find forgiveness for yourself and forgive others.
89706**    May you share freely, never taking more than you give.
89707**
89708*************************************************************************
89709** This file contains the sqlite3_get_table() and sqlite3_free_table()
89710** interface routines.  These are just wrappers around the main
89711** interface routine of sqlite3_exec().
89712**
89713** These routines are in a separate files so that they will not be linked
89714** if they are not used.
89715*/
89716
89717#ifndef SQLITE_OMIT_GET_TABLE
89718
89719/*
89720** This structure is used to pass data from sqlite3_get_table() through
89721** to the callback function is uses to build the result.
89722*/
89723typedef struct TabResult {
89724  char **azResult;   /* Accumulated output */
89725  char *zErrMsg;     /* Error message text, if an error occurs */
89726  int nAlloc;        /* Slots allocated for azResult[] */
89727  int nRow;          /* Number of rows in the result */
89728  int nColumn;       /* Number of columns in the result */
89729  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
89730  int rc;            /* Return code from sqlite3_exec() */
89731} TabResult;
89732
89733/*
89734** This routine is called once for each row in the result table.  Its job
89735** is to fill in the TabResult structure appropriately, allocating new
89736** memory as necessary.
89737*/
89738static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
89739  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
89740  int need;                         /* Slots needed in p->azResult[] */
89741  int i;                            /* Loop counter */
89742  char *z;                          /* A single column of result */
89743
89744  /* Make sure there is enough space in p->azResult to hold everything
89745  ** we need to remember from this invocation of the callback.
89746  */
89747  if( p->nRow==0 && argv!=0 ){
89748    need = nCol*2;
89749  }else{
89750    need = nCol;
89751  }
89752  if( p->nData + need > p->nAlloc ){
89753    char **azNew;
89754    p->nAlloc = p->nAlloc*2 + need;
89755    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
89756    if( azNew==0 ) goto malloc_failed;
89757    p->azResult = azNew;
89758  }
89759
89760  /* If this is the first row, then generate an extra row containing
89761  ** the names of all columns.
89762  */
89763  if( p->nRow==0 ){
89764    p->nColumn = nCol;
89765    for(i=0; i<nCol; i++){
89766      z = sqlite3_mprintf("%s", colv[i]);
89767      if( z==0 ) goto malloc_failed;
89768      p->azResult[p->nData++] = z;
89769    }
89770  }else if( p->nColumn!=nCol ){
89771    sqlite3_free(p->zErrMsg);
89772    p->zErrMsg = sqlite3_mprintf(
89773       "sqlite3_get_table() called with two or more incompatible queries"
89774    );
89775    p->rc = SQLITE_ERROR;
89776    return 1;
89777  }
89778
89779  /* Copy over the row data
89780  */
89781  if( argv!=0 ){
89782    for(i=0; i<nCol; i++){
89783      if( argv[i]==0 ){
89784        z = 0;
89785      }else{
89786        int n = sqlite3Strlen30(argv[i])+1;
89787        z = sqlite3_malloc( n );
89788        if( z==0 ) goto malloc_failed;
89789        memcpy(z, argv[i], n);
89790      }
89791      p->azResult[p->nData++] = z;
89792    }
89793    p->nRow++;
89794  }
89795  return 0;
89796
89797malloc_failed:
89798  p->rc = SQLITE_NOMEM;
89799  return 1;
89800}
89801
89802/*
89803** Query the database.  But instead of invoking a callback for each row,
89804** malloc() for space to hold the result and return the entire results
89805** at the conclusion of the call.
89806**
89807** The result that is written to ***pazResult is held in memory obtained
89808** from malloc().  But the caller cannot free this memory directly.
89809** Instead, the entire table should be passed to sqlite3_free_table() when
89810** the calling procedure is finished using it.
89811*/
89812SQLITE_API int sqlite3_get_table(
89813  sqlite3 *db,                /* The database on which the SQL executes */
89814  const char *zSql,           /* The SQL to be executed */
89815  char ***pazResult,          /* Write the result table here */
89816  int *pnRow,                 /* Write the number of rows in the result here */
89817  int *pnColumn,              /* Write the number of columns of result here */
89818  char **pzErrMsg             /* Write error messages here */
89819){
89820  int rc;
89821  TabResult res;
89822
89823  *pazResult = 0;
89824  if( pnColumn ) *pnColumn = 0;
89825  if( pnRow ) *pnRow = 0;
89826  if( pzErrMsg ) *pzErrMsg = 0;
89827  res.zErrMsg = 0;
89828  res.nRow = 0;
89829  res.nColumn = 0;
89830  res.nData = 1;
89831  res.nAlloc = 20;
89832  res.rc = SQLITE_OK;
89833  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
89834  if( res.azResult==0 ){
89835     db->errCode = SQLITE_NOMEM;
89836     return SQLITE_NOMEM;
89837  }
89838  res.azResult[0] = 0;
89839  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
89840  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
89841  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
89842  if( (rc&0xff)==SQLITE_ABORT ){
89843    sqlite3_free_table(&res.azResult[1]);
89844    if( res.zErrMsg ){
89845      if( pzErrMsg ){
89846        sqlite3_free(*pzErrMsg);
89847        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
89848      }
89849      sqlite3_free(res.zErrMsg);
89850    }
89851    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
89852    return res.rc;
89853  }
89854  sqlite3_free(res.zErrMsg);
89855  if( rc!=SQLITE_OK ){
89856    sqlite3_free_table(&res.azResult[1]);
89857    return rc;
89858  }
89859  if( res.nAlloc>res.nData ){
89860    char **azNew;
89861    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
89862    if( azNew==0 ){
89863      sqlite3_free_table(&res.azResult[1]);
89864      db->errCode = SQLITE_NOMEM;
89865      return SQLITE_NOMEM;
89866    }
89867    res.azResult = azNew;
89868  }
89869  *pazResult = &res.azResult[1];
89870  if( pnColumn ) *pnColumn = res.nColumn;
89871  if( pnRow ) *pnRow = res.nRow;
89872  return rc;
89873}
89874
89875/*
89876** This routine frees the space the sqlite3_get_table() malloced.
89877*/
89878SQLITE_API void sqlite3_free_table(
89879  char **azResult            /* Result returned from from sqlite3_get_table() */
89880){
89881  if( azResult ){
89882    int i, n;
89883    azResult--;
89884    assert( azResult!=0 );
89885    n = SQLITE_PTR_TO_INT(azResult[0]);
89886    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
89887    sqlite3_free(azResult);
89888  }
89889}
89890
89891#endif /* SQLITE_OMIT_GET_TABLE */
89892
89893/************** End of table.c ***********************************************/
89894/************** Begin file trigger.c *****************************************/
89895/*
89896**
89897** The author disclaims copyright to this source code.  In place of
89898** a legal notice, here is a blessing:
89899**
89900**    May you do good and not evil.
89901**    May you find forgiveness for yourself and forgive others.
89902**    May you share freely, never taking more than you give.
89903**
89904*************************************************************************
89905** This file contains the implementation for TRIGGERs
89906*/
89907
89908#ifndef SQLITE_OMIT_TRIGGER
89909/*
89910** Delete a linked list of TriggerStep structures.
89911*/
89912SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
89913  while( pTriggerStep ){
89914    TriggerStep * pTmp = pTriggerStep;
89915    pTriggerStep = pTriggerStep->pNext;
89916
89917    sqlite3ExprDelete(db, pTmp->pWhere);
89918    sqlite3ExprListDelete(db, pTmp->pExprList);
89919    sqlite3SelectDelete(db, pTmp->pSelect);
89920    sqlite3IdListDelete(db, pTmp->pIdList);
89921
89922    sqlite3DbFree(db, pTmp);
89923  }
89924}
89925
89926/*
89927** Given table pTab, return a list of all the triggers attached to
89928** the table. The list is connected by Trigger.pNext pointers.
89929**
89930** All of the triggers on pTab that are in the same database as pTab
89931** are already attached to pTab->pTrigger.  But there might be additional
89932** triggers on pTab in the TEMP schema.  This routine prepends all
89933** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
89934** and returns the combined list.
89935**
89936** To state it another way:  This routine returns a list of all triggers
89937** that fire off of pTab.  The list will include any TEMP triggers on
89938** pTab as well as the triggers lised in pTab->pTrigger.
89939*/
89940SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
89941  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
89942  Trigger *pList = 0;                  /* List of triggers to return */
89943
89944  if( pParse->disableTriggers ){
89945    return 0;
89946  }
89947
89948  if( pTmpSchema!=pTab->pSchema ){
89949    HashElem *p;
89950    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
89951      Trigger *pTrig = (Trigger *)sqliteHashData(p);
89952      if( pTrig->pTabSchema==pTab->pSchema
89953       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
89954      ){
89955        pTrig->pNext = (pList ? pList : pTab->pTrigger);
89956        pList = pTrig;
89957      }
89958    }
89959  }
89960
89961  return (pList ? pList : pTab->pTrigger);
89962}
89963
89964/*
89965** This is called by the parser when it sees a CREATE TRIGGER statement
89966** up to the point of the BEGIN before the trigger actions.  A Trigger
89967** structure is generated based on the information available and stored
89968** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
89969** sqlite3FinishTrigger() function is called to complete the trigger
89970** construction process.
89971*/
89972SQLITE_PRIVATE void sqlite3BeginTrigger(
89973  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
89974  Token *pName1,      /* The name of the trigger */
89975  Token *pName2,      /* The name of the trigger */
89976  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
89977  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
89978  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
89979  SrcList *pTableName,/* The name of the table/view the trigger applies to */
89980  Expr *pWhen,        /* WHEN clause */
89981  int isTemp,         /* True if the TEMPORARY keyword is present */
89982  int noErr           /* Suppress errors if the trigger already exists */
89983){
89984  Trigger *pTrigger = 0;  /* The new trigger */
89985  Table *pTab;            /* Table that the trigger fires off of */
89986  char *zName = 0;        /* Name of the trigger */
89987  sqlite3 *db = pParse->db;  /* The database connection */
89988  int iDb;                /* The database to store the trigger in */
89989  Token *pName;           /* The unqualified db name */
89990  DbFixer sFix;           /* State vector for the DB fixer */
89991  int iTabDb;             /* Index of the database holding pTab */
89992
89993  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
89994  assert( pName2!=0 );
89995  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
89996  assert( op>0 && op<0xff );
89997  if( isTemp ){
89998    /* If TEMP was specified, then the trigger name may not be qualified. */
89999    if( pName2->n>0 ){
90000      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
90001      goto trigger_cleanup;
90002    }
90003    iDb = 1;
90004    pName = pName1;
90005  }else{
90006    /* Figure out the db that the the trigger will be created in */
90007    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90008    if( iDb<0 ){
90009      goto trigger_cleanup;
90010    }
90011  }
90012
90013  /* If the trigger name was unqualified, and the table is a temp table,
90014  ** then set iDb to 1 to create the trigger in the temporary database.
90015  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
90016  ** exist, the error is caught by the block below.
90017  */
90018  if( !pTableName || db->mallocFailed ){
90019    goto trigger_cleanup;
90020  }
90021  pTab = sqlite3SrcListLookup(pParse, pTableName);
90022  if( db->init.busy==0 && pName2->n==0 && pTab
90023        && pTab->pSchema==db->aDb[1].pSchema ){
90024    iDb = 1;
90025  }
90026
90027  /* Ensure the table name matches database name and that the table exists */
90028  if( db->mallocFailed ) goto trigger_cleanup;
90029  assert( pTableName->nSrc==1 );
90030  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
90031      sqlite3FixSrcList(&sFix, pTableName) ){
90032    goto trigger_cleanup;
90033  }
90034  pTab = sqlite3SrcListLookup(pParse, pTableName);
90035  if( !pTab ){
90036    /* The table does not exist. */
90037    if( db->init.iDb==1 ){
90038      /* Ticket #3810.
90039      ** Normally, whenever a table is dropped, all associated triggers are
90040      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
90041      ** and the table is dropped by a different database connection, the
90042      ** trigger is not visible to the database connection that does the
90043      ** drop so the trigger cannot be dropped.  This results in an
90044      ** "orphaned trigger" - a trigger whose associated table is missing.
90045      */
90046      db->init.orphanTrigger = 1;
90047    }
90048    goto trigger_cleanup;
90049  }
90050  if( IsVirtual(pTab) ){
90051    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
90052    goto trigger_cleanup;
90053  }
90054
90055  /* Check that the trigger name is not reserved and that no trigger of the
90056  ** specified name exists */
90057  zName = sqlite3NameFromToken(db, pName);
90058  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
90059    goto trigger_cleanup;
90060  }
90061  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
90062                      zName, sqlite3Strlen30(zName)) ){
90063    if( !noErr ){
90064      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
90065    }
90066    goto trigger_cleanup;
90067  }
90068
90069  /* Do not create a trigger on a system table */
90070  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
90071    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
90072    pParse->nErr++;
90073    goto trigger_cleanup;
90074  }
90075
90076  /* INSTEAD of triggers are only for views and views only support INSTEAD
90077  ** of triggers.
90078  */
90079  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
90080    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
90081        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
90082    goto trigger_cleanup;
90083  }
90084  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
90085    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
90086        " trigger on table: %S", pTableName, 0);
90087    goto trigger_cleanup;
90088  }
90089  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90090
90091#ifndef SQLITE_OMIT_AUTHORIZATION
90092  {
90093    int code = SQLITE_CREATE_TRIGGER;
90094    const char *zDb = db->aDb[iTabDb].zName;
90095    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
90096    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
90097    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
90098      goto trigger_cleanup;
90099    }
90100    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
90101      goto trigger_cleanup;
90102    }
90103  }
90104#endif
90105
90106  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
90107  ** cannot appear on views.  So we might as well translate every
90108  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
90109  ** elsewhere.
90110  */
90111  if (tr_tm == TK_INSTEAD){
90112    tr_tm = TK_BEFORE;
90113  }
90114
90115  /* Build the Trigger object */
90116  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
90117  if( pTrigger==0 ) goto trigger_cleanup;
90118  pTrigger->zName = zName;
90119  zName = 0;
90120  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
90121  pTrigger->pSchema = db->aDb[iDb].pSchema;
90122  pTrigger->pTabSchema = pTab->pSchema;
90123  pTrigger->op = (u8)op;
90124  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
90125  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90126  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
90127  assert( pParse->pNewTrigger==0 );
90128  pParse->pNewTrigger = pTrigger;
90129
90130trigger_cleanup:
90131  sqlite3DbFree(db, zName);
90132  sqlite3SrcListDelete(db, pTableName);
90133  sqlite3IdListDelete(db, pColumns);
90134  sqlite3ExprDelete(db, pWhen);
90135  if( !pParse->pNewTrigger ){
90136    sqlite3DeleteTrigger(db, pTrigger);
90137  }else{
90138    assert( pParse->pNewTrigger==pTrigger );
90139  }
90140}
90141
90142/*
90143** This routine is called after all of the trigger actions have been parsed
90144** in order to complete the process of building the trigger.
90145*/
90146SQLITE_PRIVATE void sqlite3FinishTrigger(
90147  Parse *pParse,          /* Parser context */
90148  TriggerStep *pStepList, /* The triggered program */
90149  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
90150){
90151  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
90152  char *zName;                            /* Name of trigger */
90153  sqlite3 *db = pParse->db;               /* The database */
90154  DbFixer sFix;                           /* Fixer object */
90155  int iDb;                                /* Database containing the trigger */
90156  Token nameToken;                        /* Trigger name for error reporting */
90157
90158  pTrig = pParse->pNewTrigger;
90159  pParse->pNewTrigger = 0;
90160  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
90161  zName = pTrig->zName;
90162  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
90163  pTrig->step_list = pStepList;
90164  while( pStepList ){
90165    pStepList->pTrig = pTrig;
90166    pStepList = pStepList->pNext;
90167  }
90168  nameToken.z = pTrig->zName;
90169  nameToken.n = sqlite3Strlen30(nameToken.z);
90170  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
90171          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
90172    goto triggerfinish_cleanup;
90173  }
90174
90175  /* if we are not initializing,
90176  ** build the sqlite_master entry
90177  */
90178  if( !db->init.busy ){
90179    Vdbe *v;
90180    char *z;
90181
90182    /* Make an entry in the sqlite_master table */
90183    v = sqlite3GetVdbe(pParse);
90184    if( v==0 ) goto triggerfinish_cleanup;
90185    sqlite3BeginWriteOperation(pParse, 0, iDb);
90186    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
90187    sqlite3NestedParse(pParse,
90188       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
90189       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
90190       pTrig->table, z);
90191    sqlite3DbFree(db, z);
90192    sqlite3ChangeCookie(pParse, iDb);
90193    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
90194        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
90195    );
90196  }
90197
90198  if( db->init.busy ){
90199    Trigger *pLink = pTrig;
90200    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
90201    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
90202    if( pTrig ){
90203      db->mallocFailed = 1;
90204    }else if( pLink->pSchema==pLink->pTabSchema ){
90205      Table *pTab;
90206      int n = sqlite3Strlen30(pLink->table);
90207      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
90208      assert( pTab!=0 );
90209      pLink->pNext = pTab->pTrigger;
90210      pTab->pTrigger = pLink;
90211    }
90212  }
90213
90214triggerfinish_cleanup:
90215  sqlite3DeleteTrigger(db, pTrig);
90216  assert( !pParse->pNewTrigger );
90217  sqlite3DeleteTriggerStep(db, pStepList);
90218}
90219
90220/*
90221** Turn a SELECT statement (that the pSelect parameter points to) into
90222** a trigger step.  Return a pointer to a TriggerStep structure.
90223**
90224** The parser calls this routine when it finds a SELECT statement in
90225** body of a TRIGGER.
90226*/
90227SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
90228  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
90229  if( pTriggerStep==0 ) {
90230    sqlite3SelectDelete(db, pSelect);
90231    return 0;
90232  }
90233  pTriggerStep->op = TK_SELECT;
90234  pTriggerStep->pSelect = pSelect;
90235  pTriggerStep->orconf = OE_Default;
90236  return pTriggerStep;
90237}
90238
90239/*
90240** Allocate space to hold a new trigger step.  The allocated space
90241** holds both the TriggerStep object and the TriggerStep.target.z string.
90242**
90243** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
90244*/
90245static TriggerStep *triggerStepAllocate(
90246  sqlite3 *db,                /* Database connection */
90247  u8 op,                      /* Trigger opcode */
90248  Token *pName                /* The target name */
90249){
90250  TriggerStep *pTriggerStep;
90251
90252  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
90253  if( pTriggerStep ){
90254    char *z = (char*)&pTriggerStep[1];
90255    memcpy(z, pName->z, pName->n);
90256    pTriggerStep->target.z = z;
90257    pTriggerStep->target.n = pName->n;
90258    pTriggerStep->op = op;
90259  }
90260  return pTriggerStep;
90261}
90262
90263/*
90264** Build a trigger step out of an INSERT statement.  Return a pointer
90265** to the new trigger step.
90266**
90267** The parser calls this routine when it sees an INSERT inside the
90268** body of a trigger.
90269*/
90270SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
90271  sqlite3 *db,        /* The database connection */
90272  Token *pTableName,  /* Name of the table into which we insert */
90273  IdList *pColumn,    /* List of columns in pTableName to insert into */
90274  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
90275  Select *pSelect,    /* A SELECT statement that supplies values */
90276  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
90277){
90278  TriggerStep *pTriggerStep;
90279
90280  assert(pEList == 0 || pSelect == 0);
90281  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
90282
90283  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
90284  if( pTriggerStep ){
90285    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90286    pTriggerStep->pIdList = pColumn;
90287    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90288    pTriggerStep->orconf = orconf;
90289  }else{
90290    sqlite3IdListDelete(db, pColumn);
90291  }
90292  sqlite3ExprListDelete(db, pEList);
90293  sqlite3SelectDelete(db, pSelect);
90294
90295  return pTriggerStep;
90296}
90297
90298/*
90299** Construct a trigger step that implements an UPDATE statement and return
90300** a pointer to that trigger step.  The parser calls this routine when it
90301** sees an UPDATE statement inside the body of a CREATE TRIGGER.
90302*/
90303SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
90304  sqlite3 *db,         /* The database connection */
90305  Token *pTableName,   /* Name of the table to be updated */
90306  ExprList *pEList,    /* The SET clause: list of column and new values */
90307  Expr *pWhere,        /* The WHERE clause */
90308  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
90309){
90310  TriggerStep *pTriggerStep;
90311
90312  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
90313  if( pTriggerStep ){
90314    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90315    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90316    pTriggerStep->orconf = orconf;
90317  }
90318  sqlite3ExprListDelete(db, pEList);
90319  sqlite3ExprDelete(db, pWhere);
90320  return pTriggerStep;
90321}
90322
90323/*
90324** Construct a trigger step that implements a DELETE statement and return
90325** a pointer to that trigger step.  The parser calls this routine when it
90326** sees a DELETE statement inside the body of a CREATE TRIGGER.
90327*/
90328SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
90329  sqlite3 *db,            /* Database connection */
90330  Token *pTableName,      /* The table from which rows are deleted */
90331  Expr *pWhere            /* The WHERE clause */
90332){
90333  TriggerStep *pTriggerStep;
90334
90335  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
90336  if( pTriggerStep ){
90337    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90338    pTriggerStep->orconf = OE_Default;
90339  }
90340  sqlite3ExprDelete(db, pWhere);
90341  return pTriggerStep;
90342}
90343
90344/*
90345** Recursively delete a Trigger structure
90346*/
90347SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
90348  if( pTrigger==0 ) return;
90349  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
90350  sqlite3DbFree(db, pTrigger->zName);
90351  sqlite3DbFree(db, pTrigger->table);
90352  sqlite3ExprDelete(db, pTrigger->pWhen);
90353  sqlite3IdListDelete(db, pTrigger->pColumns);
90354  sqlite3DbFree(db, pTrigger);
90355}
90356
90357/*
90358** This function is called to drop a trigger from the database schema.
90359**
90360** This may be called directly from the parser and therefore identifies
90361** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
90362** same job as this routine except it takes a pointer to the trigger
90363** instead of the trigger name.
90364**/
90365SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
90366  Trigger *pTrigger = 0;
90367  int i;
90368  const char *zDb;
90369  const char *zName;
90370  int nName;
90371  sqlite3 *db = pParse->db;
90372
90373  if( db->mallocFailed ) goto drop_trigger_cleanup;
90374  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
90375    goto drop_trigger_cleanup;
90376  }
90377
90378  assert( pName->nSrc==1 );
90379  zDb = pName->a[0].zDatabase;
90380  zName = pName->a[0].zName;
90381  nName = sqlite3Strlen30(zName);
90382  for(i=OMIT_TEMPDB; i<db->nDb; i++){
90383    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
90384    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
90385    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
90386    if( pTrigger ) break;
90387  }
90388  if( !pTrigger ){
90389    if( !noErr ){
90390      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
90391    }
90392    pParse->checkSchema = 1;
90393    goto drop_trigger_cleanup;
90394  }
90395  sqlite3DropTriggerPtr(pParse, pTrigger);
90396
90397drop_trigger_cleanup:
90398  sqlite3SrcListDelete(db, pName);
90399}
90400
90401/*
90402** Return a pointer to the Table structure for the table that a trigger
90403** is set on.
90404*/
90405static Table *tableOfTrigger(Trigger *pTrigger){
90406  int n = sqlite3Strlen30(pTrigger->table);
90407  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
90408}
90409
90410
90411/*
90412** Drop a trigger given a pointer to that trigger.
90413*/
90414SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
90415  Table   *pTable;
90416  Vdbe *v;
90417  sqlite3 *db = pParse->db;
90418  int iDb;
90419
90420  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
90421  assert( iDb>=0 && iDb<db->nDb );
90422  pTable = tableOfTrigger(pTrigger);
90423  assert( pTable );
90424  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
90425#ifndef SQLITE_OMIT_AUTHORIZATION
90426  {
90427    int code = SQLITE_DROP_TRIGGER;
90428    const char *zDb = db->aDb[iDb].zName;
90429    const char *zTab = SCHEMA_TABLE(iDb);
90430    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
90431    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
90432      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
90433      return;
90434    }
90435  }
90436#endif
90437
90438  /* Generate code to destroy the database record of the trigger.
90439  */
90440  assert( pTable!=0 );
90441  if( (v = sqlite3GetVdbe(pParse))!=0 ){
90442    int base;
90443    static const VdbeOpList dropTrigger[] = {
90444      { OP_Rewind,     0, ADDR(9),  0},
90445      { OP_String8,    0, 1,        0}, /* 1 */
90446      { OP_Column,     0, 1,        2},
90447      { OP_Ne,         2, ADDR(8),  1},
90448      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
90449      { OP_Column,     0, 0,        2},
90450      { OP_Ne,         2, ADDR(8),  1},
90451      { OP_Delete,     0, 0,        0},
90452      { OP_Next,       0, ADDR(1),  0}, /* 8 */
90453    };
90454
90455    sqlite3BeginWriteOperation(pParse, 0, iDb);
90456    sqlite3OpenMasterTable(pParse, iDb);
90457    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
90458    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
90459    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
90460    sqlite3ChangeCookie(pParse, iDb);
90461    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
90462    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
90463    if( pParse->nMem<3 ){
90464      pParse->nMem = 3;
90465    }
90466  }
90467}
90468
90469/*
90470** Remove a trigger from the hash tables of the sqlite* pointer.
90471*/
90472SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
90473  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
90474  Trigger *pTrigger;
90475  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
90476  if( ALWAYS(pTrigger) ){
90477    if( pTrigger->pSchema==pTrigger->pTabSchema ){
90478      Table *pTab = tableOfTrigger(pTrigger);
90479      Trigger **pp;
90480      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
90481      *pp = (*pp)->pNext;
90482    }
90483    sqlite3DeleteTrigger(db, pTrigger);
90484    db->flags |= SQLITE_InternChanges;
90485  }
90486}
90487
90488/*
90489** pEList is the SET clause of an UPDATE statement.  Each entry
90490** in pEList is of the format <id>=<expr>.  If any of the entries
90491** in pEList have an <id> which matches an identifier in pIdList,
90492** then return TRUE.  If pIdList==NULL, then it is considered a
90493** wildcard that matches anything.  Likewise if pEList==NULL then
90494** it matches anything so always return true.  Return false only
90495** if there is no match.
90496*/
90497static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
90498  int e;
90499  if( pIdList==0 || NEVER(pEList==0) ) return 1;
90500  for(e=0; e<pEList->nExpr; e++){
90501    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
90502  }
90503  return 0;
90504}
90505
90506/*
90507** Return a list of all triggers on table pTab if there exists at least
90508** one trigger that must be fired when an operation of type 'op' is
90509** performed on the table, and, if that operation is an UPDATE, if at
90510** least one of the columns in pChanges is being modified.
90511*/
90512SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
90513  Parse *pParse,          /* Parse context */
90514  Table *pTab,            /* The table the contains the triggers */
90515  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
90516  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
90517  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
90518){
90519  int mask = 0;
90520  Trigger *pList = sqlite3TriggerList(pParse, pTab);
90521  Trigger *p;
90522  assert( pList==0 || IsVirtual(pTab)==0 );
90523  for(p=pList; p; p=p->pNext){
90524    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
90525      mask |= p->tr_tm;
90526    }
90527  }
90528  if( pMask ){
90529    *pMask = mask;
90530  }
90531  return (mask ? pList : 0);
90532}
90533
90534/*
90535** Convert the pStep->target token into a SrcList and return a pointer
90536** to that SrcList.
90537**
90538** This routine adds a specific database name, if needed, to the target when
90539** forming the SrcList.  This prevents a trigger in one database from
90540** referring to a target in another database.  An exception is when the
90541** trigger is in TEMP in which case it can refer to any other database it
90542** wants.
90543*/
90544static SrcList *targetSrcList(
90545  Parse *pParse,       /* The parsing context */
90546  TriggerStep *pStep   /* The trigger containing the target token */
90547){
90548  int iDb;             /* Index of the database to use */
90549  SrcList *pSrc;       /* SrcList to be returned */
90550
90551  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
90552  if( pSrc ){
90553    assert( pSrc->nSrc>0 );
90554    assert( pSrc->a!=0 );
90555    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
90556    if( iDb==0 || iDb>=2 ){
90557      sqlite3 *db = pParse->db;
90558      assert( iDb<pParse->db->nDb );
90559      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
90560    }
90561  }
90562  return pSrc;
90563}
90564
90565/*
90566** Generate VDBE code for the statements inside the body of a single
90567** trigger.
90568*/
90569static int codeTriggerProgram(
90570  Parse *pParse,            /* The parser context */
90571  TriggerStep *pStepList,   /* List of statements inside the trigger body */
90572  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
90573){
90574  TriggerStep *pStep;
90575  Vdbe *v = pParse->pVdbe;
90576  sqlite3 *db = pParse->db;
90577
90578  assert( pParse->pTriggerTab && pParse->pToplevel );
90579  assert( pStepList );
90580  assert( v!=0 );
90581  for(pStep=pStepList; pStep; pStep=pStep->pNext){
90582    /* Figure out the ON CONFLICT policy that will be used for this step
90583    ** of the trigger program. If the statement that caused this trigger
90584    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
90585    ** the ON CONFLICT policy that was specified as part of the trigger
90586    ** step statement. Example:
90587    **
90588    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
90589    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
90590    **   END;
90591    **
90592    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
90593    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
90594    */
90595    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
90596
90597    switch( pStep->op ){
90598      case TK_UPDATE: {
90599        sqlite3Update(pParse,
90600          targetSrcList(pParse, pStep),
90601          sqlite3ExprListDup(db, pStep->pExprList, 0),
90602          sqlite3ExprDup(db, pStep->pWhere, 0),
90603          pParse->eOrconf
90604        );
90605        break;
90606      }
90607      case TK_INSERT: {
90608        sqlite3Insert(pParse,
90609          targetSrcList(pParse, pStep),
90610          sqlite3ExprListDup(db, pStep->pExprList, 0),
90611          sqlite3SelectDup(db, pStep->pSelect, 0),
90612          sqlite3IdListDup(db, pStep->pIdList),
90613          pParse->eOrconf
90614        );
90615        break;
90616      }
90617      case TK_DELETE: {
90618        sqlite3DeleteFrom(pParse,
90619          targetSrcList(pParse, pStep),
90620          sqlite3ExprDup(db, pStep->pWhere, 0)
90621        );
90622        break;
90623      }
90624      default: assert( pStep->op==TK_SELECT ); {
90625        SelectDest sDest;
90626        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
90627        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
90628        sqlite3Select(pParse, pSelect, &sDest);
90629        sqlite3SelectDelete(db, pSelect);
90630        break;
90631      }
90632    }
90633    if( pStep->op!=TK_SELECT ){
90634      sqlite3VdbeAddOp0(v, OP_ResetCount);
90635    }
90636  }
90637
90638  return 0;
90639}
90640
90641#ifdef SQLITE_DEBUG
90642/*
90643** This function is used to add VdbeComment() annotations to a VDBE
90644** program. It is not used in production code, only for debugging.
90645*/
90646static const char *onErrorText(int onError){
90647  switch( onError ){
90648    case OE_Abort:    return "abort";
90649    case OE_Rollback: return "rollback";
90650    case OE_Fail:     return "fail";
90651    case OE_Replace:  return "replace";
90652    case OE_Ignore:   return "ignore";
90653    case OE_Default:  return "default";
90654  }
90655  return "n/a";
90656}
90657#endif
90658
90659/*
90660** Parse context structure pFrom has just been used to create a sub-vdbe
90661** (trigger program). If an error has occurred, transfer error information
90662** from pFrom to pTo.
90663*/
90664static void transferParseError(Parse *pTo, Parse *pFrom){
90665  assert( pFrom->zErrMsg==0 || pFrom->nErr );
90666  assert( pTo->zErrMsg==0 || pTo->nErr );
90667  if( pTo->nErr==0 ){
90668    pTo->zErrMsg = pFrom->zErrMsg;
90669    pTo->nErr = pFrom->nErr;
90670  }else{
90671    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
90672  }
90673}
90674
90675/*
90676** Create and populate a new TriggerPrg object with a sub-program
90677** implementing trigger pTrigger with ON CONFLICT policy orconf.
90678*/
90679static TriggerPrg *codeRowTrigger(
90680  Parse *pParse,       /* Current parse context */
90681  Trigger *pTrigger,   /* Trigger to code */
90682  Table *pTab,         /* The table pTrigger is attached to */
90683  int orconf           /* ON CONFLICT policy to code trigger program with */
90684){
90685  Parse *pTop = sqlite3ParseToplevel(pParse);
90686  sqlite3 *db = pParse->db;   /* Database handle */
90687  TriggerPrg *pPrg;           /* Value to return */
90688  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
90689  Vdbe *v;                    /* Temporary VM */
90690  NameContext sNC;            /* Name context for sub-vdbe */
90691  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
90692  Parse *pSubParse;           /* Parse context for sub-vdbe */
90693  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
90694
90695  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
90696
90697  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
90698  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
90699  ** list of the top-level Parse object sooner rather than later.  */
90700  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
90701  if( !pPrg ) return 0;
90702  pPrg->pNext = pTop->pTriggerPrg;
90703  pTop->pTriggerPrg = pPrg;
90704  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
90705  if( !pProgram ) return 0;
90706  pProgram->nRef = 1;
90707  pPrg->pTrigger = pTrigger;
90708  pPrg->orconf = orconf;
90709  pPrg->aColmask[0] = 0xffffffff;
90710  pPrg->aColmask[1] = 0xffffffff;
90711
90712  /* Allocate and populate a new Parse context to use for coding the
90713  ** trigger sub-program.  */
90714  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
90715  if( !pSubParse ) return 0;
90716  memset(&sNC, 0, sizeof(sNC));
90717  sNC.pParse = pSubParse;
90718  pSubParse->db = db;
90719  pSubParse->pTriggerTab = pTab;
90720  pSubParse->pToplevel = pTop;
90721  pSubParse->zAuthContext = pTrigger->zName;
90722  pSubParse->eTriggerOp = pTrigger->op;
90723  pSubParse->nQueryLoop = pParse->nQueryLoop;
90724
90725  v = sqlite3GetVdbe(pSubParse);
90726  if( v ){
90727    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
90728      pTrigger->zName, onErrorText(orconf),
90729      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
90730        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
90731        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
90732        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
90733      pTab->zName
90734    ));
90735#ifndef SQLITE_OMIT_TRACE
90736    sqlite3VdbeChangeP4(v, -1,
90737      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
90738    );
90739#endif
90740
90741    /* If one was specified, code the WHEN clause. If it evaluates to false
90742    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
90743    ** OP_Halt inserted at the end of the program.  */
90744    if( pTrigger->pWhen ){
90745      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
90746      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
90747       && db->mallocFailed==0
90748      ){
90749        iEndTrigger = sqlite3VdbeMakeLabel(v);
90750        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
90751      }
90752      sqlite3ExprDelete(db, pWhen);
90753    }
90754
90755    /* Code the trigger program into the sub-vdbe. */
90756    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
90757
90758    /* Insert an OP_Halt at the end of the sub-program. */
90759    if( iEndTrigger ){
90760      sqlite3VdbeResolveLabel(v, iEndTrigger);
90761    }
90762    sqlite3VdbeAddOp0(v, OP_Halt);
90763    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
90764
90765    transferParseError(pParse, pSubParse);
90766    if( db->mallocFailed==0 ){
90767      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
90768    }
90769    pProgram->nMem = pSubParse->nMem;
90770    pProgram->nCsr = pSubParse->nTab;
90771    pProgram->token = (void *)pTrigger;
90772    pPrg->aColmask[0] = pSubParse->oldmask;
90773    pPrg->aColmask[1] = pSubParse->newmask;
90774    sqlite3VdbeDelete(v);
90775  }
90776
90777  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
90778  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
90779  sqlite3StackFree(db, pSubParse);
90780
90781  return pPrg;
90782}
90783
90784/*
90785** Return a pointer to a TriggerPrg object containing the sub-program for
90786** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
90787** TriggerPrg object exists, a new object is allocated and populated before
90788** being returned.
90789*/
90790static TriggerPrg *getRowTrigger(
90791  Parse *pParse,       /* Current parse context */
90792  Trigger *pTrigger,   /* Trigger to code */
90793  Table *pTab,         /* The table trigger pTrigger is attached to */
90794  int orconf           /* ON CONFLICT algorithm. */
90795){
90796  Parse *pRoot = sqlite3ParseToplevel(pParse);
90797  TriggerPrg *pPrg;
90798
90799  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
90800
90801  /* It may be that this trigger has already been coded (or is in the
90802  ** process of being coded). If this is the case, then an entry with
90803  ** a matching TriggerPrg.pTrigger field will be present somewhere
90804  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
90805  for(pPrg=pRoot->pTriggerPrg;
90806      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
90807      pPrg=pPrg->pNext
90808  );
90809
90810  /* If an existing TriggerPrg could not be located, create a new one. */
90811  if( !pPrg ){
90812    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
90813  }
90814
90815  return pPrg;
90816}
90817
90818/*
90819** Generate code for the trigger program associated with trigger p on
90820** table pTab. The reg, orconf and ignoreJump parameters passed to this
90821** function are the same as those described in the header function for
90822** sqlite3CodeRowTrigger()
90823*/
90824SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
90825  Parse *pParse,       /* Parse context */
90826  Trigger *p,          /* Trigger to code */
90827  Table *pTab,         /* The table to code triggers from */
90828  int reg,             /* Reg array containing OLD.* and NEW.* values */
90829  int orconf,          /* ON CONFLICT policy */
90830  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
90831){
90832  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
90833  TriggerPrg *pPrg;
90834  pPrg = getRowTrigger(pParse, p, pTab, orconf);
90835  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
90836
90837  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
90838  ** is a pointer to the sub-vdbe containing the trigger program.  */
90839  if( pPrg ){
90840    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
90841    pPrg->pProgram->nRef++;
90842    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
90843    VdbeComment(
90844        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
90845
90846    /* Set the P5 operand of the OP_Program instruction to non-zero if
90847    ** recursive invocation of this trigger program is disallowed. Recursive
90848    ** invocation is disallowed if (a) the sub-program is really a trigger,
90849    ** not a foreign key action, and (b) the flag to enable recursive triggers
90850    ** is clear.  */
90851    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
90852  }
90853}
90854
90855/*
90856** This is called to code the required FOR EACH ROW triggers for an operation
90857** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
90858** is given by the op paramater. The tr_tm parameter determines whether the
90859** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
90860** parameter pChanges is passed the list of columns being modified.
90861**
90862** If there are no triggers that fire at the specified time for the specified
90863** operation on pTab, this function is a no-op.
90864**
90865** The reg argument is the address of the first in an array of registers
90866** that contain the values substituted for the new.* and old.* references
90867** in the trigger program. If N is the number of columns in table pTab
90868** (a copy of pTab->nCol), then registers are populated as follows:
90869**
90870**   Register       Contains
90871**   ------------------------------------------------------
90872**   reg+0          OLD.rowid
90873**   reg+1          OLD.* value of left-most column of pTab
90874**   ...            ...
90875**   reg+N          OLD.* value of right-most column of pTab
90876**   reg+N+1        NEW.rowid
90877**   reg+N+2        OLD.* value of left-most column of pTab
90878**   ...            ...
90879**   reg+N+N+1      NEW.* value of right-most column of pTab
90880**
90881** For ON DELETE triggers, the registers containing the NEW.* values will
90882** never be accessed by the trigger program, so they are not allocated or
90883** populated by the caller (there is no data to populate them with anyway).
90884** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
90885** are never accessed, and so are not allocated by the caller. So, for an
90886** ON INSERT trigger, the value passed to this function as parameter reg
90887** is not a readable register, although registers (reg+N) through
90888** (reg+N+N+1) are.
90889**
90890** Parameter orconf is the default conflict resolution algorithm for the
90891** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
90892** is the instruction that control should jump to if a trigger program
90893** raises an IGNORE exception.
90894*/
90895SQLITE_PRIVATE void sqlite3CodeRowTrigger(
90896  Parse *pParse,       /* Parse context */
90897  Trigger *pTrigger,   /* List of triggers on table pTab */
90898  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
90899  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
90900  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
90901  Table *pTab,         /* The table to code triggers from */
90902  int reg,             /* The first in an array of registers (see above) */
90903  int orconf,          /* ON CONFLICT policy */
90904  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
90905){
90906  Trigger *p;          /* Used to iterate through pTrigger list */
90907
90908  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
90909  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
90910  assert( (op==TK_UPDATE)==(pChanges!=0) );
90911
90912  for(p=pTrigger; p; p=p->pNext){
90913
90914    /* Sanity checking:  The schema for the trigger and for the table are
90915    ** always defined.  The trigger must be in the same schema as the table
90916    ** or else it must be a TEMP trigger. */
90917    assert( p->pSchema!=0 );
90918    assert( p->pTabSchema!=0 );
90919    assert( p->pSchema==p->pTabSchema
90920         || p->pSchema==pParse->db->aDb[1].pSchema );
90921
90922    /* Determine whether we should code this trigger */
90923    if( p->op==op
90924     && p->tr_tm==tr_tm
90925     && checkColumnOverlap(p->pColumns, pChanges)
90926    ){
90927      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
90928    }
90929  }
90930}
90931
90932/*
90933** Triggers may access values stored in the old.* or new.* pseudo-table.
90934** This function returns a 32-bit bitmask indicating which columns of the
90935** old.* or new.* tables actually are used by triggers. This information
90936** may be used by the caller, for example, to avoid having to load the entire
90937** old.* record into memory when executing an UPDATE or DELETE command.
90938**
90939** Bit 0 of the returned mask is set if the left-most column of the
90940** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
90941** the second leftmost column value is required, and so on. If there
90942** are more than 32 columns in the table, and at least one of the columns
90943** with an index greater than 32 may be accessed, 0xffffffff is returned.
90944**
90945** It is not possible to determine if the old.rowid or new.rowid column is
90946** accessed by triggers. The caller must always assume that it is.
90947**
90948** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
90949** applies to the old.* table. If 1, the new.* table.
90950**
90951** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
90952** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
90953** included in the returned mask if the TRIGGER_BEFORE bit is set in the
90954** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
90955** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
90956*/
90957SQLITE_PRIVATE u32 sqlite3TriggerColmask(
90958  Parse *pParse,       /* Parse context */
90959  Trigger *pTrigger,   /* List of triggers on table pTab */
90960  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
90961  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
90962  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
90963  Table *pTab,         /* The table to code triggers from */
90964  int orconf           /* Default ON CONFLICT policy for trigger steps */
90965){
90966  const int op = pChanges ? TK_UPDATE : TK_DELETE;
90967  u32 mask = 0;
90968  Trigger *p;
90969
90970  assert( isNew==1 || isNew==0 );
90971  for(p=pTrigger; p; p=p->pNext){
90972    if( p->op==op && (tr_tm&p->tr_tm)
90973     && checkColumnOverlap(p->pColumns,pChanges)
90974    ){
90975      TriggerPrg *pPrg;
90976      pPrg = getRowTrigger(pParse, p, pTab, orconf);
90977      if( pPrg ){
90978        mask |= pPrg->aColmask[isNew];
90979      }
90980    }
90981  }
90982
90983  return mask;
90984}
90985
90986#endif /* !defined(SQLITE_OMIT_TRIGGER) */
90987
90988/************** End of trigger.c *********************************************/
90989/************** Begin file update.c ******************************************/
90990/*
90991** 2001 September 15
90992**
90993** The author disclaims copyright to this source code.  In place of
90994** a legal notice, here is a blessing:
90995**
90996**    May you do good and not evil.
90997**    May you find forgiveness for yourself and forgive others.
90998**    May you share freely, never taking more than you give.
90999**
91000sqlite*************************************************************************
91001** This file contains C code routines that are called by the parser
91002** to handle UPDATE statements.
91003*/
91004
91005#ifndef SQLITE_OMIT_VIRTUALTABLE
91006/* Forward declaration */
91007static void updateVirtualTable(
91008  Parse *pParse,       /* The parsing context */
91009  SrcList *pSrc,       /* The virtual table to be modified */
91010  Table *pTab,         /* The virtual table */
91011  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91012  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
91013  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91014  Expr *pWhere         /* WHERE clause of the UPDATE statement */
91015);
91016#endif /* SQLITE_OMIT_VIRTUALTABLE */
91017
91018/*
91019** The most recently coded instruction was an OP_Column to retrieve the
91020** i-th column of table pTab. This routine sets the P4 parameter of the
91021** OP_Column to the default value, if any.
91022**
91023** The default value of a column is specified by a DEFAULT clause in the
91024** column definition. This was either supplied by the user when the table
91025** was created, or added later to the table definition by an ALTER TABLE
91026** command. If the latter, then the row-records in the table btree on disk
91027** may not contain a value for the column and the default value, taken
91028** from the P4 parameter of the OP_Column instruction, is returned instead.
91029** If the former, then all row-records are guaranteed to include a value
91030** for the column and the P4 value is not required.
91031**
91032** Column definitions created by an ALTER TABLE command may only have
91033** literal default values specified: a number, null or a string. (If a more
91034** complicated default expression value was provided, it is evaluated
91035** when the ALTER TABLE is executed and one of the literal values written
91036** into the sqlite_master table.)
91037**
91038** Therefore, the P4 parameter is only required if the default value for
91039** the column is a literal number, string or null. The sqlite3ValueFromExpr()
91040** function is capable of transforming these types of expressions into
91041** sqlite3_value objects.
91042**
91043** If parameter iReg is not negative, code an OP_RealAffinity instruction
91044** on register iReg. This is used when an equivalent integer value is
91045** stored in place of an 8-byte floating point value in order to save
91046** space.
91047*/
91048SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
91049  assert( pTab!=0 );
91050  if( !pTab->pSelect ){
91051    sqlite3_value *pValue;
91052    u8 enc = ENC(sqlite3VdbeDb(v));
91053    Column *pCol = &pTab->aCol[i];
91054    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
91055    assert( i<pTab->nCol );
91056    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
91057                         pCol->affinity, &pValue);
91058    if( pValue ){
91059      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
91060    }
91061#ifndef SQLITE_OMIT_FLOATING_POINT
91062    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
91063      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
91064    }
91065#endif
91066  }
91067}
91068
91069/*
91070** Process an UPDATE statement.
91071**
91072**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
91073**          \_______/ \________/     \______/       \________________/
91074*            onError   pTabList      pChanges             pWhere
91075*/
91076SQLITE_PRIVATE void sqlite3Update(
91077  Parse *pParse,         /* The parser context */
91078  SrcList *pTabList,     /* The table in which we should change things */
91079  ExprList *pChanges,    /* Things to be changed */
91080  Expr *pWhere,          /* The WHERE clause.  May be null */
91081  int onError            /* How to handle constraint errors */
91082){
91083  int i, j;              /* Loop counters */
91084  Table *pTab;           /* The table to be updated */
91085  int addr = 0;          /* VDBE instruction address of the start of the loop */
91086  WhereInfo *pWInfo;     /* Information about the WHERE clause */
91087  Vdbe *v;               /* The virtual database engine */
91088  Index *pIdx;           /* For looping over indices */
91089  int nIdx;              /* Number of indices that need updating */
91090  int iCur;              /* VDBE Cursor number of pTab */
91091  sqlite3 *db;           /* The database structure */
91092  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
91093  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
91094                         ** an expression for the i-th column of the table.
91095                         ** aXRef[i]==-1 if the i-th column is not changed. */
91096  int chngRowid;         /* True if the record number is being changed */
91097  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
91098  int openAll = 0;       /* True if all indices need to be opened */
91099  AuthContext sContext;  /* The authorization context */
91100  NameContext sNC;       /* The name-context to resolve expressions in */
91101  int iDb;               /* Database containing the table being updated */
91102  int okOnePass;         /* True for one-pass algorithm without the FIFO */
91103  int hasFK;             /* True if foreign key processing is required */
91104
91105#ifndef SQLITE_OMIT_TRIGGER
91106  int isView;            /* True when updating a view (INSTEAD OF trigger) */
91107  Trigger *pTrigger;     /* List of triggers on pTab, if required */
91108  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91109#endif
91110  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
91111
91112  /* Register Allocations */
91113  int regRowCount = 0;   /* A count of rows changed */
91114  int regOldRowid;       /* The old rowid */
91115  int regNewRowid;       /* The new rowid */
91116  int regNew;
91117  int regOld = 0;
91118  int regRowSet = 0;     /* Rowset of rows to be updated */
91119  int regRec;            /* Register used for new table record to insert */
91120
91121  memset(&sContext, 0, sizeof(sContext));
91122  db = pParse->db;
91123  if( pParse->nErr || db->mallocFailed ){
91124    goto update_cleanup;
91125  }
91126  assert( pTabList->nSrc==1 );
91127
91128  /* Locate the table which we want to update.
91129  */
91130  pTab = sqlite3SrcListLookup(pParse, pTabList);
91131  if( pTab==0 ) goto update_cleanup;
91132  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91133
91134  /* Figure out if we have any triggers and if the table being
91135  ** updated is a view.
91136  */
91137#ifndef SQLITE_OMIT_TRIGGER
91138  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
91139  isView = pTab->pSelect!=0;
91140  assert( pTrigger || tmask==0 );
91141#else
91142# define pTrigger 0
91143# define isView 0
91144# define tmask 0
91145#endif
91146#ifdef SQLITE_OMIT_VIEW
91147# undef isView
91148# define isView 0
91149#endif
91150
91151  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
91152    goto update_cleanup;
91153  }
91154  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
91155    goto update_cleanup;
91156  }
91157  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
91158  if( aXRef==0 ) goto update_cleanup;
91159  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
91160
91161  /* Allocate a cursors for the main database table and for all indices.
91162  ** The index cursors might not be used, but if they are used they
91163  ** need to occur right after the database cursor.  So go ahead and
91164  ** allocate enough space, just in case.
91165  */
91166  pTabList->a[0].iCursor = iCur = pParse->nTab++;
91167  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91168    pParse->nTab++;
91169  }
91170
91171  /* Initialize the name-context */
91172  memset(&sNC, 0, sizeof(sNC));
91173  sNC.pParse = pParse;
91174  sNC.pSrcList = pTabList;
91175
91176  /* Resolve the column names in all the expressions of the
91177  ** of the UPDATE statement.  Also find the column index
91178  ** for each column to be updated in the pChanges array.  For each
91179  ** column to be updated, make sure we have authorization to change
91180  ** that column.
91181  */
91182  chngRowid = 0;
91183  for(i=0; i<pChanges->nExpr; i++){
91184    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
91185      goto update_cleanup;
91186    }
91187    for(j=0; j<pTab->nCol; j++){
91188      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
91189        if( j==pTab->iPKey ){
91190          chngRowid = 1;
91191          pRowidExpr = pChanges->a[i].pExpr;
91192        }
91193        aXRef[j] = i;
91194        break;
91195      }
91196    }
91197    if( j>=pTab->nCol ){
91198      if( sqlite3IsRowid(pChanges->a[i].zName) ){
91199        chngRowid = 1;
91200        pRowidExpr = pChanges->a[i].pExpr;
91201      }else{
91202        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
91203        pParse->checkSchema = 1;
91204        goto update_cleanup;
91205      }
91206    }
91207#ifndef SQLITE_OMIT_AUTHORIZATION
91208    {
91209      int rc;
91210      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
91211                           pTab->aCol[j].zName, db->aDb[iDb].zName);
91212      if( rc==SQLITE_DENY ){
91213        goto update_cleanup;
91214      }else if( rc==SQLITE_IGNORE ){
91215        aXRef[j] = -1;
91216      }
91217    }
91218#endif
91219  }
91220
91221  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
91222
91223  /* Allocate memory for the array aRegIdx[].  There is one entry in the
91224  ** array for each index associated with table being updated.  Fill in
91225  ** the value with a register number for indices that are to be used
91226  ** and with zero for unused indices.
91227  */
91228  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91229  if( nIdx>0 ){
91230    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
91231    if( aRegIdx==0 ) goto update_cleanup;
91232  }
91233  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91234    int reg;
91235    if( chngRowid ){
91236      reg = ++pParse->nMem;
91237    }else{
91238      reg = 0;
91239      for(i=0; i<pIdx->nColumn; i++){
91240        if( aXRef[pIdx->aiColumn[i]]>=0 ){
91241          reg = ++pParse->nMem;
91242          break;
91243        }
91244      }
91245    }
91246    aRegIdx[j] = reg;
91247  }
91248
91249  /* Begin generating code. */
91250  v = sqlite3GetVdbe(pParse);
91251  if( v==0 ) goto update_cleanup;
91252  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
91253  sqlite3BeginWriteOperation(pParse, 1, iDb);
91254
91255#ifndef SQLITE_OMIT_VIRTUALTABLE
91256  /* Virtual tables must be handled separately */
91257  if( IsVirtual(pTab) ){
91258    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
91259                       pWhere);
91260    pWhere = 0;
91261    pTabList = 0;
91262    goto update_cleanup;
91263  }
91264#endif
91265
91266  /* Allocate required registers. */
91267  regOldRowid = regNewRowid = ++pParse->nMem;
91268  if( pTrigger || hasFK ){
91269    regOld = pParse->nMem + 1;
91270    pParse->nMem += pTab->nCol;
91271  }
91272  if( chngRowid || pTrigger || hasFK ){
91273    regNewRowid = ++pParse->nMem;
91274  }
91275  regNew = pParse->nMem + 1;
91276  pParse->nMem += pTab->nCol;
91277  regRec = ++pParse->nMem;
91278
91279  /* Start the view context. */
91280  if( isView ){
91281    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
91282  }
91283
91284  /* If we are trying to update a view, realize that view into
91285  ** a ephemeral table.
91286  */
91287#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
91288  if( isView ){
91289    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
91290  }
91291#endif
91292
91293  /* Resolve the column names in all the expressions in the
91294  ** WHERE clause.
91295  */
91296  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
91297    goto update_cleanup;
91298  }
91299
91300  /* Begin the database scan
91301  */
91302  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
91303  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
91304  if( pWInfo==0 ) goto update_cleanup;
91305  okOnePass = pWInfo->okOnePass;
91306
91307  /* Remember the rowid of every item to be updated.
91308  */
91309  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
91310  if( !okOnePass ){
91311    regRowSet = ++pParse->nMem;
91312    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
91313  }
91314
91315  /* End the database scan loop.
91316  */
91317  sqlite3WhereEnd(pWInfo);
91318
91319  /* Initialize the count of updated rows
91320  */
91321  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
91322    regRowCount = ++pParse->nMem;
91323    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
91324  }
91325
91326  if( !isView ){
91327    /*
91328    ** Open every index that needs updating.  Note that if any
91329    ** index could potentially invoke a REPLACE conflict resolution
91330    ** action, then we need to open all indices because we might need
91331    ** to be deleting some records.
91332    */
91333    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
91334    if( onError==OE_Replace ){
91335      openAll = 1;
91336    }else{
91337      openAll = 0;
91338      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91339        if( pIdx->onError==OE_Replace ){
91340          openAll = 1;
91341          break;
91342        }
91343      }
91344    }
91345    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91346      if( openAll || aRegIdx[i]>0 ){
91347        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91348        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
91349                       (char*)pKey, P4_KEYINFO_HANDOFF);
91350        assert( pParse->nTab>iCur+i+1 );
91351      }
91352    }
91353  }
91354
91355  /* Top of the update loop */
91356  if( okOnePass ){
91357    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
91358    addr = sqlite3VdbeAddOp0(v, OP_Goto);
91359    sqlite3VdbeJumpHere(v, a1);
91360  }else{
91361    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
91362  }
91363
91364  /* Make cursor iCur point to the record that is being updated. If
91365  ** this record does not exist for some reason (deleted by a trigger,
91366  ** for example, then jump to the next iteration of the RowSet loop.  */
91367  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91368
91369  /* If the record number will change, set register regNewRowid to
91370  ** contain the new value. If the record number is not being modified,
91371  ** then regNewRowid is the same register as regOldRowid, which is
91372  ** already populated.  */
91373  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
91374  if( chngRowid ){
91375    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
91376    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
91377  }
91378
91379  /* If there are triggers on this table, populate an array of registers
91380  ** with the required old.* column data.  */
91381  if( hasFK || pTrigger ){
91382    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
91383    oldmask |= sqlite3TriggerColmask(pParse,
91384        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
91385    );
91386    for(i=0; i<pTab->nCol; i++){
91387      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
91388        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
91389      }else{
91390        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
91391      }
91392    }
91393    if( chngRowid==0 ){
91394      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
91395    }
91396  }
91397
91398  /* Populate the array of registers beginning at regNew with the new
91399  ** row data. This array is used to check constaints, create the new
91400  ** table and index records, and as the values for any new.* references
91401  ** made by triggers.
91402  **
91403  ** If there are one or more BEFORE triggers, then do not populate the
91404  ** registers associated with columns that are (a) not modified by
91405  ** this UPDATE statement and (b) not accessed by new.* references. The
91406  ** values for registers not modified by the UPDATE must be reloaded from
91407  ** the database after the BEFORE triggers are fired anyway (as the trigger
91408  ** may have modified them). So not loading those that are not going to
91409  ** be used eliminates some redundant opcodes.
91410  */
91411  newmask = sqlite3TriggerColmask(
91412      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
91413  );
91414  for(i=0; i<pTab->nCol; i++){
91415    if( i==pTab->iPKey ){
91416      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
91417    }else{
91418      j = aXRef[i];
91419      if( j>=0 ){
91420        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
91421      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
91422        /* This branch loads the value of a column that will not be changed
91423        ** into a register. This is done if there are no BEFORE triggers, or
91424        ** if there are one or more BEFORE triggers that use this value via
91425        ** a new.* reference in a trigger program.
91426        */
91427        testcase( i==31 );
91428        testcase( i==32 );
91429        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91430        sqlite3ColumnDefault(v, pTab, i, regNew+i);
91431      }
91432    }
91433  }
91434
91435  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
91436  ** verified. One could argue that this is wrong.
91437  */
91438  if( tmask&TRIGGER_BEFORE ){
91439    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
91440    sqlite3TableAffinityStr(v, pTab);
91441    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
91442        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
91443
91444    /* The row-trigger may have deleted the row being updated. In this
91445    ** case, jump to the next row. No updates or AFTER triggers are
91446    ** required. This behaviour - what happens when the row being updated
91447    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
91448    ** documentation.
91449    */
91450    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91451
91452    /* If it did not delete it, the row-trigger may still have modified
91453    ** some of the columns of the row being updated. Load the values for
91454    ** all columns not modified by the update statement into their
91455    ** registers in case this has happened.
91456    */
91457    for(i=0; i<pTab->nCol; i++){
91458      if( aXRef[i]<0 && i!=pTab->iPKey ){
91459        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91460        sqlite3ColumnDefault(v, pTab, i, regNew+i);
91461      }
91462    }
91463  }
91464
91465  if( !isView ){
91466    int j1;                       /* Address of jump instruction */
91467
91468    /* Do constraint checks. */
91469    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
91470        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
91471
91472    /* Do FK constraint checks. */
91473    if( hasFK ){
91474      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
91475    }
91476
91477    /* Delete the index entries associated with the current record.  */
91478    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
91479    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
91480
91481    /* If changing the record number, delete the old record.  */
91482    if( hasFK || chngRowid ){
91483      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
91484    }
91485    sqlite3VdbeJumpHere(v, j1);
91486
91487    if( hasFK ){
91488      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
91489    }
91490
91491    /* Insert the new index entries and the new record. */
91492    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
91493
91494    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
91495    ** handle rows (possibly in other tables) that refer via a foreign key
91496    ** to the row just updated. */
91497    if( hasFK ){
91498      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
91499    }
91500  }
91501
91502  /* Increment the row counter
91503  */
91504  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
91505    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91506  }
91507
91508  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
91509      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
91510
91511  /* Repeat the above with the next record to be updated, until
91512  ** all record selected by the WHERE clause have been updated.
91513  */
91514  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
91515  sqlite3VdbeJumpHere(v, addr);
91516
91517  /* Close all tables */
91518  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91519    if( openAll || aRegIdx[i]>0 ){
91520      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
91521    }
91522  }
91523  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
91524
91525  /* Update the sqlite_sequence table by storing the content of the
91526  ** maximum rowid counter values recorded while inserting into
91527  ** autoincrement tables.
91528  */
91529  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91530    sqlite3AutoincrementEnd(pParse);
91531  }
91532
91533  /*
91534  ** Return the number of rows that were changed. If this routine is
91535  ** generating code because of a call to sqlite3NestedParse(), do not
91536  ** invoke the callback function.
91537  */
91538  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
91539    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91540    sqlite3VdbeSetNumCols(v, 1);
91541    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
91542  }
91543
91544update_cleanup:
91545  sqlite3AuthContextPop(&sContext);
91546  sqlite3DbFree(db, aRegIdx);
91547  sqlite3DbFree(db, aXRef);
91548  sqlite3SrcListDelete(db, pTabList);
91549  sqlite3ExprListDelete(db, pChanges);
91550  sqlite3ExprDelete(db, pWhere);
91551  return;
91552}
91553/* Make sure "isView" and other macros defined above are undefined. Otherwise
91554** thely may interfere with compilation of other functions in this file
91555** (or in another file, if this file becomes part of the amalgamation).  */
91556#ifdef isView
91557 #undef isView
91558#endif
91559#ifdef pTrigger
91560 #undef pTrigger
91561#endif
91562
91563#ifndef SQLITE_OMIT_VIRTUALTABLE
91564/*
91565** Generate code for an UPDATE of a virtual table.
91566**
91567** The strategy is that we create an ephemerial table that contains
91568** for each row to be changed:
91569**
91570**   (A)  The original rowid of that row.
91571**   (B)  The revised rowid for the row. (note1)
91572**   (C)  The content of every column in the row.
91573**
91574** Then we loop over this ephemeral table and for each row in
91575** the ephermeral table call VUpdate.
91576**
91577** When finished, drop the ephemeral table.
91578**
91579** (note1) Actually, if we know in advance that (A) is always the same
91580** as (B) we only store (A), then duplicate (A) when pulling
91581** it out of the ephemeral table before calling VUpdate.
91582*/
91583static void updateVirtualTable(
91584  Parse *pParse,       /* The parsing context */
91585  SrcList *pSrc,       /* The virtual table to be modified */
91586  Table *pTab,         /* The virtual table */
91587  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91588  Expr *pRowid,        /* Expression used to recompute the rowid */
91589  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91590  Expr *pWhere         /* WHERE clause of the UPDATE statement */
91591){
91592  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
91593  ExprList *pEList = 0;     /* The result set of the SELECT statement */
91594  Select *pSelect = 0;      /* The SELECT statement */
91595  Expr *pExpr;              /* Temporary expression */
91596  int ephemTab;             /* Table holding the result of the SELECT */
91597  int i;                    /* Loop counter */
91598  int addr;                 /* Address of top of loop */
91599  int iReg;                 /* First register in set passed to OP_VUpdate */
91600  sqlite3 *db = pParse->db; /* Database connection */
91601  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
91602  SelectDest dest;
91603
91604  /* Construct the SELECT statement that will find the new values for
91605  ** all updated rows.
91606  */
91607  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
91608  if( pRowid ){
91609    pEList = sqlite3ExprListAppend(pParse, pEList,
91610                                   sqlite3ExprDup(db, pRowid, 0));
91611  }
91612  assert( pTab->iPKey<0 );
91613  for(i=0; i<pTab->nCol; i++){
91614    if( aXRef[i]>=0 ){
91615      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
91616    }else{
91617      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
91618    }
91619    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
91620  }
91621  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
91622
91623  /* Create the ephemeral table into which the update results will
91624  ** be stored.
91625  */
91626  assert( v );
91627  ephemTab = pParse->nTab++;
91628  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
91629
91630  /* fill the ephemeral table
91631  */
91632  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
91633  sqlite3Select(pParse, pSelect, &dest);
91634
91635  /* Generate code to scan the ephemeral table and call VUpdate. */
91636  iReg = ++pParse->nMem;
91637  pParse->nMem += pTab->nCol+1;
91638  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
91639  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
91640  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
91641  for(i=0; i<pTab->nCol; i++){
91642    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
91643  }
91644  sqlite3VtabMakeWritable(pParse, pTab);
91645  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
91646  sqlite3MayAbort(pParse);
91647  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
91648  sqlite3VdbeJumpHere(v, addr);
91649  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
91650
91651  /* Cleanup */
91652  sqlite3SelectDelete(db, pSelect);
91653}
91654#endif /* SQLITE_OMIT_VIRTUALTABLE */
91655
91656/************** End of update.c **********************************************/
91657/************** Begin file vacuum.c ******************************************/
91658/*
91659** 2003 April 6
91660**
91661** The author disclaims copyright to this source code.  In place of
91662** a legal notice, here is a blessing:
91663**
91664**    May you do good and not evil.
91665**    May you find forgiveness for yourself and forgive others.
91666**    May you share freely, never taking more than you give.
91667**
91668*************************************************************************
91669** This file contains code used to implement the VACUUM command.
91670**
91671** Most of the code in this file may be omitted by defining the
91672** SQLITE_OMIT_VACUUM macro.
91673*/
91674
91675#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
91676/*
91677** Finalize a prepared statement.  If there was an error, store the
91678** text of the error message in *pzErrMsg.  Return the result code.
91679*/
91680static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
91681  int rc;
91682  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
91683  if( rc ){
91684    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
91685  }
91686  return rc;
91687}
91688
91689/*
91690** Execute zSql on database db. Return an error code.
91691*/
91692static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
91693  sqlite3_stmt *pStmt;
91694  VVA_ONLY( int rc; )
91695  if( !zSql ){
91696    return SQLITE_NOMEM;
91697  }
91698  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
91699    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
91700    return sqlite3_errcode(db);
91701  }
91702  VVA_ONLY( rc = ) sqlite3_step(pStmt);
91703  assert( rc!=SQLITE_ROW );
91704  return vacuumFinalize(db, pStmt, pzErrMsg);
91705}
91706
91707/*
91708** Execute zSql on database db. The statement returns exactly
91709** one column. Execute this as SQL on the same database.
91710*/
91711static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
91712  sqlite3_stmt *pStmt;
91713  int rc;
91714
91715  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
91716  if( rc!=SQLITE_OK ) return rc;
91717
91718  while( SQLITE_ROW==sqlite3_step(pStmt) ){
91719    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
91720    if( rc!=SQLITE_OK ){
91721      vacuumFinalize(db, pStmt, pzErrMsg);
91722      return rc;
91723    }
91724  }
91725
91726  return vacuumFinalize(db, pStmt, pzErrMsg);
91727}
91728
91729/*
91730** The non-standard VACUUM command is used to clean up the database,
91731** collapse free space, etc.  It is modelled after the VACUUM command
91732** in PostgreSQL.
91733**
91734** In version 1.0.x of SQLite, the VACUUM command would call
91735** gdbm_reorganize() on all the database tables.  But beginning
91736** with 2.0.0, SQLite no longer uses GDBM so this command has
91737** become a no-op.
91738*/
91739SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
91740  Vdbe *v = sqlite3GetVdbe(pParse);
91741  if( v ){
91742    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
91743  }
91744  return;
91745}
91746
91747/*
91748** This routine implements the OP_Vacuum opcode of the VDBE.
91749*/
91750SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
91751  int rc = SQLITE_OK;     /* Return code from service routines */
91752  Btree *pMain;           /* The database being vacuumed */
91753  Btree *pTemp;           /* The temporary database we vacuum into */
91754  char *zSql = 0;         /* SQL statements */
91755  int saved_flags;        /* Saved value of the db->flags */
91756  int saved_nChange;      /* Saved value of db->nChange */
91757  int saved_nTotalChange; /* Saved value of db->nTotalChange */
91758  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
91759  Db *pDb = 0;            /* Database to detach at end of vacuum */
91760  int isMemDb;            /* True if vacuuming a :memory: database */
91761  int nRes;               /* Bytes of reserved space at the end of each page */
91762  int nDb;                /* Number of attached databases */
91763
91764  if( !db->autoCommit ){
91765    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
91766    return SQLITE_ERROR;
91767  }
91768
91769  /* Save the current value of the database flags so that it can be
91770  ** restored before returning. Then set the writable-schema flag, and
91771  ** disable CHECK and foreign key constraints.  */
91772  saved_flags = db->flags;
91773  saved_nChange = db->nChange;
91774  saved_nTotalChange = db->nTotalChange;
91775  saved_xTrace = db->xTrace;
91776  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
91777  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
91778  db->xTrace = 0;
91779
91780  pMain = db->aDb[0].pBt;
91781  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
91782
91783  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
91784  ** can be set to 'off' for this file, as it is not recovered if a crash
91785  ** occurs anyway. The integrity of the database is maintained by a
91786  ** (possibly synchronous) transaction opened on the main database before
91787  ** sqlite3BtreeCopyFile() is called.
91788  **
91789  ** An optimisation would be to use a non-journaled pager.
91790  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
91791  ** that actually made the VACUUM run slower.  Very little journalling
91792  ** actually occurs when doing a vacuum since the vacuum_db is initially
91793  ** empty.  Only the journal header is written.  Apparently it takes more
91794  ** time to parse and run the PRAGMA to turn journalling off than it does
91795  ** to write the journal header file.
91796  */
91797  nDb = db->nDb;
91798  if( sqlite3TempInMemory(db) ){
91799    zSql = "ATTACH ':memory:' AS vacuum_db;";
91800  }else{
91801    zSql = "ATTACH '' AS vacuum_db;";
91802  }
91803  rc = execSql(db, pzErrMsg, zSql);
91804  if( db->nDb>nDb ){
91805    pDb = &db->aDb[db->nDb-1];
91806    assert( strcmp(pDb->zName,"vacuum_db")==0 );
91807  }
91808  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91809  pTemp = db->aDb[db->nDb-1].pBt;
91810
91811  /* The call to execSql() to attach the temp database has left the file
91812  ** locked (as there was more than one active statement when the transaction
91813  ** to read the schema was concluded. Unlock it here so that this doesn't
91814  ** cause problems for the call to BtreeSetPageSize() below.  */
91815  sqlite3BtreeCommit(pTemp);
91816
91817  nRes = sqlite3BtreeGetReserve(pMain);
91818
91819  /* A VACUUM cannot change the pagesize of an encrypted database. */
91820#ifdef SQLITE_HAS_CODEC
91821  if( db->nextPagesize ){
91822    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
91823    int nKey;
91824    char *zKey;
91825    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
91826    if( nKey ) db->nextPagesize = 0;
91827  }
91828#endif
91829
91830  /* Do not attempt to change the page size for a WAL database */
91831  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
91832                                               ==PAGER_JOURNALMODE_WAL ){
91833    db->nextPagesize = 0;
91834  }
91835
91836  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
91837   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
91838   || NEVER(db->mallocFailed)
91839  ){
91840    rc = SQLITE_NOMEM;
91841    goto end_of_vacuum;
91842  }
91843  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
91844  if( rc!=SQLITE_OK ){
91845    goto end_of_vacuum;
91846  }
91847
91848#ifndef SQLITE_OMIT_AUTOVACUUM
91849  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
91850                                           sqlite3BtreeGetAutoVacuum(pMain));
91851#endif
91852
91853  /* Begin a transaction */
91854  rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
91855  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91856
91857  /* Query the schema of the main database. Create a mirror schema
91858  ** in the temporary database.
91859  */
91860  rc = execExecSql(db, pzErrMsg,
91861      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
91862      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
91863      "   AND rootpage>0"
91864  );
91865  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91866  rc = execExecSql(db, pzErrMsg,
91867      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
91868      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
91869  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91870  rc = execExecSql(db, pzErrMsg,
91871      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
91872      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
91873  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91874
91875  /* Loop through the tables in the main database. For each, do
91876  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
91877  ** the contents to the temporary database.
91878  */
91879  rc = execExecSql(db, pzErrMsg,
91880      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
91881      "|| ' SELECT * FROM main.' || quote(name) || ';'"
91882      "FROM main.sqlite_master "
91883      "WHERE type = 'table' AND name!='sqlite_sequence' "
91884      "  AND rootpage>0"
91885  );
91886  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91887
91888  /* Copy over the sequence table
91889  */
91890  rc = execExecSql(db, pzErrMsg,
91891      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
91892      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
91893  );
91894  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91895  rc = execExecSql(db, pzErrMsg,
91896      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
91897      "|| ' SELECT * FROM main.' || quote(name) || ';' "
91898      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
91899  );
91900  if( rc!=SQLITE_OK ) goto end_of_vacuum;
91901
91902
91903  /* Copy the triggers, views, and virtual tables from the main database
91904  ** over to the temporary database.  None of these objects has any
91905  ** associated storage, so all we have to do is copy their entries
91906  ** from the SQLITE_MASTER table.
91907  */
91908  rc = execSql(db, pzErrMsg,
91909      "INSERT INTO vacuum_db.sqlite_master "
91910      "  SELECT type, name, tbl_name, rootpage, sql"
91911      "    FROM main.sqlite_master"
91912      "   WHERE type='view' OR type='trigger'"
91913      "      OR (type='table' AND rootpage=0)"
91914  );
91915  if( rc ) goto end_of_vacuum;
91916
91917  /* At this point, unless the main db was completely empty, there is now a
91918  ** transaction open on the vacuum database, but not on the main database.
91919  ** Open a btree level transaction on the main database. This allows a
91920  ** call to sqlite3BtreeCopyFile(). The main database btree level
91921  ** transaction is then committed, so the SQL level never knows it was
91922  ** opened for writing. This way, the SQL transaction used to create the
91923  ** temporary database never needs to be committed.
91924  */
91925  {
91926    u32 meta;
91927    int i;
91928
91929    /* This array determines which meta meta values are preserved in the
91930    ** vacuum.  Even entries are the meta value number and odd entries
91931    ** are an increment to apply to the meta value after the vacuum.
91932    ** The increment is used to increase the schema cookie so that other
91933    ** connections to the same database will know to reread the schema.
91934    */
91935    static const unsigned char aCopy[] = {
91936       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
91937       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
91938       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
91939       BTREE_USER_VERSION,       0,  /* Preserve the user version */
91940    };
91941
91942    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
91943    assert( 1==sqlite3BtreeIsInTrans(pMain) );
91944
91945    /* Copy Btree meta values */
91946    for(i=0; i<ArraySize(aCopy); i+=2){
91947      /* GetMeta() and UpdateMeta() cannot fail in this context because
91948      ** we already have page 1 loaded into cache and marked dirty. */
91949      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
91950      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
91951      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
91952    }
91953
91954    rc = sqlite3BtreeCopyFile(pMain, pTemp);
91955    if( rc!=SQLITE_OK ) goto end_of_vacuum;
91956    rc = sqlite3BtreeCommit(pTemp);
91957    if( rc!=SQLITE_OK ) goto end_of_vacuum;
91958#ifndef SQLITE_OMIT_AUTOVACUUM
91959    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
91960#endif
91961  }
91962
91963  assert( rc==SQLITE_OK );
91964  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
91965
91966end_of_vacuum:
91967  /* Restore the original value of db->flags */
91968  db->flags = saved_flags;
91969  db->nChange = saved_nChange;
91970  db->nTotalChange = saved_nTotalChange;
91971  db->xTrace = saved_xTrace;
91972  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
91973
91974  /* Currently there is an SQL level transaction open on the vacuum
91975  ** database. No locks are held on any other files (since the main file
91976  ** was committed at the btree level). So it safe to end the transaction
91977  ** by manually setting the autoCommit flag to true and detaching the
91978  ** vacuum database. The vacuum_db journal file is deleted when the pager
91979  ** is closed by the DETACH.
91980  */
91981  db->autoCommit = 1;
91982
91983  if( pDb ){
91984    sqlite3BtreeClose(pDb->pBt);
91985    pDb->pBt = 0;
91986    pDb->pSchema = 0;
91987  }
91988
91989  sqlite3ResetInternalSchema(db, 0);
91990
91991  return rc;
91992}
91993#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
91994
91995/************** End of vacuum.c **********************************************/
91996/************** Begin file vtab.c ********************************************/
91997/*
91998** 2006 June 10
91999**
92000** The author disclaims copyright to this source code.  In place of
92001** a legal notice, here is a blessing:
92002**
92003**    May you do good and not evil.
92004**    May you find forgiveness for yourself and forgive others.
92005**    May you share freely, never taking more than you give.
92006**
92007*************************************************************************
92008** This file contains code used to help implement virtual tables.
92009*/
92010#ifndef SQLITE_OMIT_VIRTUALTABLE
92011
92012/*
92013** The actual function that does the work of creating a new module.
92014** This function implements the sqlite3_create_module() and
92015** sqlite3_create_module_v2() interfaces.
92016*/
92017static int createModule(
92018  sqlite3 *db,                    /* Database in which module is registered */
92019  const char *zName,              /* Name assigned to this module */
92020  const sqlite3_module *pModule,  /* The definition of the module */
92021  void *pAux,                     /* Context pointer for xCreate/xConnect */
92022  void (*xDestroy)(void *)        /* Module destructor function */
92023){
92024  int rc, nName;
92025  Module *pMod;
92026
92027  sqlite3_mutex_enter(db->mutex);
92028  nName = sqlite3Strlen30(zName);
92029  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
92030  if( pMod ){
92031    Module *pDel;
92032    char *zCopy = (char *)(&pMod[1]);
92033    memcpy(zCopy, zName, nName+1);
92034    pMod->zName = zCopy;
92035    pMod->pModule = pModule;
92036    pMod->pAux = pAux;
92037    pMod->xDestroy = xDestroy;
92038    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
92039    if( pDel && pDel->xDestroy ){
92040      pDel->xDestroy(pDel->pAux);
92041    }
92042    sqlite3DbFree(db, pDel);
92043    if( pDel==pMod ){
92044      db->mallocFailed = 1;
92045    }
92046    sqlite3ResetInternalSchema(db, 0);
92047  }else if( xDestroy ){
92048    xDestroy(pAux);
92049  }
92050  rc = sqlite3ApiExit(db, SQLITE_OK);
92051  sqlite3_mutex_leave(db->mutex);
92052  return rc;
92053}
92054
92055
92056/*
92057** External API function used to create a new virtual-table module.
92058*/
92059SQLITE_API int sqlite3_create_module(
92060  sqlite3 *db,                    /* Database in which module is registered */
92061  const char *zName,              /* Name assigned to this module */
92062  const sqlite3_module *pModule,  /* The definition of the module */
92063  void *pAux                      /* Context pointer for xCreate/xConnect */
92064){
92065  return createModule(db, zName, pModule, pAux, 0);
92066}
92067
92068/*
92069** External API function used to create a new virtual-table module.
92070*/
92071SQLITE_API int sqlite3_create_module_v2(
92072  sqlite3 *db,                    /* Database in which module is registered */
92073  const char *zName,              /* Name assigned to this module */
92074  const sqlite3_module *pModule,  /* The definition of the module */
92075  void *pAux,                     /* Context pointer for xCreate/xConnect */
92076  void (*xDestroy)(void *)        /* Module destructor function */
92077){
92078  return createModule(db, zName, pModule, pAux, xDestroy);
92079}
92080
92081/*
92082** Lock the virtual table so that it cannot be disconnected.
92083** Locks nest.  Every lock should have a corresponding unlock.
92084** If an unlock is omitted, resources leaks will occur.
92085**
92086** If a disconnect is attempted while a virtual table is locked,
92087** the disconnect is deferred until all locks have been removed.
92088*/
92089SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
92090  pVTab->nRef++;
92091}
92092
92093
92094/*
92095** pTab is a pointer to a Table structure representing a virtual-table.
92096** Return a pointer to the VTable object used by connection db to access
92097** this virtual-table, if one has been created, or NULL otherwise.
92098*/
92099SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
92100  VTable *pVtab;
92101  assert( IsVirtual(pTab) );
92102  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
92103  return pVtab;
92104}
92105
92106/*
92107** Decrement the ref-count on a virtual table object. When the ref-count
92108** reaches zero, call the xDisconnect() method to delete the object.
92109*/
92110SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
92111  sqlite3 *db = pVTab->db;
92112
92113  assert( db );
92114  assert( pVTab->nRef>0 );
92115  assert( sqlite3SafetyCheckOk(db) );
92116
92117  pVTab->nRef--;
92118  if( pVTab->nRef==0 ){
92119    sqlite3_vtab *p = pVTab->pVtab;
92120    if( p ){
92121      p->pModule->xDisconnect(p);
92122    }
92123    sqlite3DbFree(db, pVTab);
92124  }
92125}
92126
92127/*
92128** Table p is a virtual table. This function moves all elements in the
92129** p->pVTable list to the sqlite3.pDisconnect lists of their associated
92130** database connections to be disconnected at the next opportunity.
92131** Except, if argument db is not NULL, then the entry associated with
92132** connection db is left in the p->pVTable list.
92133*/
92134static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
92135  VTable *pRet = 0;
92136  VTable *pVTable = p->pVTable;
92137  p->pVTable = 0;
92138
92139  /* Assert that the mutex (if any) associated with the BtShared database
92140  ** that contains table p is held by the caller. See header comments
92141  ** above function sqlite3VtabUnlockList() for an explanation of why
92142  ** this makes it safe to access the sqlite3.pDisconnect list of any
92143  ** database connection that may have an entry in the p->pVTable list.  */
92144  assert( db==0 ||
92145    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
92146  );
92147
92148  while( pVTable ){
92149    sqlite3 *db2 = pVTable->db;
92150    VTable *pNext = pVTable->pNext;
92151    assert( db2 );
92152    if( db2==db ){
92153      pRet = pVTable;
92154      p->pVTable = pRet;
92155      pRet->pNext = 0;
92156    }else{
92157      pVTable->pNext = db2->pDisconnect;
92158      db2->pDisconnect = pVTable;
92159    }
92160    pVTable = pNext;
92161  }
92162
92163  assert( !db || pRet );
92164  return pRet;
92165}
92166
92167
92168/*
92169** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
92170**
92171** This function may only be called when the mutexes associated with all
92172** shared b-tree databases opened using connection db are held by the
92173** caller. This is done to protect the sqlite3.pDisconnect list. The
92174** sqlite3.pDisconnect list is accessed only as follows:
92175**
92176**   1) By this function. In this case, all BtShared mutexes and the mutex
92177**      associated with the database handle itself must be held.
92178**
92179**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
92180**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
92181**      associated with the database the virtual table is stored in is held
92182**      or, if the virtual table is stored in a non-sharable database, then
92183**      the database handle mutex is held.
92184**
92185** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
92186** by multiple threads. It is thread-safe.
92187*/
92188SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
92189  VTable *p = db->pDisconnect;
92190  db->pDisconnect = 0;
92191
92192  assert( sqlite3BtreeHoldsAllMutexes(db) );
92193  assert( sqlite3_mutex_held(db->mutex) );
92194
92195  if( p ){
92196    sqlite3ExpirePreparedStatements(db);
92197    do {
92198      VTable *pNext = p->pNext;
92199      sqlite3VtabUnlock(p);
92200      p = pNext;
92201    }while( p );
92202  }
92203}
92204
92205/*
92206** Clear any and all virtual-table information from the Table record.
92207** This routine is called, for example, just before deleting the Table
92208** record.
92209**
92210** Since it is a virtual-table, the Table structure contains a pointer
92211** to the head of a linked list of VTable structures. Each VTable
92212** structure is associated with a single sqlite3* user of the schema.
92213** The reference count of the VTable structure associated with database
92214** connection db is decremented immediately (which may lead to the
92215** structure being xDisconnected and free). Any other VTable structures
92216** in the list are moved to the sqlite3.pDisconnect list of the associated
92217** database connection.
92218*/
92219SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
92220  vtabDisconnectAll(0, p);
92221  if( p->azModuleArg ){
92222    int i;
92223    for(i=0; i<p->nModuleArg; i++){
92224      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
92225    }
92226    sqlite3DbFree(p->dbMem, p->azModuleArg);
92227  }
92228}
92229
92230/*
92231** Add a new module argument to pTable->azModuleArg[].
92232** The string is not copied - the pointer is stored.  The
92233** string will be freed automatically when the table is
92234** deleted.
92235*/
92236static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
92237  int i = pTable->nModuleArg++;
92238  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
92239  char **azModuleArg;
92240  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
92241  if( azModuleArg==0 ){
92242    int j;
92243    for(j=0; j<i; j++){
92244      sqlite3DbFree(db, pTable->azModuleArg[j]);
92245    }
92246    sqlite3DbFree(db, zArg);
92247    sqlite3DbFree(db, pTable->azModuleArg);
92248    pTable->nModuleArg = 0;
92249  }else{
92250    azModuleArg[i] = zArg;
92251    azModuleArg[i+1] = 0;
92252  }
92253  pTable->azModuleArg = azModuleArg;
92254}
92255
92256/*
92257** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
92258** statement.  The module name has been parsed, but the optional list
92259** of parameters that follow the module name are still pending.
92260*/
92261SQLITE_PRIVATE void sqlite3VtabBeginParse(
92262  Parse *pParse,        /* Parsing context */
92263  Token *pName1,        /* Name of new table, or database name */
92264  Token *pName2,        /* Name of new table or NULL */
92265  Token *pModuleName    /* Name of the module for the virtual table */
92266){
92267  int iDb;              /* The database the table is being created in */
92268  Table *pTable;        /* The new virtual table */
92269  sqlite3 *db;          /* Database connection */
92270
92271  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
92272  pTable = pParse->pNewTable;
92273  if( pTable==0 ) return;
92274  assert( 0==pTable->pIndex );
92275
92276  db = pParse->db;
92277  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
92278  assert( iDb>=0 );
92279
92280  pTable->tabFlags |= TF_Virtual;
92281  pTable->nModuleArg = 0;
92282  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
92283  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
92284  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
92285  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
92286
92287#ifndef SQLITE_OMIT_AUTHORIZATION
92288  /* Creating a virtual table invokes the authorization callback twice.
92289  ** The first invocation, to obtain permission to INSERT a row into the
92290  ** sqlite_master table, has already been made by sqlite3StartTable().
92291  ** The second call, to obtain permission to create the table, is made now.
92292  */
92293  if( pTable->azModuleArg ){
92294    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
92295            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
92296  }
92297#endif
92298}
92299
92300/*
92301** This routine takes the module argument that has been accumulating
92302** in pParse->zArg[] and appends it to the list of arguments on the
92303** virtual table currently under construction in pParse->pTable.
92304*/
92305static void addArgumentToVtab(Parse *pParse){
92306  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
92307    const char *z = (const char*)pParse->sArg.z;
92308    int n = pParse->sArg.n;
92309    sqlite3 *db = pParse->db;
92310    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
92311  }
92312}
92313
92314/*
92315** The parser calls this routine after the CREATE VIRTUAL TABLE statement
92316** has been completely parsed.
92317*/
92318SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
92319  Table *pTab = pParse->pNewTable;  /* The table being constructed */
92320  sqlite3 *db = pParse->db;         /* The database connection */
92321
92322  if( pTab==0 ) return;
92323  addArgumentToVtab(pParse);
92324  pParse->sArg.z = 0;
92325  if( pTab->nModuleArg<1 ) return;
92326
92327  /* If the CREATE VIRTUAL TABLE statement is being entered for the
92328  ** first time (in other words if the virtual table is actually being
92329  ** created now instead of just being read out of sqlite_master) then
92330  ** do additional initialization work and store the statement text
92331  ** in the sqlite_master table.
92332  */
92333  if( !db->init.busy ){
92334    char *zStmt;
92335    char *zWhere;
92336    int iDb;
92337    Vdbe *v;
92338
92339    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
92340    if( pEnd ){
92341      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
92342    }
92343    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
92344
92345    /* A slot for the record has already been allocated in the
92346    ** SQLITE_MASTER table.  We just need to update that slot with all
92347    ** the information we've collected.
92348    **
92349    ** The VM register number pParse->regRowid holds the rowid of an
92350    ** entry in the sqlite_master table tht was created for this vtab
92351    ** by sqlite3StartTable().
92352    */
92353    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92354    sqlite3NestedParse(pParse,
92355      "UPDATE %Q.%s "
92356         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
92357       "WHERE rowid=#%d",
92358      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
92359      pTab->zName,
92360      pTab->zName,
92361      zStmt,
92362      pParse->regRowid
92363    );
92364    sqlite3DbFree(db, zStmt);
92365    v = sqlite3GetVdbe(pParse);
92366    sqlite3ChangeCookie(pParse, iDb);
92367
92368    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92369    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
92370    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
92371    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
92372                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
92373  }
92374
92375  /* If we are rereading the sqlite_master table create the in-memory
92376  ** record of the table. The xConnect() method is not called until
92377  ** the first time the virtual table is used in an SQL statement. This
92378  ** allows a schema that contains virtual tables to be loaded before
92379  ** the required virtual table implementations are registered.  */
92380  else {
92381    Table *pOld;
92382    Schema *pSchema = pTab->pSchema;
92383    const char *zName = pTab->zName;
92384    int nName = sqlite3Strlen30(zName);
92385    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
92386    if( pOld ){
92387      db->mallocFailed = 1;
92388      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
92389      return;
92390    }
92391    pSchema->db = pParse->db;
92392    pParse->pNewTable = 0;
92393  }
92394}
92395
92396/*
92397** The parser calls this routine when it sees the first token
92398** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
92399*/
92400SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
92401  addArgumentToVtab(pParse);
92402  pParse->sArg.z = 0;
92403  pParse->sArg.n = 0;
92404}
92405
92406/*
92407** The parser calls this routine for each token after the first token
92408** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
92409*/
92410SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
92411  Token *pArg = &pParse->sArg;
92412  if( pArg->z==0 ){
92413    pArg->z = p->z;
92414    pArg->n = p->n;
92415  }else{
92416    assert(pArg->z < p->z);
92417    pArg->n = (int)(&p->z[p->n] - pArg->z);
92418  }
92419}
92420
92421/*
92422** Invoke a virtual table constructor (either xCreate or xConnect). The
92423** pointer to the function to invoke is passed as the fourth parameter
92424** to this procedure.
92425*/
92426static int vtabCallConstructor(
92427  sqlite3 *db,
92428  Table *pTab,
92429  Module *pMod,
92430  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
92431  char **pzErr
92432){
92433  VTable *pVTable;
92434  int rc;
92435  const char *const*azArg = (const char *const*)pTab->azModuleArg;
92436  int nArg = pTab->nModuleArg;
92437  char *zErr = 0;
92438  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
92439
92440  if( !zModuleName ){
92441    return SQLITE_NOMEM;
92442  }
92443
92444  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
92445  if( !pVTable ){
92446    sqlite3DbFree(db, zModuleName);
92447    return SQLITE_NOMEM;
92448  }
92449  pVTable->db = db;
92450  pVTable->pMod = pMod;
92451
92452  assert( !db->pVTab );
92453  assert( xConstruct );
92454  db->pVTab = pTab;
92455
92456  /* Invoke the virtual table constructor */
92457  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
92458  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
92459
92460  if( SQLITE_OK!=rc ){
92461    if( zErr==0 ){
92462      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
92463    }else {
92464      *pzErr = sqlite3MPrintf(db, "%s", zErr);
92465      sqlite3DbFree(db, zErr);
92466    }
92467    sqlite3DbFree(db, pVTable);
92468  }else if( ALWAYS(pVTable->pVtab) ){
92469    /* Justification of ALWAYS():  A correct vtab constructor must allocate
92470    ** the sqlite3_vtab object if successful.  */
92471    pVTable->pVtab->pModule = pMod->pModule;
92472    pVTable->nRef = 1;
92473    if( db->pVTab ){
92474      const char *zFormat = "vtable constructor did not declare schema: %s";
92475      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
92476      sqlite3VtabUnlock(pVTable);
92477      rc = SQLITE_ERROR;
92478    }else{
92479      int iCol;
92480      /* If everything went according to plan, link the new VTable structure
92481      ** into the linked list headed by pTab->pVTable. Then loop through the
92482      ** columns of the table to see if any of them contain the token "hidden".
92483      ** If so, set the Column.isHidden flag and remove the token from
92484      ** the type string.  */
92485      pVTable->pNext = pTab->pVTable;
92486      pTab->pVTable = pVTable;
92487
92488      for(iCol=0; iCol<pTab->nCol; iCol++){
92489        char *zType = pTab->aCol[iCol].zType;
92490        int nType;
92491        int i = 0;
92492        if( !zType ) continue;
92493        nType = sqlite3Strlen30(zType);
92494        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
92495          for(i=0; i<nType; i++){
92496            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
92497             && (zType[i+7]=='\0' || zType[i+7]==' ')
92498            ){
92499              i++;
92500              break;
92501            }
92502          }
92503        }
92504        if( i<nType ){
92505          int j;
92506          int nDel = 6 + (zType[i+6] ? 1 : 0);
92507          for(j=i; (j+nDel)<=nType; j++){
92508            zType[j] = zType[j+nDel];
92509          }
92510          if( zType[i]=='\0' && i>0 ){
92511            assert(zType[i-1]==' ');
92512            zType[i-1] = '\0';
92513          }
92514          pTab->aCol[iCol].isHidden = 1;
92515        }
92516      }
92517    }
92518  }
92519
92520  sqlite3DbFree(db, zModuleName);
92521  db->pVTab = 0;
92522  return rc;
92523}
92524
92525/*
92526** This function is invoked by the parser to call the xConnect() method
92527** of the virtual table pTab. If an error occurs, an error code is returned
92528** and an error left in pParse.
92529**
92530** This call is a no-op if table pTab is not a virtual table.
92531*/
92532SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
92533  sqlite3 *db = pParse->db;
92534  const char *zMod;
92535  Module *pMod;
92536  int rc;
92537
92538  assert( pTab );
92539  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
92540    return SQLITE_OK;
92541  }
92542
92543  /* Locate the required virtual table module */
92544  zMod = pTab->azModuleArg[0];
92545  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92546
92547  if( !pMod ){
92548    const char *zModule = pTab->azModuleArg[0];
92549    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
92550    rc = SQLITE_ERROR;
92551  }else{
92552    char *zErr = 0;
92553    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
92554    if( rc!=SQLITE_OK ){
92555      sqlite3ErrorMsg(pParse, "%s", zErr);
92556    }
92557    sqlite3DbFree(db, zErr);
92558  }
92559
92560  return rc;
92561}
92562
92563/*
92564** Add the virtual table pVTab to the array sqlite3.aVTrans[].
92565*/
92566static int addToVTrans(sqlite3 *db, VTable *pVTab){
92567  const int ARRAY_INCR = 5;
92568
92569  /* Grow the sqlite3.aVTrans array if required */
92570  if( (db->nVTrans%ARRAY_INCR)==0 ){
92571    VTable **aVTrans;
92572    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
92573    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
92574    if( !aVTrans ){
92575      return SQLITE_NOMEM;
92576    }
92577    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
92578    db->aVTrans = aVTrans;
92579  }
92580
92581  /* Add pVtab to the end of sqlite3.aVTrans */
92582  db->aVTrans[db->nVTrans++] = pVTab;
92583  sqlite3VtabLock(pVTab);
92584  return SQLITE_OK;
92585}
92586
92587/*
92588** This function is invoked by the vdbe to call the xCreate method
92589** of the virtual table named zTab in database iDb.
92590**
92591** If an error occurs, *pzErr is set to point an an English language
92592** description of the error and an SQLITE_XXX error code is returned.
92593** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
92594*/
92595SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
92596  int rc = SQLITE_OK;
92597  Table *pTab;
92598  Module *pMod;
92599  const char *zMod;
92600
92601  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
92602  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
92603
92604  /* Locate the required virtual table module */
92605  zMod = pTab->azModuleArg[0];
92606  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92607
92608  /* If the module has been registered and includes a Create method,
92609  ** invoke it now. If the module has not been registered, return an
92610  ** error. Otherwise, do nothing.
92611  */
92612  if( !pMod ){
92613    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
92614    rc = SQLITE_ERROR;
92615  }else{
92616    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
92617  }
92618
92619  /* Justification of ALWAYS():  The xConstructor method is required to
92620  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
92621  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
92622      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
92623  }
92624
92625  return rc;
92626}
92627
92628/*
92629** This function is used to set the schema of a virtual table.  It is only
92630** valid to call this function from within the xCreate() or xConnect() of a
92631** virtual table module.
92632*/
92633SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
92634  Parse *pParse;
92635
92636  int rc = SQLITE_OK;
92637  Table *pTab;
92638  char *zErr = 0;
92639
92640  sqlite3_mutex_enter(db->mutex);
92641  pTab = db->pVTab;
92642  if( !pTab ){
92643    sqlite3Error(db, SQLITE_MISUSE, 0);
92644    sqlite3_mutex_leave(db->mutex);
92645    return SQLITE_MISUSE_BKPT;
92646  }
92647  assert( (pTab->tabFlags & TF_Virtual)!=0 );
92648
92649  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
92650  if( pParse==0 ){
92651    rc = SQLITE_NOMEM;
92652  }else{
92653    pParse->declareVtab = 1;
92654    pParse->db = db;
92655    pParse->nQueryLoop = 1;
92656
92657    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
92658     && pParse->pNewTable
92659     && !db->mallocFailed
92660     && !pParse->pNewTable->pSelect
92661     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
92662    ){
92663      if( !pTab->aCol ){
92664        pTab->aCol = pParse->pNewTable->aCol;
92665        pTab->nCol = pParse->pNewTable->nCol;
92666        pParse->pNewTable->nCol = 0;
92667        pParse->pNewTable->aCol = 0;
92668      }
92669      db->pVTab = 0;
92670    }else{
92671      sqlite3Error(db, SQLITE_ERROR, zErr);
92672      sqlite3DbFree(db, zErr);
92673      rc = SQLITE_ERROR;
92674    }
92675    pParse->declareVtab = 0;
92676
92677    if( pParse->pVdbe ){
92678      sqlite3VdbeFinalize(pParse->pVdbe);
92679    }
92680    sqlite3DeleteTable(pParse->pNewTable);
92681    sqlite3StackFree(db, pParse);
92682  }
92683
92684  assert( (rc&0xff)==rc );
92685  rc = sqlite3ApiExit(db, rc);
92686  sqlite3_mutex_leave(db->mutex);
92687  return rc;
92688}
92689
92690/*
92691** This function is invoked by the vdbe to call the xDestroy method
92692** of the virtual table named zTab in database iDb. This occurs
92693** when a DROP TABLE is mentioned.
92694**
92695** This call is a no-op if zTab is not a virtual table.
92696*/
92697SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
92698  int rc = SQLITE_OK;
92699  Table *pTab;
92700
92701  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
92702  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
92703    VTable *p = vtabDisconnectAll(db, pTab);
92704
92705    assert( rc==SQLITE_OK );
92706    rc = p->pMod->pModule->xDestroy(p->pVtab);
92707
92708    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
92709    if( rc==SQLITE_OK ){
92710      assert( pTab->pVTable==p && p->pNext==0 );
92711      p->pVtab = 0;
92712      pTab->pVTable = 0;
92713      sqlite3VtabUnlock(p);
92714    }
92715  }
92716
92717  return rc;
92718}
92719
92720/*
92721** This function invokes either the xRollback or xCommit method
92722** of each of the virtual tables in the sqlite3.aVTrans array. The method
92723** called is identified by the second argument, "offset", which is
92724** the offset of the method to call in the sqlite3_module structure.
92725**
92726** The array is cleared after invoking the callbacks.
92727*/
92728static void callFinaliser(sqlite3 *db, int offset){
92729  int i;
92730  if( db->aVTrans ){
92731    for(i=0; i<db->nVTrans; i++){
92732      VTable *pVTab = db->aVTrans[i];
92733      sqlite3_vtab *p = pVTab->pVtab;
92734      if( p ){
92735        int (*x)(sqlite3_vtab *);
92736        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
92737        if( x ) x(p);
92738      }
92739      sqlite3VtabUnlock(pVTab);
92740    }
92741    sqlite3DbFree(db, db->aVTrans);
92742    db->nVTrans = 0;
92743    db->aVTrans = 0;
92744  }
92745}
92746
92747/*
92748** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
92749** array. Return the error code for the first error that occurs, or
92750** SQLITE_OK if all xSync operations are successful.
92751**
92752** Set *pzErrmsg to point to a buffer that should be released using
92753** sqlite3DbFree() containing an error message, if one is available.
92754*/
92755SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
92756  int i;
92757  int rc = SQLITE_OK;
92758  VTable **aVTrans = db->aVTrans;
92759
92760  db->aVTrans = 0;
92761  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
92762    int (*x)(sqlite3_vtab *);
92763    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
92764    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
92765      rc = x(pVtab);
92766      sqlite3DbFree(db, *pzErrmsg);
92767      *pzErrmsg = pVtab->zErrMsg;
92768      pVtab->zErrMsg = 0;
92769    }
92770  }
92771  db->aVTrans = aVTrans;
92772  return rc;
92773}
92774
92775/*
92776** Invoke the xRollback method of all virtual tables in the
92777** sqlite3.aVTrans array. Then clear the array itself.
92778*/
92779SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
92780  callFinaliser(db, offsetof(sqlite3_module,xRollback));
92781  return SQLITE_OK;
92782}
92783
92784/*
92785** Invoke the xCommit method of all virtual tables in the
92786** sqlite3.aVTrans array. Then clear the array itself.
92787*/
92788SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
92789  callFinaliser(db, offsetof(sqlite3_module,xCommit));
92790  return SQLITE_OK;
92791}
92792
92793/*
92794** If the virtual table pVtab supports the transaction interface
92795** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
92796** not currently open, invoke the xBegin method now.
92797**
92798** If the xBegin call is successful, place the sqlite3_vtab pointer
92799** in the sqlite3.aVTrans array.
92800*/
92801SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
92802  int rc = SQLITE_OK;
92803  const sqlite3_module *pModule;
92804
92805  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
92806  ** than zero, then this function is being called from within a
92807  ** virtual module xSync() callback. It is illegal to write to
92808  ** virtual module tables in this case, so return SQLITE_LOCKED.
92809  */
92810  if( sqlite3VtabInSync(db) ){
92811    return SQLITE_LOCKED;
92812  }
92813  if( !pVTab ){
92814    return SQLITE_OK;
92815  }
92816  pModule = pVTab->pVtab->pModule;
92817
92818  if( pModule->xBegin ){
92819    int i;
92820
92821
92822    /* If pVtab is already in the aVTrans array, return early */
92823    for(i=0; i<db->nVTrans; i++){
92824      if( db->aVTrans[i]==pVTab ){
92825        return SQLITE_OK;
92826      }
92827    }
92828
92829    /* Invoke the xBegin method */
92830    rc = pModule->xBegin(pVTab->pVtab);
92831    if( rc==SQLITE_OK ){
92832      rc = addToVTrans(db, pVTab);
92833    }
92834  }
92835  return rc;
92836}
92837
92838/*
92839** The first parameter (pDef) is a function implementation.  The
92840** second parameter (pExpr) is the first argument to this function.
92841** If pExpr is a column in a virtual table, then let the virtual
92842** table implementation have an opportunity to overload the function.
92843**
92844** This routine is used to allow virtual table implementations to
92845** overload MATCH, LIKE, GLOB, and REGEXP operators.
92846**
92847** Return either the pDef argument (indicating no change) or a
92848** new FuncDef structure that is marked as ephemeral using the
92849** SQLITE_FUNC_EPHEM flag.
92850*/
92851SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
92852  sqlite3 *db,    /* Database connection for reporting malloc problems */
92853  FuncDef *pDef,  /* Function to possibly overload */
92854  int nArg,       /* Number of arguments to the function */
92855  Expr *pExpr     /* First argument to the function */
92856){
92857  Table *pTab;
92858  sqlite3_vtab *pVtab;
92859  sqlite3_module *pMod;
92860  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
92861  void *pArg = 0;
92862  FuncDef *pNew;
92863  int rc = 0;
92864  char *zLowerName;
92865  unsigned char *z;
92866
92867
92868  /* Check to see the left operand is a column in a virtual table */
92869  if( NEVER(pExpr==0) ) return pDef;
92870  if( pExpr->op!=TK_COLUMN ) return pDef;
92871  pTab = pExpr->pTab;
92872  if( NEVER(pTab==0) ) return pDef;
92873  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
92874  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
92875  assert( pVtab!=0 );
92876  assert( pVtab->pModule!=0 );
92877  pMod = (sqlite3_module *)pVtab->pModule;
92878  if( pMod->xFindFunction==0 ) return pDef;
92879
92880  /* Call the xFindFunction method on the virtual table implementation
92881  ** to see if the implementation wants to overload this function
92882  */
92883  zLowerName = sqlite3DbStrDup(db, pDef->zName);
92884  if( zLowerName ){
92885    for(z=(unsigned char*)zLowerName; *z; z++){
92886      *z = sqlite3UpperToLower[*z];
92887    }
92888    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
92889    sqlite3DbFree(db, zLowerName);
92890  }
92891  if( rc==0 ){
92892    return pDef;
92893  }
92894
92895  /* Create a new ephemeral function definition for the overloaded
92896  ** function */
92897  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
92898                             + sqlite3Strlen30(pDef->zName) + 1);
92899  if( pNew==0 ){
92900    return pDef;
92901  }
92902  *pNew = *pDef;
92903  pNew->zName = (char *)&pNew[1];
92904  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
92905  pNew->xFunc = xFunc;
92906  pNew->pUserData = pArg;
92907  pNew->flags |= SQLITE_FUNC_EPHEM;
92908  return pNew;
92909}
92910
92911/*
92912** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
92913** array so that an OP_VBegin will get generated for it.  Add pTab to the
92914** array if it is missing.  If pTab is already in the array, this routine
92915** is a no-op.
92916*/
92917SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
92918  Parse *pToplevel = sqlite3ParseToplevel(pParse);
92919  int i, n;
92920  Table **apVtabLock;
92921
92922  assert( IsVirtual(pTab) );
92923  for(i=0; i<pToplevel->nVtabLock; i++){
92924    if( pTab==pToplevel->apVtabLock[i] ) return;
92925  }
92926  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
92927  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
92928  if( apVtabLock ){
92929    pToplevel->apVtabLock = apVtabLock;
92930    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
92931  }else{
92932    pToplevel->db->mallocFailed = 1;
92933  }
92934}
92935
92936#endif /* SQLITE_OMIT_VIRTUALTABLE */
92937
92938/************** End of vtab.c ************************************************/
92939/************** Begin file where.c *******************************************/
92940/*
92941** 2001 September 15
92942**
92943** The author disclaims copyright to this source code.  In place of
92944** a legal notice, here is a blessing:
92945**
92946**    May you do good and not evil.
92947**    May you find forgiveness for yourself and forgive others.
92948**    May you share freely, never taking more than you give.
92949**
92950*************************************************************************
92951** This module contains C code that generates VDBE code used to process
92952** the WHERE clause of SQL statements.  This module is responsible for
92953** generating the code that loops through a table looking for applicable
92954** rows.  Indices are selected and used to speed the search when doing
92955** so is applicable.  Because this module is responsible for selecting
92956** indices, you might also think of this module as the "query optimizer".
92957*/
92958
92959/*
92960** Trace output macros
92961*/
92962#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
92963SQLITE_PRIVATE int sqlite3WhereTrace = 0;
92964#endif
92965#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
92966# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
92967#else
92968# define WHERETRACE(X)
92969#endif
92970
92971/* Forward reference
92972*/
92973typedef struct WhereClause WhereClause;
92974typedef struct WhereMaskSet WhereMaskSet;
92975typedef struct WhereOrInfo WhereOrInfo;
92976typedef struct WhereAndInfo WhereAndInfo;
92977typedef struct WhereCost WhereCost;
92978
92979/*
92980** The query generator uses an array of instances of this structure to
92981** help it analyze the subexpressions of the WHERE clause.  Each WHERE
92982** clause subexpression is separated from the others by AND operators,
92983** usually, or sometimes subexpressions separated by OR.
92984**
92985** All WhereTerms are collected into a single WhereClause structure.
92986** The following identity holds:
92987**
92988**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
92989**
92990** When a term is of the form:
92991**
92992**              X <op> <expr>
92993**
92994** where X is a column name and <op> is one of certain operators,
92995** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
92996** cursor number and column number for X.  WhereTerm.eOperator records
92997** the <op> using a bitmask encoding defined by WO_xxx below.  The
92998** use of a bitmask encoding for the operator allows us to search
92999** quickly for terms that match any of several different operators.
93000**
93001** A WhereTerm might also be two or more subterms connected by OR:
93002**
93003**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
93004**
93005** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
93006** and the WhereTerm.u.pOrInfo field points to auxiliary information that
93007** is collected about the
93008**
93009** If a term in the WHERE clause does not match either of the two previous
93010** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
93011** to the original subexpression content and wtFlags is set up appropriately
93012** but no other fields in the WhereTerm object are meaningful.
93013**
93014** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
93015** but they do so indirectly.  A single WhereMaskSet structure translates
93016** cursor number into bits and the translated bit is stored in the prereq
93017** fields.  The translation is used in order to maximize the number of
93018** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
93019** spread out over the non-negative integers.  For example, the cursor
93020** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
93021** translates these sparse cursor numbers into consecutive integers
93022** beginning with 0 in order to make the best possible use of the available
93023** bits in the Bitmask.  So, in the example above, the cursor numbers
93024** would be mapped into integers 0 through 7.
93025**
93026** The number of terms in a join is limited by the number of bits
93027** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
93028** is only able to process joins with 64 or fewer tables.
93029*/
93030typedef struct WhereTerm WhereTerm;
93031struct WhereTerm {
93032  Expr *pExpr;            /* Pointer to the subexpression that is this term */
93033  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
93034  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
93035  union {
93036    int leftColumn;         /* Column number of X in "X <op> <expr>" */
93037    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
93038    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
93039  } u;
93040  u16 eOperator;          /* A WO_xx value describing <op> */
93041  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
93042  u8 nChild;              /* Number of children that must disable us */
93043  WhereClause *pWC;       /* The clause this term is part of */
93044  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
93045  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
93046};
93047
93048/*
93049** Allowed values of WhereTerm.wtFlags
93050*/
93051#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
93052#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
93053#define TERM_CODED      0x04   /* This term is already coded */
93054#define TERM_COPIED     0x08   /* Has a child */
93055#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
93056#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
93057#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
93058
93059/*
93060** An instance of the following structure holds all information about a
93061** WHERE clause.  Mostly this is a container for one or more WhereTerms.
93062*/
93063struct WhereClause {
93064  Parse *pParse;           /* The parser context */
93065  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
93066  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
93067  u8 op;                   /* Split operator.  TK_AND or TK_OR */
93068  int nTerm;               /* Number of terms */
93069  int nSlot;               /* Number of entries in a[] */
93070  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
93071#if defined(SQLITE_SMALL_STACK)
93072  WhereTerm aStatic[1];    /* Initial static space for a[] */
93073#else
93074  WhereTerm aStatic[8];    /* Initial static space for a[] */
93075#endif
93076};
93077
93078/*
93079** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
93080** a dynamically allocated instance of the following structure.
93081*/
93082struct WhereOrInfo {
93083  WhereClause wc;          /* Decomposition into subterms */
93084  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
93085};
93086
93087/*
93088** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
93089** a dynamically allocated instance of the following structure.
93090*/
93091struct WhereAndInfo {
93092  WhereClause wc;          /* The subexpression broken out */
93093};
93094
93095/*
93096** An instance of the following structure keeps track of a mapping
93097** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
93098**
93099** The VDBE cursor numbers are small integers contained in
93100** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
93101** clause, the cursor numbers might not begin with 0 and they might
93102** contain gaps in the numbering sequence.  But we want to make maximum
93103** use of the bits in our bitmasks.  This structure provides a mapping
93104** from the sparse cursor numbers into consecutive integers beginning
93105** with 0.
93106**
93107** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
93108** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
93109**
93110** For example, if the WHERE clause expression used these VDBE
93111** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
93112** would map those cursor numbers into bits 0 through 5.
93113**
93114** Note that the mapping is not necessarily ordered.  In the example
93115** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
93116** 57->5, 73->4.  Or one of 719 other combinations might be used. It
93117** does not really matter.  What is important is that sparse cursor
93118** numbers all get mapped into bit numbers that begin with 0 and contain
93119** no gaps.
93120*/
93121struct WhereMaskSet {
93122  int n;                        /* Number of assigned cursor values */
93123  int ix[BMS];                  /* Cursor assigned to each bit */
93124};
93125
93126/*
93127** A WhereCost object records a lookup strategy and the estimated
93128** cost of pursuing that strategy.
93129*/
93130struct WhereCost {
93131  WherePlan plan;    /* The lookup strategy */
93132  double rCost;      /* Overall cost of pursuing this search strategy */
93133  double nRow;       /* Estimated number of output rows */
93134  Bitmask used;      /* Bitmask of cursors used by this plan */
93135};
93136
93137/*
93138** Bitmasks for the operators that indices are able to exploit.  An
93139** OR-ed combination of these values can be used when searching for
93140** terms in the where clause.
93141*/
93142#define WO_IN     0x001
93143#define WO_EQ     0x002
93144#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
93145#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
93146#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
93147#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
93148#define WO_MATCH  0x040
93149#define WO_ISNULL 0x080
93150#define WO_OR     0x100       /* Two or more OR-connected terms */
93151#define WO_AND    0x200       /* Two or more AND-connected terms */
93152
93153#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
93154#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
93155
93156/*
93157** Value for wsFlags returned by bestIndex() and stored in
93158** WhereLevel.wsFlags.  These flags determine which search
93159** strategies are appropriate.
93160**
93161** The least significant 12 bits is reserved as a mask for WO_ values above.
93162** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
93163** But if the table is the right table of a left join, WhereLevel.wsFlags
93164** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
93165** the "op" parameter to findTerm when we are resolving equality constraints.
93166** ISNULL constraints will then not be used on the right table of a left
93167** join.  Tickets #2177 and #2189.
93168*/
93169#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
93170#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
93171#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
93172#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
93173#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
93174#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
93175#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
93176#define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
93177#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
93178#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
93179#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
93180#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
93181#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
93182#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
93183#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
93184#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
93185#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
93186#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
93187
93188/*
93189** Initialize a preallocated WhereClause structure.
93190*/
93191static void whereClauseInit(
93192  WhereClause *pWC,        /* The WhereClause to be initialized */
93193  Parse *pParse,           /* The parsing context */
93194  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
93195){
93196  pWC->pParse = pParse;
93197  pWC->pMaskSet = pMaskSet;
93198  pWC->nTerm = 0;
93199  pWC->nSlot = ArraySize(pWC->aStatic);
93200  pWC->a = pWC->aStatic;
93201  pWC->vmask = 0;
93202}
93203
93204/* Forward reference */
93205static void whereClauseClear(WhereClause*);
93206
93207/*
93208** Deallocate all memory associated with a WhereOrInfo object.
93209*/
93210static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
93211  whereClauseClear(&p->wc);
93212  sqlite3DbFree(db, p);
93213}
93214
93215/*
93216** Deallocate all memory associated with a WhereAndInfo object.
93217*/
93218static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
93219  whereClauseClear(&p->wc);
93220  sqlite3DbFree(db, p);
93221}
93222
93223/*
93224** Deallocate a WhereClause structure.  The WhereClause structure
93225** itself is not freed.  This routine is the inverse of whereClauseInit().
93226*/
93227static void whereClauseClear(WhereClause *pWC){
93228  int i;
93229  WhereTerm *a;
93230  sqlite3 *db = pWC->pParse->db;
93231  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
93232    if( a->wtFlags & TERM_DYNAMIC ){
93233      sqlite3ExprDelete(db, a->pExpr);
93234    }
93235    if( a->wtFlags & TERM_ORINFO ){
93236      whereOrInfoDelete(db, a->u.pOrInfo);
93237    }else if( a->wtFlags & TERM_ANDINFO ){
93238      whereAndInfoDelete(db, a->u.pAndInfo);
93239    }
93240  }
93241  if( pWC->a!=pWC->aStatic ){
93242    sqlite3DbFree(db, pWC->a);
93243  }
93244}
93245
93246/*
93247** Add a single new WhereTerm entry to the WhereClause object pWC.
93248** The new WhereTerm object is constructed from Expr p and with wtFlags.
93249** The index in pWC->a[] of the new WhereTerm is returned on success.
93250** 0 is returned if the new WhereTerm could not be added due to a memory
93251** allocation error.  The memory allocation failure will be recorded in
93252** the db->mallocFailed flag so that higher-level functions can detect it.
93253**
93254** This routine will increase the size of the pWC->a[] array as necessary.
93255**
93256** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
93257** for freeing the expression p is assumed by the WhereClause object pWC.
93258** This is true even if this routine fails to allocate a new WhereTerm.
93259**
93260** WARNING:  This routine might reallocate the space used to store
93261** WhereTerms.  All pointers to WhereTerms should be invalidated after
93262** calling this routine.  Such pointers may be reinitialized by referencing
93263** the pWC->a[] array.
93264*/
93265static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
93266  WhereTerm *pTerm;
93267  int idx;
93268  if( pWC->nTerm>=pWC->nSlot ){
93269    WhereTerm *pOld = pWC->a;
93270    sqlite3 *db = pWC->pParse->db;
93271    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
93272    if( pWC->a==0 ){
93273      if( wtFlags & TERM_DYNAMIC ){
93274        sqlite3ExprDelete(db, p);
93275      }
93276      pWC->a = pOld;
93277      return 0;
93278    }
93279    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
93280    if( pOld!=pWC->aStatic ){
93281      sqlite3DbFree(db, pOld);
93282    }
93283    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
93284  }
93285  pTerm = &pWC->a[idx = pWC->nTerm++];
93286  pTerm->pExpr = p;
93287  pTerm->wtFlags = wtFlags;
93288  pTerm->pWC = pWC;
93289  pTerm->iParent = -1;
93290  return idx;
93291}
93292
93293/*
93294** This routine identifies subexpressions in the WHERE clause where
93295** each subexpression is separated by the AND operator or some other
93296** operator specified in the op parameter.  The WhereClause structure
93297** is filled with pointers to subexpressions.  For example:
93298**
93299**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
93300**           \________/     \_______________/     \________________/
93301**            slot[0]            slot[1]               slot[2]
93302**
93303** The original WHERE clause in pExpr is unaltered.  All this routine
93304** does is make slot[] entries point to substructure within pExpr.
93305**
93306** In the previous sentence and in the diagram, "slot[]" refers to
93307** the WhereClause.a[] array.  The slot[] array grows as needed to contain
93308** all terms of the WHERE clause.
93309*/
93310static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
93311  pWC->op = (u8)op;
93312  if( pExpr==0 ) return;
93313  if( pExpr->op!=op ){
93314    whereClauseInsert(pWC, pExpr, 0);
93315  }else{
93316    whereSplit(pWC, pExpr->pLeft, op);
93317    whereSplit(pWC, pExpr->pRight, op);
93318  }
93319}
93320
93321/*
93322** Initialize an expression mask set (a WhereMaskSet object)
93323*/
93324#define initMaskSet(P)  memset(P, 0, sizeof(*P))
93325
93326/*
93327** Return the bitmask for the given cursor number.  Return 0 if
93328** iCursor is not in the set.
93329*/
93330static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
93331  int i;
93332  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
93333  for(i=0; i<pMaskSet->n; i++){
93334    if( pMaskSet->ix[i]==iCursor ){
93335      return ((Bitmask)1)<<i;
93336    }
93337  }
93338  return 0;
93339}
93340
93341/*
93342** Create a new mask for cursor iCursor.
93343**
93344** There is one cursor per table in the FROM clause.  The number of
93345** tables in the FROM clause is limited by a test early in the
93346** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
93347** array will never overflow.
93348*/
93349static void createMask(WhereMaskSet *pMaskSet, int iCursor){
93350  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
93351  pMaskSet->ix[pMaskSet->n++] = iCursor;
93352}
93353
93354/*
93355** This routine walks (recursively) an expression tree and generates
93356** a bitmask indicating which tables are used in that expression
93357** tree.
93358**
93359** In order for this routine to work, the calling function must have
93360** previously invoked sqlite3ResolveExprNames() on the expression.  See
93361** the header comment on that routine for additional information.
93362** The sqlite3ResolveExprNames() routines looks for column names and
93363** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
93364** the VDBE cursor number of the table.  This routine just has to
93365** translate the cursor numbers into bitmask values and OR all
93366** the bitmasks together.
93367*/
93368static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
93369static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
93370static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
93371  Bitmask mask = 0;
93372  if( p==0 ) return 0;
93373  if( p->op==TK_COLUMN ){
93374    mask = getMask(pMaskSet, p->iTable);
93375    return mask;
93376  }
93377  mask = exprTableUsage(pMaskSet, p->pRight);
93378  mask |= exprTableUsage(pMaskSet, p->pLeft);
93379  if( ExprHasProperty(p, EP_xIsSelect) ){
93380    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
93381  }else{
93382    mask |= exprListTableUsage(pMaskSet, p->x.pList);
93383  }
93384  return mask;
93385}
93386static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
93387  int i;
93388  Bitmask mask = 0;
93389  if( pList ){
93390    for(i=0; i<pList->nExpr; i++){
93391      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
93392    }
93393  }
93394  return mask;
93395}
93396static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
93397  Bitmask mask = 0;
93398  while( pS ){
93399    mask |= exprListTableUsage(pMaskSet, pS->pEList);
93400    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
93401    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
93402    mask |= exprTableUsage(pMaskSet, pS->pWhere);
93403    mask |= exprTableUsage(pMaskSet, pS->pHaving);
93404    pS = pS->pPrior;
93405  }
93406  return mask;
93407}
93408
93409/*
93410** Return TRUE if the given operator is one of the operators that is
93411** allowed for an indexable WHERE clause term.  The allowed operators are
93412** "=", "<", ">", "<=", ">=", and "IN".
93413*/
93414static int allowedOp(int op){
93415  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
93416  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
93417  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
93418  assert( TK_GE==TK_EQ+4 );
93419  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
93420}
93421
93422/*
93423** Swap two objects of type TYPE.
93424*/
93425#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
93426
93427/*
93428** Commute a comparison operator.  Expressions of the form "X op Y"
93429** are converted into "Y op X".
93430**
93431** If a collation sequence is associated with either the left or right
93432** side of the comparison, it remains associated with the same side after
93433** the commutation. So "Y collate NOCASE op X" becomes
93434** "X collate NOCASE op Y". This is because any collation sequence on
93435** the left hand side of a comparison overrides any collation sequence
93436** attached to the right. For the same reason the EP_ExpCollate flag
93437** is not commuted.
93438*/
93439static void exprCommute(Parse *pParse, Expr *pExpr){
93440  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
93441  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
93442  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
93443  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
93444  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
93445  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
93446  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
93447  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
93448  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
93449  if( pExpr->op>=TK_GT ){
93450    assert( TK_LT==TK_GT+2 );
93451    assert( TK_GE==TK_LE+2 );
93452    assert( TK_GT>TK_EQ );
93453    assert( TK_GT<TK_LE );
93454    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
93455    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
93456  }
93457}
93458
93459/*
93460** Translate from TK_xx operator to WO_xx bitmask.
93461*/
93462static u16 operatorMask(int op){
93463  u16 c;
93464  assert( allowedOp(op) );
93465  if( op==TK_IN ){
93466    c = WO_IN;
93467  }else if( op==TK_ISNULL ){
93468    c = WO_ISNULL;
93469  }else{
93470    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
93471    c = (u16)(WO_EQ<<(op-TK_EQ));
93472  }
93473  assert( op!=TK_ISNULL || c==WO_ISNULL );
93474  assert( op!=TK_IN || c==WO_IN );
93475  assert( op!=TK_EQ || c==WO_EQ );
93476  assert( op!=TK_LT || c==WO_LT );
93477  assert( op!=TK_LE || c==WO_LE );
93478  assert( op!=TK_GT || c==WO_GT );
93479  assert( op!=TK_GE || c==WO_GE );
93480  return c;
93481}
93482
93483/*
93484** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
93485** where X is a reference to the iColumn of table iCur and <op> is one of
93486** the WO_xx operator codes specified by the op parameter.
93487** Return a pointer to the term.  Return 0 if not found.
93488*/
93489static WhereTerm *findTerm(
93490  WhereClause *pWC,     /* The WHERE clause to be searched */
93491  int iCur,             /* Cursor number of LHS */
93492  int iColumn,          /* Column number of LHS */
93493  Bitmask notReady,     /* RHS must not overlap with this mask */
93494  u32 op,               /* Mask of WO_xx values describing operator */
93495  Index *pIdx           /* Must be compatible with this index, if not NULL */
93496){
93497  WhereTerm *pTerm;
93498  int k;
93499  assert( iCur>=0 );
93500  op &= WO_ALL;
93501  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
93502    if( pTerm->leftCursor==iCur
93503       && (pTerm->prereqRight & notReady)==0
93504       && pTerm->u.leftColumn==iColumn
93505       && (pTerm->eOperator & op)!=0
93506    ){
93507      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
93508        Expr *pX = pTerm->pExpr;
93509        CollSeq *pColl;
93510        char idxaff;
93511        int j;
93512        Parse *pParse = pWC->pParse;
93513
93514        idxaff = pIdx->pTable->aCol[iColumn].affinity;
93515        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
93516
93517        /* Figure out the collation sequence required from an index for
93518        ** it to be useful for optimising expression pX. Store this
93519        ** value in variable pColl.
93520        */
93521        assert(pX->pLeft);
93522        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
93523        assert(pColl || pParse->nErr);
93524
93525        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
93526          if( NEVER(j>=pIdx->nColumn) ) return 0;
93527        }
93528        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
93529      }
93530      return pTerm;
93531    }
93532  }
93533  return 0;
93534}
93535
93536/* Forward reference */
93537static void exprAnalyze(SrcList*, WhereClause*, int);
93538
93539/*
93540** Call exprAnalyze on all terms in a WHERE clause.
93541**
93542**
93543*/
93544static void exprAnalyzeAll(
93545  SrcList *pTabList,       /* the FROM clause */
93546  WhereClause *pWC         /* the WHERE clause to be analyzed */
93547){
93548  int i;
93549  for(i=pWC->nTerm-1; i>=0; i--){
93550    exprAnalyze(pTabList, pWC, i);
93551  }
93552}
93553
93554#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
93555/*
93556** Check to see if the given expression is a LIKE or GLOB operator that
93557** can be optimized using inequality constraints.  Return TRUE if it is
93558** so and false if not.
93559**
93560** In order for the operator to be optimizible, the RHS must be a string
93561** literal that does not begin with a wildcard.
93562*/
93563static int isLikeOrGlob(
93564  Parse *pParse,    /* Parsing and code generating context */
93565  Expr *pExpr,      /* Test this expression */
93566  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
93567  int *pisComplete, /* True if the only wildcard is % in the last character */
93568  int *pnoCase      /* True if uppercase is equivalent to lowercase */
93569){
93570  const char *z = 0;         /* String on RHS of LIKE operator */
93571  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
93572  ExprList *pList;           /* List of operands to the LIKE operator */
93573  int c;                     /* One character in z[] */
93574  int cnt;                   /* Number of non-wildcard prefix characters */
93575  char wc[3];                /* Wildcard characters */
93576  CollSeq *pColl;            /* Collating sequence for LHS */
93577  sqlite3 *db = pParse->db;  /* Database connection */
93578  sqlite3_value *pVal = 0;
93579  int op;                    /* Opcode of pRight */
93580
93581  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
93582    return 0;
93583  }
93584#ifdef SQLITE_EBCDIC
93585  if( *pnoCase ) return 0;
93586#endif
93587  pList = pExpr->x.pList;
93588  pLeft = pList->a[1].pExpr;
93589  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
93590    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
93591    ** be the name of an indexed column with TEXT affinity. */
93592    return 0;
93593  }
93594  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
93595  pColl = sqlite3ExprCollSeq(pParse, pLeft);
93596  if( pColl==0 ) return 0;  /* Happens when LHS has an undefined collation */
93597  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
93598      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
93599    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
93600    ** default BINARY collating sequence.
93601    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
93602    ** is enabled then the column must use the default BINARY collating
93603    ** sequence, or if case_sensitive_like mode is disabled then the column
93604    ** must use the built-in NOCASE collating sequence.
93605    */
93606    return 0;
93607  }
93608
93609  pRight = pList->a[0].pExpr;
93610  op = pRight->op;
93611  if( op==TK_REGISTER ){
93612    op = pRight->op2;
93613  }
93614  if( op==TK_VARIABLE ){
93615    Vdbe *pReprepare = pParse->pReprepare;
93616    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
93617    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
93618      z = (char *)sqlite3_value_text(pVal);
93619    }
93620    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
93621    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
93622  }else if( op==TK_STRING ){
93623    z = pRight->u.zToken;
93624  }
93625  if( z ){
93626    cnt = 0;
93627    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
93628      cnt++;
93629    }
93630    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
93631      Expr *pPrefix;
93632      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
93633      pPrefix = sqlite3Expr(db, TK_STRING, z);
93634      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
93635      *ppPrefix = pPrefix;
93636      if( op==TK_VARIABLE ){
93637        Vdbe *v = pParse->pVdbe;
93638        sqlite3VdbeSetVarmask(v, pRight->iColumn);
93639        if( *pisComplete && pRight->u.zToken[1] ){
93640          /* If the rhs of the LIKE expression is a variable, and the current
93641          ** value of the variable means there is no need to invoke the LIKE
93642          ** function, then no OP_Variable will be added to the program.
93643          ** This causes problems for the sqlite3_bind_parameter_name()
93644          ** API. To workaround them, add a dummy OP_Variable here.
93645          */
93646          int r1 = sqlite3GetTempReg(pParse);
93647          sqlite3ExprCodeTarget(pParse, pRight, r1);
93648          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
93649          sqlite3ReleaseTempReg(pParse, r1);
93650        }
93651      }
93652    }else{
93653      z = 0;
93654    }
93655  }
93656
93657  sqlite3ValueFree(pVal);
93658  return (z!=0);
93659}
93660#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
93661
93662
93663#ifndef SQLITE_OMIT_VIRTUALTABLE
93664/*
93665** Check to see if the given expression is of the form
93666**
93667**         column MATCH expr
93668**
93669** If it is then return TRUE.  If not, return FALSE.
93670*/
93671static int isMatchOfColumn(
93672  Expr *pExpr      /* Test this expression */
93673){
93674  ExprList *pList;
93675
93676  if( pExpr->op!=TK_FUNCTION ){
93677    return 0;
93678  }
93679  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
93680    return 0;
93681  }
93682  pList = pExpr->x.pList;
93683  if( pList->nExpr!=2 ){
93684    return 0;
93685  }
93686  if( pList->a[1].pExpr->op != TK_COLUMN ){
93687    return 0;
93688  }
93689  return 1;
93690}
93691#endif /* SQLITE_OMIT_VIRTUALTABLE */
93692
93693/*
93694** If the pBase expression originated in the ON or USING clause of
93695** a join, then transfer the appropriate markings over to derived.
93696*/
93697static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
93698  pDerived->flags |= pBase->flags & EP_FromJoin;
93699  pDerived->iRightJoinTable = pBase->iRightJoinTable;
93700}
93701
93702#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
93703/*
93704** Analyze a term that consists of two or more OR-connected
93705** subterms.  So in:
93706**
93707**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
93708**                          ^^^^^^^^^^^^^^^^^^^^
93709**
93710** This routine analyzes terms such as the middle term in the above example.
93711** A WhereOrTerm object is computed and attached to the term under
93712** analysis, regardless of the outcome of the analysis.  Hence:
93713**
93714**     WhereTerm.wtFlags   |=  TERM_ORINFO
93715**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
93716**
93717** The term being analyzed must have two or more of OR-connected subterms.
93718** A single subterm might be a set of AND-connected sub-subterms.
93719** Examples of terms under analysis:
93720**
93721**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
93722**     (B)     x=expr1 OR expr2=x OR x=expr3
93723**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
93724**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
93725**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
93726**
93727** CASE 1:
93728**
93729** If all subterms are of the form T.C=expr for some single column of C
93730** a single table T (as shown in example B above) then create a new virtual
93731** term that is an equivalent IN expression.  In other words, if the term
93732** being analyzed is:
93733**
93734**      x = expr1  OR  expr2 = x  OR  x = expr3
93735**
93736** then create a new virtual term like this:
93737**
93738**      x IN (expr1,expr2,expr3)
93739**
93740** CASE 2:
93741**
93742** If all subterms are indexable by a single table T, then set
93743**
93744**     WhereTerm.eOperator              =  WO_OR
93745**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
93746**
93747** A subterm is "indexable" if it is of the form
93748** "T.C <op> <expr>" where C is any column of table T and
93749** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
93750** A subterm is also indexable if it is an AND of two or more
93751** subsubterms at least one of which is indexable.  Indexable AND
93752** subterms have their eOperator set to WO_AND and they have
93753** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
93754**
93755** From another point of view, "indexable" means that the subterm could
93756** potentially be used with an index if an appropriate index exists.
93757** This analysis does not consider whether or not the index exists; that
93758** is something the bestIndex() routine will determine.  This analysis
93759** only looks at whether subterms appropriate for indexing exist.
93760**
93761** All examples A through E above all satisfy case 2.  But if a term
93762** also statisfies case 1 (such as B) we know that the optimizer will
93763** always prefer case 1, so in that case we pretend that case 2 is not
93764** satisfied.
93765**
93766** It might be the case that multiple tables are indexable.  For example,
93767** (E) above is indexable on tables P, Q, and R.
93768**
93769** Terms that satisfy case 2 are candidates for lookup by using
93770** separate indices to find rowids for each subterm and composing
93771** the union of all rowids using a RowSet object.  This is similar
93772** to "bitmap indices" in other database engines.
93773**
93774** OTHERWISE:
93775**
93776** If neither case 1 nor case 2 apply, then leave the eOperator set to
93777** zero.  This term is not useful for search.
93778*/
93779static void exprAnalyzeOrTerm(
93780  SrcList *pSrc,            /* the FROM clause */
93781  WhereClause *pWC,         /* the complete WHERE clause */
93782  int idxTerm               /* Index of the OR-term to be analyzed */
93783){
93784  Parse *pParse = pWC->pParse;            /* Parser context */
93785  sqlite3 *db = pParse->db;               /* Database connection */
93786  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
93787  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
93788  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
93789  int i;                                  /* Loop counters */
93790  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
93791  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
93792  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
93793  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
93794  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
93795
93796  /*
93797  ** Break the OR clause into its separate subterms.  The subterms are
93798  ** stored in a WhereClause structure containing within the WhereOrInfo
93799  ** object that is attached to the original OR clause term.
93800  */
93801  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
93802  assert( pExpr->op==TK_OR );
93803  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
93804  if( pOrInfo==0 ) return;
93805  pTerm->wtFlags |= TERM_ORINFO;
93806  pOrWc = &pOrInfo->wc;
93807  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
93808  whereSplit(pOrWc, pExpr, TK_OR);
93809  exprAnalyzeAll(pSrc, pOrWc);
93810  if( db->mallocFailed ) return;
93811  assert( pOrWc->nTerm>=2 );
93812
93813  /*
93814  ** Compute the set of tables that might satisfy cases 1 or 2.
93815  */
93816  indexable = ~(Bitmask)0;
93817  chngToIN = ~(pWC->vmask);
93818  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
93819    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
93820      WhereAndInfo *pAndInfo;
93821      assert( pOrTerm->eOperator==0 );
93822      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
93823      chngToIN = 0;
93824      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
93825      if( pAndInfo ){
93826        WhereClause *pAndWC;
93827        WhereTerm *pAndTerm;
93828        int j;
93829        Bitmask b = 0;
93830        pOrTerm->u.pAndInfo = pAndInfo;
93831        pOrTerm->wtFlags |= TERM_ANDINFO;
93832        pOrTerm->eOperator = WO_AND;
93833        pAndWC = &pAndInfo->wc;
93834        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
93835        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
93836        exprAnalyzeAll(pSrc, pAndWC);
93837        testcase( db->mallocFailed );
93838        if( !db->mallocFailed ){
93839          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
93840            assert( pAndTerm->pExpr );
93841            if( allowedOp(pAndTerm->pExpr->op) ){
93842              b |= getMask(pMaskSet, pAndTerm->leftCursor);
93843            }
93844          }
93845        }
93846        indexable &= b;
93847      }
93848    }else if( pOrTerm->wtFlags & TERM_COPIED ){
93849      /* Skip this term for now.  We revisit it when we process the
93850      ** corresponding TERM_VIRTUAL term */
93851    }else{
93852      Bitmask b;
93853      b = getMask(pMaskSet, pOrTerm->leftCursor);
93854      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
93855        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
93856        b |= getMask(pMaskSet, pOther->leftCursor);
93857      }
93858      indexable &= b;
93859      if( pOrTerm->eOperator!=WO_EQ ){
93860        chngToIN = 0;
93861      }else{
93862        chngToIN &= b;
93863      }
93864    }
93865  }
93866
93867  /*
93868  ** Record the set of tables that satisfy case 2.  The set might be
93869  ** empty.
93870  */
93871  pOrInfo->indexable = indexable;
93872  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
93873
93874  /*
93875  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
93876  ** we have to do some additional checking to see if case 1 really
93877  ** is satisfied.
93878  **
93879  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
93880  ** that there is no possibility of transforming the OR clause into an
93881  ** IN operator because one or more terms in the OR clause contain
93882  ** something other than == on a column in the single table.  The 1-bit
93883  ** case means that every term of the OR clause is of the form
93884  ** "table.column=expr" for some single table.  The one bit that is set
93885  ** will correspond to the common table.  We still need to check to make
93886  ** sure the same column is used on all terms.  The 2-bit case is when
93887  ** the all terms are of the form "table1.column=table2.column".  It
93888  ** might be possible to form an IN operator with either table1.column
93889  ** or table2.column as the LHS if either is common to every term of
93890  ** the OR clause.
93891  **
93892  ** Note that terms of the form "table.column1=table.column2" (the
93893  ** same table on both sizes of the ==) cannot be optimized.
93894  */
93895  if( chngToIN ){
93896    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
93897    int iColumn = -1;         /* Column index on lhs of IN operator */
93898    int iCursor = -1;         /* Table cursor common to all terms */
93899    int j = 0;                /* Loop counter */
93900
93901    /* Search for a table and column that appears on one side or the
93902    ** other of the == operator in every subterm.  That table and column
93903    ** will be recorded in iCursor and iColumn.  There might not be any
93904    ** such table and column.  Set okToChngToIN if an appropriate table
93905    ** and column is found but leave okToChngToIN false if not found.
93906    */
93907    for(j=0; j<2 && !okToChngToIN; j++){
93908      pOrTerm = pOrWc->a;
93909      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
93910        assert( pOrTerm->eOperator==WO_EQ );
93911        pOrTerm->wtFlags &= ~TERM_OR_OK;
93912        if( pOrTerm->leftCursor==iCursor ){
93913          /* This is the 2-bit case and we are on the second iteration and
93914          ** current term is from the first iteration.  So skip this term. */
93915          assert( j==1 );
93916          continue;
93917        }
93918        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
93919          /* This term must be of the form t1.a==t2.b where t2 is in the
93920          ** chngToIN set but t1 is not.  This term will be either preceeded
93921          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
93922          ** and use its inversion. */
93923          testcase( pOrTerm->wtFlags & TERM_COPIED );
93924          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
93925          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
93926          continue;
93927        }
93928        iColumn = pOrTerm->u.leftColumn;
93929        iCursor = pOrTerm->leftCursor;
93930        break;
93931      }
93932      if( i<0 ){
93933        /* No candidate table+column was found.  This can only occur
93934        ** on the second iteration */
93935        assert( j==1 );
93936        assert( (chngToIN&(chngToIN-1))==0 );
93937        assert( chngToIN==getMask(pMaskSet, iCursor) );
93938        break;
93939      }
93940      testcase( j==1 );
93941
93942      /* We have found a candidate table and column.  Check to see if that
93943      ** table and column is common to every term in the OR clause */
93944      okToChngToIN = 1;
93945      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
93946        assert( pOrTerm->eOperator==WO_EQ );
93947        if( pOrTerm->leftCursor!=iCursor ){
93948          pOrTerm->wtFlags &= ~TERM_OR_OK;
93949        }else if( pOrTerm->u.leftColumn!=iColumn ){
93950          okToChngToIN = 0;
93951        }else{
93952          int affLeft, affRight;
93953          /* If the right-hand side is also a column, then the affinities
93954          ** of both right and left sides must be such that no type
93955          ** conversions are required on the right.  (Ticket #2249)
93956          */
93957          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
93958          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
93959          if( affRight!=0 && affRight!=affLeft ){
93960            okToChngToIN = 0;
93961          }else{
93962            pOrTerm->wtFlags |= TERM_OR_OK;
93963          }
93964        }
93965      }
93966    }
93967
93968    /* At this point, okToChngToIN is true if original pTerm satisfies
93969    ** case 1.  In that case, construct a new virtual term that is
93970    ** pTerm converted into an IN operator.
93971    */
93972    if( okToChngToIN ){
93973      Expr *pDup;            /* A transient duplicate expression */
93974      ExprList *pList = 0;   /* The RHS of the IN operator */
93975      Expr *pLeft = 0;       /* The LHS of the IN operator */
93976      Expr *pNew;            /* The complete IN operator */
93977
93978      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
93979        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
93980        assert( pOrTerm->eOperator==WO_EQ );
93981        assert( pOrTerm->leftCursor==iCursor );
93982        assert( pOrTerm->u.leftColumn==iColumn );
93983        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
93984        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
93985        pLeft = pOrTerm->pExpr->pLeft;
93986      }
93987      assert( pLeft!=0 );
93988      pDup = sqlite3ExprDup(db, pLeft, 0);
93989      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
93990      if( pNew ){
93991        int idxNew;
93992        transferJoinMarkings(pNew, pExpr);
93993        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
93994        pNew->x.pList = pList;
93995        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
93996        testcase( idxNew==0 );
93997        exprAnalyze(pSrc, pWC, idxNew);
93998        pTerm = &pWC->a[idxTerm];
93999        pWC->a[idxNew].iParent = idxTerm;
94000        pTerm->nChild = 1;
94001      }else{
94002        sqlite3ExprListDelete(db, pList);
94003      }
94004      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
94005    }
94006  }
94007}
94008#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
94009
94010
94011/*
94012** The input to this routine is an WhereTerm structure with only the
94013** "pExpr" field filled in.  The job of this routine is to analyze the
94014** subexpression and populate all the other fields of the WhereTerm
94015** structure.
94016**
94017** If the expression is of the form "<expr> <op> X" it gets commuted
94018** to the standard form of "X <op> <expr>".
94019**
94020** If the expression is of the form "X <op> Y" where both X and Y are
94021** columns, then the original expression is unchanged and a new virtual
94022** term of the form "Y <op> X" is added to the WHERE clause and
94023** analyzed separately.  The original term is marked with TERM_COPIED
94024** and the new term is marked with TERM_DYNAMIC (because it's pExpr
94025** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
94026** is a commuted copy of a prior term.)  The original term has nChild=1
94027** and the copy has idxParent set to the index of the original term.
94028*/
94029static void exprAnalyze(
94030  SrcList *pSrc,            /* the FROM clause */
94031  WhereClause *pWC,         /* the WHERE clause */
94032  int idxTerm               /* Index of the term to be analyzed */
94033){
94034  WhereTerm *pTerm;                /* The term to be analyzed */
94035  WhereMaskSet *pMaskSet;          /* Set of table index masks */
94036  Expr *pExpr;                     /* The expression to be analyzed */
94037  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
94038  Bitmask prereqAll;               /* Prerequesites of pExpr */
94039  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
94040  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
94041  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
94042  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
94043  int op;                          /* Top-level operator.  pExpr->op */
94044  Parse *pParse = pWC->pParse;     /* Parsing context */
94045  sqlite3 *db = pParse->db;        /* Database connection */
94046
94047  if( db->mallocFailed ){
94048    return;
94049  }
94050  pTerm = &pWC->a[idxTerm];
94051  pMaskSet = pWC->pMaskSet;
94052  pExpr = pTerm->pExpr;
94053  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
94054  op = pExpr->op;
94055  if( op==TK_IN ){
94056    assert( pExpr->pRight==0 );
94057    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94058      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
94059    }else{
94060      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
94061    }
94062  }else if( op==TK_ISNULL ){
94063    pTerm->prereqRight = 0;
94064  }else{
94065    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
94066  }
94067  prereqAll = exprTableUsage(pMaskSet, pExpr);
94068  if( ExprHasProperty(pExpr, EP_FromJoin) ){
94069    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
94070    prereqAll |= x;
94071    extraRight = x-1;  /* ON clause terms may not be used with an index
94072                       ** on left table of a LEFT JOIN.  Ticket #3015 */
94073  }
94074  pTerm->prereqAll = prereqAll;
94075  pTerm->leftCursor = -1;
94076  pTerm->iParent = -1;
94077  pTerm->eOperator = 0;
94078  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
94079    Expr *pLeft = pExpr->pLeft;
94080    Expr *pRight = pExpr->pRight;
94081    if( pLeft->op==TK_COLUMN ){
94082      pTerm->leftCursor = pLeft->iTable;
94083      pTerm->u.leftColumn = pLeft->iColumn;
94084      pTerm->eOperator = operatorMask(op);
94085    }
94086    if( pRight && pRight->op==TK_COLUMN ){
94087      WhereTerm *pNew;
94088      Expr *pDup;
94089      if( pTerm->leftCursor>=0 ){
94090        int idxNew;
94091        pDup = sqlite3ExprDup(db, pExpr, 0);
94092        if( db->mallocFailed ){
94093          sqlite3ExprDelete(db, pDup);
94094          return;
94095        }
94096        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
94097        if( idxNew==0 ) return;
94098        pNew = &pWC->a[idxNew];
94099        pNew->iParent = idxTerm;
94100        pTerm = &pWC->a[idxTerm];
94101        pTerm->nChild = 1;
94102        pTerm->wtFlags |= TERM_COPIED;
94103      }else{
94104        pDup = pExpr;
94105        pNew = pTerm;
94106      }
94107      exprCommute(pParse, pDup);
94108      pLeft = pDup->pLeft;
94109      pNew->leftCursor = pLeft->iTable;
94110      pNew->u.leftColumn = pLeft->iColumn;
94111      testcase( (prereqLeft | extraRight) != prereqLeft );
94112      pNew->prereqRight = prereqLeft | extraRight;
94113      pNew->prereqAll = prereqAll;
94114      pNew->eOperator = operatorMask(pDup->op);
94115    }
94116  }
94117
94118#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
94119  /* If a term is the BETWEEN operator, create two new virtual terms
94120  ** that define the range that the BETWEEN implements.  For example:
94121  **
94122  **      a BETWEEN b AND c
94123  **
94124  ** is converted into:
94125  **
94126  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
94127  **
94128  ** The two new terms are added onto the end of the WhereClause object.
94129  ** The new terms are "dynamic" and are children of the original BETWEEN
94130  ** term.  That means that if the BETWEEN term is coded, the children are
94131  ** skipped.  Or, if the children are satisfied by an index, the original
94132  ** BETWEEN term is skipped.
94133  */
94134  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
94135    ExprList *pList = pExpr->x.pList;
94136    int i;
94137    static const u8 ops[] = {TK_GE, TK_LE};
94138    assert( pList!=0 );
94139    assert( pList->nExpr==2 );
94140    for(i=0; i<2; i++){
94141      Expr *pNewExpr;
94142      int idxNew;
94143      pNewExpr = sqlite3PExpr(pParse, ops[i],
94144                             sqlite3ExprDup(db, pExpr->pLeft, 0),
94145                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
94146      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94147      testcase( idxNew==0 );
94148      exprAnalyze(pSrc, pWC, idxNew);
94149      pTerm = &pWC->a[idxTerm];
94150      pWC->a[idxNew].iParent = idxTerm;
94151    }
94152    pTerm->nChild = 2;
94153  }
94154#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
94155
94156#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94157  /* Analyze a term that is composed of two or more subterms connected by
94158  ** an OR operator.
94159  */
94160  else if( pExpr->op==TK_OR ){
94161    assert( pWC->op==TK_AND );
94162    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
94163    pTerm = &pWC->a[idxTerm];
94164  }
94165#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94166
94167#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
94168  /* Add constraints to reduce the search space on a LIKE or GLOB
94169  ** operator.
94170  **
94171  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
94172  **
94173  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
94174  **
94175  ** The last character of the prefix "abc" is incremented to form the
94176  ** termination condition "abd".
94177  */
94178  if( pWC->op==TK_AND
94179   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
94180  ){
94181    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
94182    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
94183    Expr *pNewExpr1;
94184    Expr *pNewExpr2;
94185    int idxNew1;
94186    int idxNew2;
94187
94188    pLeft = pExpr->x.pList->a[1].pExpr;
94189    pStr2 = sqlite3ExprDup(db, pStr1, 0);
94190    if( !db->mallocFailed ){
94191      u8 c, *pC;       /* Last character before the first wildcard */
94192      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
94193      c = *pC;
94194      if( noCase ){
94195        /* The point is to increment the last character before the first
94196        ** wildcard.  But if we increment '@', that will push it into the
94197        ** alphabetic range where case conversions will mess up the
94198        ** inequality.  To avoid this, make sure to also run the full
94199        ** LIKE on all candidate expressions by clearing the isComplete flag
94200        */
94201        if( c=='A'-1 ) isComplete = 0;
94202
94203        c = sqlite3UpperToLower[c];
94204      }
94205      *pC = c + 1;
94206    }
94207    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
94208    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
94209    testcase( idxNew1==0 );
94210    exprAnalyze(pSrc, pWC, idxNew1);
94211    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
94212    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
94213    testcase( idxNew2==0 );
94214    exprAnalyze(pSrc, pWC, idxNew2);
94215    pTerm = &pWC->a[idxTerm];
94216    if( isComplete ){
94217      pWC->a[idxNew1].iParent = idxTerm;
94218      pWC->a[idxNew2].iParent = idxTerm;
94219      pTerm->nChild = 2;
94220    }
94221  }
94222#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
94223
94224#ifndef SQLITE_OMIT_VIRTUALTABLE
94225  /* Add a WO_MATCH auxiliary term to the constraint set if the
94226  ** current expression is of the form:  column MATCH expr.
94227  ** This information is used by the xBestIndex methods of
94228  ** virtual tables.  The native query optimizer does not attempt
94229  ** to do anything with MATCH functions.
94230  */
94231  if( isMatchOfColumn(pExpr) ){
94232    int idxNew;
94233    Expr *pRight, *pLeft;
94234    WhereTerm *pNewTerm;
94235    Bitmask prereqColumn, prereqExpr;
94236
94237    pRight = pExpr->x.pList->a[0].pExpr;
94238    pLeft = pExpr->x.pList->a[1].pExpr;
94239    prereqExpr = exprTableUsage(pMaskSet, pRight);
94240    prereqColumn = exprTableUsage(pMaskSet, pLeft);
94241    if( (prereqExpr & prereqColumn)==0 ){
94242      Expr *pNewExpr;
94243      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
94244                              0, sqlite3ExprDup(db, pRight, 0), 0);
94245      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94246      testcase( idxNew==0 );
94247      pNewTerm = &pWC->a[idxNew];
94248      pNewTerm->prereqRight = prereqExpr;
94249      pNewTerm->leftCursor = pLeft->iTable;
94250      pNewTerm->u.leftColumn = pLeft->iColumn;
94251      pNewTerm->eOperator = WO_MATCH;
94252      pNewTerm->iParent = idxTerm;
94253      pTerm = &pWC->a[idxTerm];
94254      pTerm->nChild = 1;
94255      pTerm->wtFlags |= TERM_COPIED;
94256      pNewTerm->prereqAll = pTerm->prereqAll;
94257    }
94258  }
94259#endif /* SQLITE_OMIT_VIRTUALTABLE */
94260
94261  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
94262  ** an index for tables to the left of the join.
94263  */
94264  pTerm->prereqRight |= extraRight;
94265}
94266
94267/*
94268** Return TRUE if any of the expressions in pList->a[iFirst...] contain
94269** a reference to any table other than the iBase table.
94270*/
94271static int referencesOtherTables(
94272  ExprList *pList,          /* Search expressions in ths list */
94273  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
94274  int iFirst,               /* Be searching with the iFirst-th expression */
94275  int iBase                 /* Ignore references to this table */
94276){
94277  Bitmask allowed = ~getMask(pMaskSet, iBase);
94278  while( iFirst<pList->nExpr ){
94279    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
94280      return 1;
94281    }
94282  }
94283  return 0;
94284}
94285
94286
94287/*
94288** This routine decides if pIdx can be used to satisfy the ORDER BY
94289** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
94290** ORDER BY clause, this routine returns 0.
94291**
94292** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
94293** left-most table in the FROM clause of that same SELECT statement and
94294** the table has a cursor number of "base".  pIdx is an index on pTab.
94295**
94296** nEqCol is the number of columns of pIdx that are used as equality
94297** constraints.  Any of these columns may be missing from the ORDER BY
94298** clause and the match can still be a success.
94299**
94300** All terms of the ORDER BY that match against the index must be either
94301** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
94302** index do not need to satisfy this constraint.)  The *pbRev value is
94303** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
94304** the ORDER BY clause is all ASC.
94305*/
94306static int isSortingIndex(
94307  Parse *pParse,          /* Parsing context */
94308  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
94309  Index *pIdx,            /* The index we are testing */
94310  int base,               /* Cursor number for the table to be sorted */
94311  ExprList *pOrderBy,     /* The ORDER BY clause */
94312  int nEqCol,             /* Number of index columns with == constraints */
94313  int *pbRev              /* Set to 1 if ORDER BY is DESC */
94314){
94315  int i, j;                       /* Loop counters */
94316  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
94317  int nTerm;                      /* Number of ORDER BY terms */
94318  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
94319  sqlite3 *db = pParse->db;
94320
94321  assert( pOrderBy!=0 );
94322  nTerm = pOrderBy->nExpr;
94323  assert( nTerm>0 );
94324
94325  /* Argument pIdx must either point to a 'real' named index structure,
94326  ** or an index structure allocated on the stack by bestBtreeIndex() to
94327  ** represent the rowid index that is part of every table.  */
94328  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
94329
94330  /* Match terms of the ORDER BY clause against columns of
94331  ** the index.
94332  **
94333  ** Note that indices have pIdx->nColumn regular columns plus
94334  ** one additional column containing the rowid.  The rowid column
94335  ** of the index is also allowed to match against the ORDER BY
94336  ** clause.
94337  */
94338  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
94339    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
94340    CollSeq *pColl;    /* The collating sequence of pExpr */
94341    int termSortOrder; /* Sort order for this term */
94342    int iColumn;       /* The i-th column of the index.  -1 for rowid */
94343    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
94344    const char *zColl; /* Name of the collating sequence for i-th index term */
94345
94346    pExpr = pTerm->pExpr;
94347    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
94348      /* Can not use an index sort on anything that is not a column in the
94349      ** left-most table of the FROM clause */
94350      break;
94351    }
94352    pColl = sqlite3ExprCollSeq(pParse, pExpr);
94353    if( !pColl ){
94354      pColl = db->pDfltColl;
94355    }
94356    if( pIdx->zName && i<pIdx->nColumn ){
94357      iColumn = pIdx->aiColumn[i];
94358      if( iColumn==pIdx->pTable->iPKey ){
94359        iColumn = -1;
94360      }
94361      iSortOrder = pIdx->aSortOrder[i];
94362      zColl = pIdx->azColl[i];
94363    }else{
94364      iColumn = -1;
94365      iSortOrder = 0;
94366      zColl = pColl->zName;
94367    }
94368    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
94369      /* Term j of the ORDER BY clause does not match column i of the index */
94370      if( i<nEqCol ){
94371        /* If an index column that is constrained by == fails to match an
94372        ** ORDER BY term, that is OK.  Just ignore that column of the index
94373        */
94374        continue;
94375      }else if( i==pIdx->nColumn ){
94376        /* Index column i is the rowid.  All other terms match. */
94377        break;
94378      }else{
94379        /* If an index column fails to match and is not constrained by ==
94380        ** then the index cannot satisfy the ORDER BY constraint.
94381        */
94382        return 0;
94383      }
94384    }
94385    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
94386    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
94387    assert( iSortOrder==0 || iSortOrder==1 );
94388    termSortOrder = iSortOrder ^ pTerm->sortOrder;
94389    if( i>nEqCol ){
94390      if( termSortOrder!=sortOrder ){
94391        /* Indices can only be used if all ORDER BY terms past the
94392        ** equality constraints are all either DESC or ASC. */
94393        return 0;
94394      }
94395    }else{
94396      sortOrder = termSortOrder;
94397    }
94398    j++;
94399    pTerm++;
94400    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94401      /* If the indexed column is the primary key and everything matches
94402      ** so far and none of the ORDER BY terms to the right reference other
94403      ** tables in the join, then we are assured that the index can be used
94404      ** to sort because the primary key is unique and so none of the other
94405      ** columns will make any difference
94406      */
94407      j = nTerm;
94408    }
94409  }
94410
94411  *pbRev = sortOrder!=0;
94412  if( j>=nTerm ){
94413    /* All terms of the ORDER BY clause are covered by this index so
94414    ** this index can be used for sorting. */
94415    return 1;
94416  }
94417  if( pIdx->onError!=OE_None && i==pIdx->nColumn
94418      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94419    /* All terms of this index match some prefix of the ORDER BY clause
94420    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
94421    ** clause reference other tables in a join.  If this is all true then
94422    ** the order by clause is superfluous. */
94423    return 1;
94424  }
94425  return 0;
94426}
94427
94428/*
94429** Prepare a crude estimate of the logarithm of the input value.
94430** The results need not be exact.  This is only used for estimating
94431** the total cost of performing operations with O(logN) or O(NlogN)
94432** complexity.  Because N is just a guess, it is no great tragedy if
94433** logN is a little off.
94434*/
94435static double estLog(double N){
94436  double logN = 1;
94437  double x = 10;
94438  while( N>x ){
94439    logN += 1;
94440    x *= 10;
94441  }
94442  return logN;
94443}
94444
94445/*
94446** Two routines for printing the content of an sqlite3_index_info
94447** structure.  Used for testing and debugging only.  If neither
94448** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
94449** are no-ops.
94450*/
94451#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
94452static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
94453  int i;
94454  if( !sqlite3WhereTrace ) return;
94455  for(i=0; i<p->nConstraint; i++){
94456    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
94457       i,
94458       p->aConstraint[i].iColumn,
94459       p->aConstraint[i].iTermOffset,
94460       p->aConstraint[i].op,
94461       p->aConstraint[i].usable);
94462  }
94463  for(i=0; i<p->nOrderBy; i++){
94464    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
94465       i,
94466       p->aOrderBy[i].iColumn,
94467       p->aOrderBy[i].desc);
94468  }
94469}
94470static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
94471  int i;
94472  if( !sqlite3WhereTrace ) return;
94473  for(i=0; i<p->nConstraint; i++){
94474    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
94475       i,
94476       p->aConstraintUsage[i].argvIndex,
94477       p->aConstraintUsage[i].omit);
94478  }
94479  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
94480  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
94481  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
94482  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
94483}
94484#else
94485#define TRACE_IDX_INPUTS(A)
94486#define TRACE_IDX_OUTPUTS(A)
94487#endif
94488
94489/*
94490** Required because bestIndex() is called by bestOrClauseIndex()
94491*/
94492static void bestIndex(
94493    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
94494
94495/*
94496** This routine attempts to find an scanning strategy that can be used
94497** to optimize an 'OR' expression that is part of a WHERE clause.
94498**
94499** The table associated with FROM clause term pSrc may be either a
94500** regular B-Tree table or a virtual table.
94501*/
94502static void bestOrClauseIndex(
94503  Parse *pParse,              /* The parsing context */
94504  WhereClause *pWC,           /* The WHERE clause */
94505  struct SrcList_item *pSrc,  /* The FROM clause term to search */
94506  Bitmask notReady,           /* Mask of cursors that are not available */
94507  ExprList *pOrderBy,         /* The ORDER BY clause */
94508  WhereCost *pCost            /* Lowest cost query plan */
94509){
94510#ifndef SQLITE_OMIT_OR_OPTIMIZATION
94511  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
94512  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
94513  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
94514  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
94515
94516  /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
94517  if( pSrc->notIndexed ){
94518    return;
94519  }
94520
94521  /* Search the WHERE clause terms for a usable WO_OR term. */
94522  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94523    if( pTerm->eOperator==WO_OR
94524     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
94525     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
94526    ){
94527      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
94528      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
94529      WhereTerm *pOrTerm;
94530      int flags = WHERE_MULTI_OR;
94531      double rTotal = 0;
94532      double nRow = 0;
94533      Bitmask used = 0;
94534
94535      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
94536        WhereCost sTermCost;
94537        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
94538          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
94539        ));
94540        if( pOrTerm->eOperator==WO_AND ){
94541          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
94542          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
94543        }else if( pOrTerm->leftCursor==iCur ){
94544          WhereClause tempWC;
94545          tempWC.pParse = pWC->pParse;
94546          tempWC.pMaskSet = pWC->pMaskSet;
94547          tempWC.op = TK_AND;
94548          tempWC.a = pOrTerm;
94549          tempWC.nTerm = 1;
94550          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
94551        }else{
94552          continue;
94553        }
94554        rTotal += sTermCost.rCost;
94555        nRow += sTermCost.nRow;
94556        used |= sTermCost.used;
94557        if( rTotal>=pCost->rCost ) break;
94558      }
94559
94560      /* If there is an ORDER BY clause, increase the scan cost to account
94561      ** for the cost of the sort. */
94562      if( pOrderBy!=0 ){
94563        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
94564                    rTotal, rTotal+nRow*estLog(nRow)));
94565        rTotal += nRow*estLog(nRow);
94566      }
94567
94568      /* If the cost of scanning using this OR term for optimization is
94569      ** less than the current cost stored in pCost, replace the contents
94570      ** of pCost. */
94571      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
94572      if( rTotal<pCost->rCost ){
94573        pCost->rCost = rTotal;
94574        pCost->nRow = nRow;
94575        pCost->used = used;
94576        pCost->plan.wsFlags = flags;
94577        pCost->plan.u.pTerm = pTerm;
94578      }
94579    }
94580  }
94581#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94582}
94583
94584#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94585/*
94586** Return TRUE if the WHERE clause term pTerm is of a form where it
94587** could be used with an index to access pSrc, assuming an appropriate
94588** index existed.
94589*/
94590static int termCanDriveIndex(
94591  WhereTerm *pTerm,              /* WHERE clause term to check */
94592  struct SrcList_item *pSrc,     /* Table we are trying to access */
94593  Bitmask notReady               /* Tables in outer loops of the join */
94594){
94595  char aff;
94596  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
94597  if( pTerm->eOperator!=WO_EQ ) return 0;
94598  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
94599  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
94600  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
94601  return 1;
94602}
94603#endif
94604
94605#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94606/*
94607** If the query plan for pSrc specified in pCost is a full table scan
94608** and indexing is allows (if there is no NOT INDEXED clause) and it
94609** possible to construct a transient index that would perform better
94610** than a full table scan even when the cost of constructing the index
94611** is taken into account, then alter the query plan to use the
94612** transient index.
94613*/
94614static void bestAutomaticIndex(
94615  Parse *pParse,              /* The parsing context */
94616  WhereClause *pWC,           /* The WHERE clause */
94617  struct SrcList_item *pSrc,  /* The FROM clause term to search */
94618  Bitmask notReady,           /* Mask of cursors that are not available */
94619  WhereCost *pCost            /* Lowest cost query plan */
94620){
94621  double nTableRow;           /* Rows in the input table */
94622  double logN;                /* log(nTableRow) */
94623  double costTempIdx;         /* per-query cost of the transient index */
94624  WhereTerm *pTerm;           /* A single term of the WHERE clause */
94625  WhereTerm *pWCEnd;          /* End of pWC->a[] */
94626  Table *pTable;              /* Table tht might be indexed */
94627
94628  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
94629    /* Automatic indices are disabled at run-time */
94630    return;
94631  }
94632  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
94633    /* We already have some kind of index in use for this query. */
94634    return;
94635  }
94636  if( pSrc->notIndexed ){
94637    /* The NOT INDEXED clause appears in the SQL. */
94638    return;
94639  }
94640
94641  assert( pParse->nQueryLoop >= (double)1 );
94642  pTable = pSrc->pTab;
94643  nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
94644  logN = estLog(nTableRow);
94645  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
94646  if( costTempIdx>=pCost->rCost ){
94647    /* The cost of creating the transient table would be greater than
94648    ** doing the full table scan */
94649    return;
94650  }
94651
94652  /* Search for any equality comparison term */
94653  pWCEnd = &pWC->a[pWC->nTerm];
94654  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94655    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
94656      WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
94657                    pCost->rCost, costTempIdx));
94658      pCost->rCost = costTempIdx;
94659      pCost->nRow = logN + 1;
94660      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
94661      pCost->used = pTerm->prereqRight;
94662      break;
94663    }
94664  }
94665}
94666#else
94667# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
94668#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
94669
94670
94671#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94672/*
94673** Generate code to construct the Index object for an automatic index
94674** and to set up the WhereLevel object pLevel so that the code generator
94675** makes use of the automatic index.
94676*/
94677static void constructAutomaticIndex(
94678  Parse *pParse,              /* The parsing context */
94679  WhereClause *pWC,           /* The WHERE clause */
94680  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
94681  Bitmask notReady,           /* Mask of cursors that are not available */
94682  WhereLevel *pLevel          /* Write new index here */
94683){
94684  int nColumn;                /* Number of columns in the constructed index */
94685  WhereTerm *pTerm;           /* A single term of the WHERE clause */
94686  WhereTerm *pWCEnd;          /* End of pWC->a[] */
94687  int nByte;                  /* Byte of memory needed for pIdx */
94688  Index *pIdx;                /* Object describing the transient index */
94689  Vdbe *v;                    /* Prepared statement under construction */
94690  int regIsInit;              /* Register set by initialization */
94691  int addrInit;               /* Address of the initialization bypass jump */
94692  Table *pTable;              /* The table being indexed */
94693  KeyInfo *pKeyinfo;          /* Key information for the index */
94694  int addrTop;                /* Top of the index fill loop */
94695  int regRecord;              /* Register holding an index record */
94696  int n;                      /* Column counter */
94697  int i;                      /* Loop counter */
94698  int mxBitCol;               /* Maximum column in pSrc->colUsed */
94699  CollSeq *pColl;             /* Collating sequence to on a column */
94700  Bitmask idxCols;            /* Bitmap of columns used for indexing */
94701  Bitmask extraCols;          /* Bitmap of additional columns */
94702
94703  /* Generate code to skip over the creation and initialization of the
94704  ** transient index on 2nd and subsequent iterations of the loop. */
94705  v = pParse->pVdbe;
94706  assert( v!=0 );
94707  regIsInit = ++pParse->nMem;
94708  addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
94709  sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
94710
94711  /* Count the number of columns that will be added to the index
94712  ** and used to match WHERE clause constraints */
94713  nColumn = 0;
94714  pTable = pSrc->pTab;
94715  pWCEnd = &pWC->a[pWC->nTerm];
94716  idxCols = 0;
94717  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94718    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
94719      int iCol = pTerm->u.leftColumn;
94720      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
94721      testcase( iCol==BMS );
94722      testcase( iCol==BMS-1 );
94723      if( (idxCols & cMask)==0 ){
94724        nColumn++;
94725        idxCols |= cMask;
94726      }
94727    }
94728  }
94729  assert( nColumn>0 );
94730  pLevel->plan.nEq = nColumn;
94731
94732  /* Count the number of additional columns needed to create a
94733  ** covering index.  A "covering index" is an index that contains all
94734  ** columns that are needed by the query.  With a covering index, the
94735  ** original table never needs to be accessed.  Automatic indices must
94736  ** be a covering index because the index will not be updated if the
94737  ** original table changes and the index and table cannot both be used
94738  ** if they go out of sync.
94739  */
94740  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
94741  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
94742  testcase( pTable->nCol==BMS-1 );
94743  testcase( pTable->nCol==BMS-2 );
94744  for(i=0; i<mxBitCol; i++){
94745    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
94746  }
94747  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
94748    nColumn += pTable->nCol - BMS + 1;
94749  }
94750  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
94751
94752  /* Construct the Index object to describe this index */
94753  nByte = sizeof(Index);
94754  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
94755  nByte += nColumn*sizeof(char*);   /* Index.azColl */
94756  nByte += nColumn;                 /* Index.aSortOrder */
94757  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
94758  if( pIdx==0 ) return;
94759  pLevel->plan.u.pIdx = pIdx;
94760  pIdx->azColl = (char**)&pIdx[1];
94761  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
94762  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
94763  pIdx->zName = "auto-index";
94764  pIdx->nColumn = nColumn;
94765  pIdx->pTable = pTable;
94766  n = 0;
94767  idxCols = 0;
94768  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94769    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
94770      int iCol = pTerm->u.leftColumn;
94771      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
94772      if( (idxCols & cMask)==0 ){
94773        Expr *pX = pTerm->pExpr;
94774        idxCols |= cMask;
94775        pIdx->aiColumn[n] = pTerm->u.leftColumn;
94776        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
94777        pIdx->azColl[n] = pColl->zName;
94778        n++;
94779      }
94780    }
94781  }
94782  assert( n==pLevel->plan.nEq );
94783
94784  /* Add additional columns needed to make the automatic index into
94785  ** a covering index */
94786  for(i=0; i<mxBitCol; i++){
94787    if( extraCols & (((Bitmask)1)<<i) ){
94788      pIdx->aiColumn[n] = i;
94789      pIdx->azColl[n] = "BINARY";
94790      n++;
94791    }
94792  }
94793  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
94794    for(i=BMS-1; i<pTable->nCol; i++){
94795      pIdx->aiColumn[n] = i;
94796      pIdx->azColl[n] = "BINARY";
94797      n++;
94798    }
94799  }
94800  assert( n==nColumn );
94801
94802  /* Create the automatic index */
94803  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
94804  assert( pLevel->iIdxCur>=0 );
94805  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
94806                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
94807  VdbeComment((v, "for %s", pTable->zName));
94808
94809  /* Fill the automatic index with content */
94810  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
94811  regRecord = sqlite3GetTempReg(pParse);
94812  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
94813  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
94814  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
94815  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
94816  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
94817  sqlite3VdbeJumpHere(v, addrTop);
94818  sqlite3ReleaseTempReg(pParse, regRecord);
94819
94820  /* Jump here when skipping the initialization */
94821  sqlite3VdbeJumpHere(v, addrInit);
94822}
94823#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
94824
94825#ifndef SQLITE_OMIT_VIRTUALTABLE
94826/*
94827** Allocate and populate an sqlite3_index_info structure. It is the
94828** responsibility of the caller to eventually release the structure
94829** by passing the pointer returned by this function to sqlite3_free().
94830*/
94831static sqlite3_index_info *allocateIndexInfo(
94832  Parse *pParse,
94833  WhereClause *pWC,
94834  struct SrcList_item *pSrc,
94835  ExprList *pOrderBy
94836){
94837  int i, j;
94838  int nTerm;
94839  struct sqlite3_index_constraint *pIdxCons;
94840  struct sqlite3_index_orderby *pIdxOrderBy;
94841  struct sqlite3_index_constraint_usage *pUsage;
94842  WhereTerm *pTerm;
94843  int nOrderBy;
94844  sqlite3_index_info *pIdxInfo;
94845
94846  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
94847
94848  /* Count the number of possible WHERE clause constraints referring
94849  ** to this virtual table */
94850  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
94851    if( pTerm->leftCursor != pSrc->iCursor ) continue;
94852    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
94853    testcase( pTerm->eOperator==WO_IN );
94854    testcase( pTerm->eOperator==WO_ISNULL );
94855    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
94856    nTerm++;
94857  }
94858
94859  /* If the ORDER BY clause contains only columns in the current
94860  ** virtual table then allocate space for the aOrderBy part of
94861  ** the sqlite3_index_info structure.
94862  */
94863  nOrderBy = 0;
94864  if( pOrderBy ){
94865    for(i=0; i<pOrderBy->nExpr; i++){
94866      Expr *pExpr = pOrderBy->a[i].pExpr;
94867      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
94868    }
94869    if( i==pOrderBy->nExpr ){
94870      nOrderBy = pOrderBy->nExpr;
94871    }
94872  }
94873
94874  /* Allocate the sqlite3_index_info structure
94875  */
94876  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
94877                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
94878                           + sizeof(*pIdxOrderBy)*nOrderBy );
94879  if( pIdxInfo==0 ){
94880    sqlite3ErrorMsg(pParse, "out of memory");
94881    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
94882    return 0;
94883  }
94884
94885  /* Initialize the structure.  The sqlite3_index_info structure contains
94886  ** many fields that are declared "const" to prevent xBestIndex from
94887  ** changing them.  We have to do some funky casting in order to
94888  ** initialize those fields.
94889  */
94890  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
94891  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
94892  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
94893  *(int*)&pIdxInfo->nConstraint = nTerm;
94894  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
94895  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
94896  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
94897  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
94898                                                                   pUsage;
94899
94900  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
94901    if( pTerm->leftCursor != pSrc->iCursor ) continue;
94902    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
94903    testcase( pTerm->eOperator==WO_IN );
94904    testcase( pTerm->eOperator==WO_ISNULL );
94905    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
94906    pIdxCons[j].iColumn = pTerm->u.leftColumn;
94907    pIdxCons[j].iTermOffset = i;
94908    pIdxCons[j].op = (u8)pTerm->eOperator;
94909    /* The direct assignment in the previous line is possible only because
94910    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
94911    ** following asserts verify this fact. */
94912    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
94913    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
94914    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
94915    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
94916    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
94917    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
94918    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
94919    j++;
94920  }
94921  for(i=0; i<nOrderBy; i++){
94922    Expr *pExpr = pOrderBy->a[i].pExpr;
94923    pIdxOrderBy[i].iColumn = pExpr->iColumn;
94924    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
94925  }
94926
94927  return pIdxInfo;
94928}
94929
94930/*
94931** The table object reference passed as the second argument to this function
94932** must represent a virtual table. This function invokes the xBestIndex()
94933** method of the virtual table with the sqlite3_index_info pointer passed
94934** as the argument.
94935**
94936** If an error occurs, pParse is populated with an error message and a
94937** non-zero value is returned. Otherwise, 0 is returned and the output
94938** part of the sqlite3_index_info structure is left populated.
94939**
94940** Whether or not an error is returned, it is the responsibility of the
94941** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
94942** that this is required.
94943*/
94944static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
94945  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
94946  int i;
94947  int rc;
94948
94949  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
94950  TRACE_IDX_INPUTS(p);
94951  rc = pVtab->pModule->xBestIndex(pVtab, p);
94952  TRACE_IDX_OUTPUTS(p);
94953
94954  if( rc!=SQLITE_OK ){
94955    if( rc==SQLITE_NOMEM ){
94956      pParse->db->mallocFailed = 1;
94957    }else if( !pVtab->zErrMsg ){
94958      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
94959    }else{
94960      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
94961    }
94962  }
94963  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
94964  pVtab->zErrMsg = 0;
94965
94966  for(i=0; i<p->nConstraint; i++){
94967    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
94968      sqlite3ErrorMsg(pParse,
94969          "table %s: xBestIndex returned an invalid plan", pTab->zName);
94970    }
94971  }
94972
94973  return pParse->nErr;
94974}
94975
94976
94977/*
94978** Compute the best index for a virtual table.
94979**
94980** The best index is computed by the xBestIndex method of the virtual
94981** table module.  This routine is really just a wrapper that sets up
94982** the sqlite3_index_info structure that is used to communicate with
94983** xBestIndex.
94984**
94985** In a join, this routine might be called multiple times for the
94986** same virtual table.  The sqlite3_index_info structure is created
94987** and initialized on the first invocation and reused on all subsequent
94988** invocations.  The sqlite3_index_info structure is also used when
94989** code is generated to access the virtual table.  The whereInfoDelete()
94990** routine takes care of freeing the sqlite3_index_info structure after
94991** everybody has finished with it.
94992*/
94993static void bestVirtualIndex(
94994  Parse *pParse,                  /* The parsing context */
94995  WhereClause *pWC,               /* The WHERE clause */
94996  struct SrcList_item *pSrc,      /* The FROM clause term to search */
94997  Bitmask notReady,               /* Mask of cursors that are not available */
94998  ExprList *pOrderBy,             /* The order by clause */
94999  WhereCost *pCost,               /* Lowest cost query plan */
95000  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
95001){
95002  Table *pTab = pSrc->pTab;
95003  sqlite3_index_info *pIdxInfo;
95004  struct sqlite3_index_constraint *pIdxCons;
95005  struct sqlite3_index_constraint_usage *pUsage;
95006  WhereTerm *pTerm;
95007  int i, j;
95008  int nOrderBy;
95009  double rCost;
95010
95011  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
95012  ** malloc in allocateIndexInfo() fails and this function returns leaving
95013  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
95014  */
95015  memset(pCost, 0, sizeof(*pCost));
95016  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
95017
95018  /* If the sqlite3_index_info structure has not been previously
95019  ** allocated and initialized, then allocate and initialize it now.
95020  */
95021  pIdxInfo = *ppIdxInfo;
95022  if( pIdxInfo==0 ){
95023    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
95024  }
95025  if( pIdxInfo==0 ){
95026    return;
95027  }
95028
95029  /* At this point, the sqlite3_index_info structure that pIdxInfo points
95030  ** to will have been initialized, either during the current invocation or
95031  ** during some prior invocation.  Now we just have to customize the
95032  ** details of pIdxInfo for the current invocation and pass it to
95033  ** xBestIndex.
95034  */
95035
95036  /* The module name must be defined. Also, by this point there must
95037  ** be a pointer to an sqlite3_vtab structure. Otherwise
95038  ** sqlite3ViewGetColumnNames() would have picked up the error.
95039  */
95040  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
95041  assert( sqlite3GetVTable(pParse->db, pTab) );
95042
95043  /* Set the aConstraint[].usable fields and initialize all
95044  ** output variables to zero.
95045  **
95046  ** aConstraint[].usable is true for constraints where the right-hand
95047  ** side contains only references to tables to the left of the current
95048  ** table.  In other words, if the constraint is of the form:
95049  **
95050  **           column = expr
95051  **
95052  ** and we are evaluating a join, then the constraint on column is
95053  ** only valid if all tables referenced in expr occur to the left
95054  ** of the table containing column.
95055  **
95056  ** The aConstraints[] array contains entries for all constraints
95057  ** on the current table.  That way we only have to compute it once
95058  ** even though we might try to pick the best index multiple times.
95059  ** For each attempt at picking an index, the order of tables in the
95060  ** join might be different so we have to recompute the usable flag
95061  ** each time.
95062  */
95063  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95064  pUsage = pIdxInfo->aConstraintUsage;
95065  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
95066    j = pIdxCons->iTermOffset;
95067    pTerm = &pWC->a[j];
95068    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
95069  }
95070  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
95071  if( pIdxInfo->needToFreeIdxStr ){
95072    sqlite3_free(pIdxInfo->idxStr);
95073  }
95074  pIdxInfo->idxStr = 0;
95075  pIdxInfo->idxNum = 0;
95076  pIdxInfo->needToFreeIdxStr = 0;
95077  pIdxInfo->orderByConsumed = 0;
95078  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
95079  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
95080  nOrderBy = pIdxInfo->nOrderBy;
95081  if( !pOrderBy ){
95082    pIdxInfo->nOrderBy = 0;
95083  }
95084
95085  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
95086    return;
95087  }
95088
95089  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95090  for(i=0; i<pIdxInfo->nConstraint; i++){
95091    if( pUsage[i].argvIndex>0 ){
95092      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
95093    }
95094  }
95095
95096  /* If there is an ORDER BY clause, and the selected virtual table index
95097  ** does not satisfy it, increase the cost of the scan accordingly. This
95098  ** matches the processing for non-virtual tables in bestBtreeIndex().
95099  */
95100  rCost = pIdxInfo->estimatedCost;
95101  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
95102    rCost += estLog(rCost)*rCost;
95103  }
95104
95105  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
95106  ** inital value of lowestCost in this loop. If it is, then the
95107  ** (cost<lowestCost) test below will never be true.
95108  **
95109  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
95110  ** is defined.
95111  */
95112  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
95113    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
95114  }else{
95115    pCost->rCost = rCost;
95116  }
95117  pCost->plan.u.pVtabIdx = pIdxInfo;
95118  if( pIdxInfo->orderByConsumed ){
95119    pCost->plan.wsFlags |= WHERE_ORDERBY;
95120  }
95121  pCost->plan.nEq = 0;
95122  pIdxInfo->nOrderBy = nOrderBy;
95123
95124  /* Try to find a more efficient access pattern by using multiple indexes
95125  ** to optimize an OR expression within the WHERE clause.
95126  */
95127  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
95128}
95129#endif /* SQLITE_OMIT_VIRTUALTABLE */
95130
95131/*
95132** Argument pIdx is a pointer to an index structure that has an array of
95133** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
95134** stored in Index.aSample. The domain of values stored in said column
95135** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
95136** Region 0 contains all values smaller than the first sample value. Region
95137** 1 contains values larger than or equal to the value of the first sample,
95138** but smaller than the value of the second. And so on.
95139**
95140** If successful, this function determines which of the regions value
95141** pVal lies in, sets *piRegion to the region index (a value between 0
95142** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
95143** Or, if an OOM occurs while converting text values between encodings,
95144** SQLITE_NOMEM is returned and *piRegion is undefined.
95145*/
95146#ifdef SQLITE_ENABLE_STAT2
95147static int whereRangeRegion(
95148  Parse *pParse,              /* Database connection */
95149  Index *pIdx,                /* Index to consider domain of */
95150  sqlite3_value *pVal,        /* Value to consider */
95151  int *piRegion               /* OUT: Region of domain in which value lies */
95152){
95153  if( ALWAYS(pVal) ){
95154    IndexSample *aSample = pIdx->aSample;
95155    int i = 0;
95156    int eType = sqlite3_value_type(pVal);
95157
95158    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
95159      double r = sqlite3_value_double(pVal);
95160      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95161        if( aSample[i].eType==SQLITE_NULL ) continue;
95162        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
95163      }
95164    }else{
95165      sqlite3 *db = pParse->db;
95166      CollSeq *pColl;
95167      const u8 *z;
95168      int n;
95169
95170      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
95171      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
95172
95173      if( eType==SQLITE_BLOB ){
95174        z = (const u8 *)sqlite3_value_blob(pVal);
95175        pColl = db->pDfltColl;
95176        assert( pColl->enc==SQLITE_UTF8 );
95177      }else{
95178        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
95179        if( pColl==0 ){
95180          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
95181                          *pIdx->azColl);
95182          return SQLITE_ERROR;
95183        }
95184        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
95185        if( !z ){
95186          return SQLITE_NOMEM;
95187        }
95188        assert( z && pColl && pColl->xCmp );
95189      }
95190      n = sqlite3ValueBytes(pVal, pColl->enc);
95191
95192      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95193        int r;
95194        int eSampletype = aSample[i].eType;
95195        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
95196        if( (eSampletype!=eType) ) break;
95197#ifndef SQLITE_OMIT_UTF16
95198        if( pColl->enc!=SQLITE_UTF8 ){
95199          int nSample;
95200          char *zSample = sqlite3Utf8to16(
95201              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
95202          );
95203          if( !zSample ){
95204            assert( db->mallocFailed );
95205            return SQLITE_NOMEM;
95206          }
95207          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
95208          sqlite3DbFree(db, zSample);
95209        }else
95210#endif
95211        {
95212          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
95213        }
95214        if( r>0 ) break;
95215      }
95216    }
95217
95218    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
95219    *piRegion = i;
95220  }
95221  return SQLITE_OK;
95222}
95223#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
95224
95225/*
95226** If expression pExpr represents a literal value, set *pp to point to
95227** an sqlite3_value structure containing the same value, with affinity
95228** aff applied to it, before returning. It is the responsibility of the
95229** caller to eventually release this structure by passing it to
95230** sqlite3ValueFree().
95231**
95232** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
95233** is an SQL variable that currently has a non-NULL value bound to it,
95234** create an sqlite3_value structure containing this value, again with
95235** affinity aff applied to it, instead.
95236**
95237** If neither of the above apply, set *pp to NULL.
95238**
95239** If an error occurs, return an error code. Otherwise, SQLITE_OK.
95240*/
95241#ifdef SQLITE_ENABLE_STAT2
95242static int valueFromExpr(
95243  Parse *pParse,
95244  Expr *pExpr,
95245  u8 aff,
95246  sqlite3_value **pp
95247){
95248  /* The evalConstExpr() function will have already converted any TK_VARIABLE
95249  ** expression involved in an comparison into a TK_REGISTER. */
95250  assert( pExpr->op!=TK_VARIABLE );
95251  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
95252    int iVar = pExpr->iColumn;
95253    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
95254    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
95255    return SQLITE_OK;
95256  }
95257  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
95258}
95259#endif
95260
95261/*
95262** This function is used to estimate the number of rows that will be visited
95263** by scanning an index for a range of values. The range may have an upper
95264** bound, a lower bound, or both. The WHERE clause terms that set the upper
95265** and lower bounds are represented by pLower and pUpper respectively. For
95266** example, assuming that index p is on t1(a):
95267**
95268**   ... FROM t1 WHERE a > ? AND a < ? ...
95269**                    |_____|   |_____|
95270**                       |         |
95271**                     pLower    pUpper
95272**
95273** If either of the upper or lower bound is not present, then NULL is passed in
95274** place of the corresponding WhereTerm.
95275**
95276** The nEq parameter is passed the index of the index column subject to the
95277** range constraint. Or, equivalently, the number of equality constraints
95278** optimized by the proposed index scan. For example, assuming index p is
95279** on t1(a, b), and the SQL query is:
95280**
95281**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
95282**
95283** then nEq should be passed the value 1 (as the range restricted column,
95284** b, is the second left-most column of the index). Or, if the query is:
95285**
95286**   ... FROM t1 WHERE a > ? AND a < ? ...
95287**
95288** then nEq should be passed 0.
95289**
95290** The returned value is an integer between 1 and 100, inclusive. A return
95291** value of 1 indicates that the proposed range scan is expected to visit
95292** approximately 1/100th (1%) of the rows selected by the nEq equality
95293** constraints (if any). A return value of 100 indicates that it is expected
95294** that the range scan will visit every row (100%) selected by the equality
95295** constraints.
95296**
95297** In the absence of sqlite_stat2 ANALYZE data, each range inequality
95298** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
95299** results in a return of 33 and a range constraint (x>? AND x<?) results
95300** in a return of 11.
95301*/
95302static int whereRangeScanEst(
95303  Parse *pParse,       /* Parsing & code generating context */
95304  Index *p,            /* The index containing the range-compared column; "x" */
95305  int nEq,             /* index into p->aCol[] of the range-compared column */
95306  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
95307  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
95308  int *piEst           /* OUT: Return value */
95309){
95310  int rc = SQLITE_OK;
95311
95312#ifdef SQLITE_ENABLE_STAT2
95313
95314  if( nEq==0 && p->aSample ){
95315    sqlite3_value *pLowerVal = 0;
95316    sqlite3_value *pUpperVal = 0;
95317    int iEst;
95318    int iLower = 0;
95319    int iUpper = SQLITE_INDEX_SAMPLES;
95320    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
95321
95322    if( pLower ){
95323      Expr *pExpr = pLower->pExpr->pRight;
95324      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
95325    }
95326    if( rc==SQLITE_OK && pUpper ){
95327      Expr *pExpr = pUpper->pExpr->pRight;
95328      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
95329    }
95330
95331    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
95332      sqlite3ValueFree(pLowerVal);
95333      sqlite3ValueFree(pUpperVal);
95334      goto range_est_fallback;
95335    }else if( pLowerVal==0 ){
95336      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95337      if( pLower ) iLower = iUpper/2;
95338    }else if( pUpperVal==0 ){
95339      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95340      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
95341    }else{
95342      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95343      if( rc==SQLITE_OK ){
95344        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95345      }
95346    }
95347
95348    iEst = iUpper - iLower;
95349    testcase( iEst==SQLITE_INDEX_SAMPLES );
95350    assert( iEst<=SQLITE_INDEX_SAMPLES );
95351    if( iEst<1 ){
95352      iEst = 1;
95353    }
95354
95355    sqlite3ValueFree(pLowerVal);
95356    sqlite3ValueFree(pUpperVal);
95357    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
95358    return rc;
95359  }
95360range_est_fallback:
95361#else
95362  UNUSED_PARAMETER(pParse);
95363  UNUSED_PARAMETER(p);
95364  UNUSED_PARAMETER(nEq);
95365#endif
95366  assert( pLower || pUpper );
95367  if( pLower && pUpper ){
95368    *piEst = 11;
95369  }else{
95370    *piEst = 33;
95371  }
95372  return rc;
95373}
95374
95375
95376/*
95377** Find the query plan for accessing a particular table.  Write the
95378** best query plan and its cost into the WhereCost object supplied as the
95379** last parameter.
95380**
95381** The lowest cost plan wins.  The cost is an estimate of the amount of
95382** CPU and disk I/O need to process the request using the selected plan.
95383** Factors that influence cost include:
95384**
95385**    *  The estimated number of rows that will be retrieved.  (The
95386**       fewer the better.)
95387**
95388**    *  Whether or not sorting must occur.
95389**
95390**    *  Whether or not there must be separate lookups in the
95391**       index and in the main table.
95392**
95393** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
95394** the SQL statement, then this function only considers plans using the
95395** named index. If no such plan is found, then the returned cost is
95396** SQLITE_BIG_DBL. If a plan is found that uses the named index,
95397** then the cost is calculated in the usual way.
95398**
95399** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
95400** in the SELECT statement, then no indexes are considered. However, the
95401** selected plan may still take advantage of the tables built-in rowid
95402** index.
95403*/
95404static void bestBtreeIndex(
95405  Parse *pParse,              /* The parsing context */
95406  WhereClause *pWC,           /* The WHERE clause */
95407  struct SrcList_item *pSrc,  /* The FROM clause term to search */
95408  Bitmask notReady,           /* Mask of cursors that are not available */
95409  ExprList *pOrderBy,         /* The ORDER BY clause */
95410  WhereCost *pCost            /* Lowest cost query plan */
95411){
95412  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
95413  Index *pProbe;              /* An index we are evaluating */
95414  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
95415  int eqTermMask;             /* Current mask of valid equality operators */
95416  int idxEqTermMask;          /* Index mask of valid equality operators */
95417  Index sPk;                  /* A fake index object for the primary key */
95418  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
95419  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
95420  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
95421
95422  /* Initialize the cost to a worst-case value */
95423  memset(pCost, 0, sizeof(*pCost));
95424  pCost->rCost = SQLITE_BIG_DBL;
95425
95426  /* If the pSrc table is the right table of a LEFT JOIN then we may not
95427  ** use an index to satisfy IS NULL constraints on that table.  This is
95428  ** because columns might end up being NULL if the table does not match -
95429  ** a circumstance which the index cannot help us discover.  Ticket #2177.
95430  */
95431  if( pSrc->jointype & JT_LEFT ){
95432    idxEqTermMask = WO_EQ|WO_IN;
95433  }else{
95434    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
95435  }
95436
95437  if( pSrc->pIndex ){
95438    /* An INDEXED BY clause specifies a particular index to use */
95439    pIdx = pProbe = pSrc->pIndex;
95440    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
95441    eqTermMask = idxEqTermMask;
95442  }else{
95443    /* There is no INDEXED BY clause.  Create a fake Index object to
95444    ** represent the primary key */
95445    Index *pFirst;                /* Any other index on the table */
95446    memset(&sPk, 0, sizeof(Index));
95447    sPk.nColumn = 1;
95448    sPk.aiColumn = &aiColumnPk;
95449    sPk.aiRowEst = aiRowEstPk;
95450    aiRowEstPk[1] = 1;
95451    sPk.onError = OE_Replace;
95452    sPk.pTable = pSrc->pTab;
95453    pFirst = pSrc->pTab->pIndex;
95454    if( pSrc->notIndexed==0 ){
95455      sPk.pNext = pFirst;
95456    }
95457    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
95458    ** table.  Get this information from the ANALYZE information if it is
95459    ** available.  If not available, assume the table 1 million rows in size.
95460    */
95461    if( pFirst ){
95462      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
95463      aiRowEstPk[0] = pFirst->aiRowEst[0];
95464    }else{
95465      aiRowEstPk[0] = 1000000;
95466    }
95467    pProbe = &sPk;
95468    wsFlagMask = ~(
95469        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
95470    );
95471    eqTermMask = WO_EQ|WO_IN;
95472    pIdx = 0;
95473  }
95474
95475  /* Loop over all indices looking for the best one to use
95476  */
95477  for(; pProbe; pIdx=pProbe=pProbe->pNext){
95478    const unsigned int * const aiRowEst = pProbe->aiRowEst;
95479    double cost;                /* Cost of using pProbe */
95480    double nRow;                /* Estimated number of rows in result set */
95481    int rev;                    /* True to scan in reverse order */
95482    int wsFlags = 0;
95483    Bitmask used = 0;
95484
95485    /* The following variables are populated based on the properties of
95486    ** scan being evaluated. They are then used to determine the expected
95487    ** cost and number of rows returned.
95488    **
95489    **  nEq:
95490    **    Number of equality terms that can be implemented using the index.
95491    **
95492    **  nInMul:
95493    **    The "in-multiplier". This is an estimate of how many seek operations
95494    **    SQLite must perform on the index in question. For example, if the
95495    **    WHERE clause is:
95496    **
95497    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
95498    **
95499    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
95500    **    set to 9. Given the same schema and either of the following WHERE
95501    **    clauses:
95502    **
95503    **      WHERE a =  1
95504    **      WHERE a >= 2
95505    **
95506    **    nInMul is set to 1.
95507    **
95508    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
95509    **    the sub-select is assumed to return 25 rows for the purposes of
95510    **    determining nInMul.
95511    **
95512    **  bInEst:
95513    **    Set to true if there was at least one "x IN (SELECT ...)" term used
95514    **    in determining the value of nInMul.
95515    **
95516    **  estBound:
95517    **    An estimate on the amount of the table that must be searched.  A
95518    **    value of 100 means the entire table is searched.  Range constraints
95519    **    might reduce this to a value less than 100 to indicate that only
95520    **    a fraction of the table needs searching.  In the absence of
95521    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
95522    **    space to 1/3rd its original size.  So an x>? constraint reduces
95523    **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
95524    **
95525    **  bSort:
95526    **    Boolean. True if there is an ORDER BY clause that will require an
95527    **    external sort (i.e. scanning the index being evaluated will not
95528    **    correctly order records).
95529    **
95530    **  bLookup:
95531    **    Boolean. True if for each index entry visited a lookup on the
95532    **    corresponding table b-tree is required. This is always false
95533    **    for the rowid index. For other indexes, it is true unless all the
95534    **    columns of the table used by the SELECT statement are present in
95535    **    the index (such an index is sometimes described as a covering index).
95536    **    For example, given the index on (a, b), the second of the following
95537    **    two queries requires table b-tree lookups, but the first does not.
95538    **
95539    **             SELECT a, b    FROM tbl WHERE a = 1;
95540    **             SELECT a, b, c FROM tbl WHERE a = 1;
95541    */
95542    int nEq;
95543    int bInEst = 0;
95544    int nInMul = 1;
95545    int estBound = 100;
95546    int nBound = 0;             /* Number of range constraints seen */
95547    int bSort = 0;
95548    int bLookup = 0;
95549    WhereTerm *pTerm;           /* A single term of the WHERE clause */
95550
95551    /* Determine the values of nEq and nInMul */
95552    for(nEq=0; nEq<pProbe->nColumn; nEq++){
95553      int j = pProbe->aiColumn[nEq];
95554      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
95555      if( pTerm==0 ) break;
95556      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
95557      if( pTerm->eOperator & WO_IN ){
95558        Expr *pExpr = pTerm->pExpr;
95559        wsFlags |= WHERE_COLUMN_IN;
95560        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95561          nInMul *= 25;
95562          bInEst = 1;
95563        }else if( pExpr->x.pList ){
95564          nInMul *= pExpr->x.pList->nExpr + 1;
95565        }
95566      }else if( pTerm->eOperator & WO_ISNULL ){
95567        wsFlags |= WHERE_COLUMN_NULL;
95568      }
95569      used |= pTerm->prereqRight;
95570    }
95571
95572    /* Determine the value of estBound. */
95573    if( nEq<pProbe->nColumn ){
95574      int j = pProbe->aiColumn[nEq];
95575      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
95576        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
95577        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
95578        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
95579        if( pTop ){
95580          nBound = 1;
95581          wsFlags |= WHERE_TOP_LIMIT;
95582          used |= pTop->prereqRight;
95583        }
95584        if( pBtm ){
95585          nBound++;
95586          wsFlags |= WHERE_BTM_LIMIT;
95587          used |= pBtm->prereqRight;
95588        }
95589        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
95590      }
95591    }else if( pProbe->onError!=OE_None ){
95592      testcase( wsFlags & WHERE_COLUMN_IN );
95593      testcase( wsFlags & WHERE_COLUMN_NULL );
95594      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
95595        wsFlags |= WHERE_UNIQUE;
95596      }
95597    }
95598
95599    /* If there is an ORDER BY clause and the index being considered will
95600    ** naturally scan rows in the required order, set the appropriate flags
95601    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
95602    ** will scan rows in a different order, set the bSort variable.  */
95603    if( pOrderBy ){
95604      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
95605        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
95606      ){
95607        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
95608        wsFlags |= (rev ? WHERE_REVERSE : 0);
95609      }else{
95610        bSort = 1;
95611      }
95612    }
95613
95614    /* If currently calculating the cost of using an index (not the IPK
95615    ** index), determine if all required column data may be obtained without
95616    ** using the main table (i.e. if the index is a covering
95617    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
95618    ** wsFlags. Otherwise, set the bLookup variable to true.  */
95619    if( pIdx && wsFlags ){
95620      Bitmask m = pSrc->colUsed;
95621      int j;
95622      for(j=0; j<pIdx->nColumn; j++){
95623        int x = pIdx->aiColumn[j];
95624        if( x<BMS-1 ){
95625          m &= ~(((Bitmask)1)<<x);
95626        }
95627      }
95628      if( m==0 ){
95629        wsFlags |= WHERE_IDX_ONLY;
95630      }else{
95631        bLookup = 1;
95632      }
95633    }
95634
95635    /*
95636    ** Estimate the number of rows of output.  For an IN operator,
95637    ** do not let the estimate exceed half the rows in the table.
95638    */
95639    nRow = (double)(aiRowEst[nEq] * nInMul);
95640    if( bInEst && nRow*2>aiRowEst[0] ){
95641      nRow = aiRowEst[0]/2;
95642      nInMul = (int)(nRow / aiRowEst[nEq]);
95643    }
95644
95645    /* Assume constant cost to access a row and logarithmic cost to
95646    ** do a binary search.  Hence, the initial cost is the number of output
95647    ** rows plus log2(table-size) times the number of binary searches.
95648    */
95649    cost = nRow + nInMul*estLog(aiRowEst[0]);
95650
95651    /* Adjust the number of rows and the cost downward to reflect rows
95652    ** that are excluded by range constraints.
95653    */
95654    nRow = (nRow * (double)estBound) / (double)100;
95655    cost = (cost * (double)estBound) / (double)100;
95656
95657    /* Add in the estimated cost of sorting the result
95658    */
95659    if( bSort ){
95660      cost += cost*estLog(cost);
95661    }
95662
95663    /* If all information can be taken directly from the index, we avoid
95664    ** doing table lookups.  This reduces the cost by half.  (Not really -
95665    ** this needs to be fixed.)
95666    */
95667    if( pIdx && bLookup==0 ){
95668      cost /= (double)2;
95669    }
95670    /**** Cost of using this index has now been computed ****/
95671
95672    /* If there are additional constraints on this table that cannot
95673    ** be used with the current index, but which might lower the number
95674    ** of output rows, adjust the nRow value accordingly.  This only
95675    ** matters if the current index is the least costly, so do not bother
95676    ** with this step if we already know this index will not be chosen.
95677    ** Also, never reduce the output row count below 2 using this step.
95678    **
95679    ** Do not reduce the output row count if pSrc is the only table that
95680    ** is notReady; if notReady is a power of two.  This will be the case
95681    ** when the main sqlite3WhereBegin() loop is scanning for a table with
95682    ** and "optimal" index, and on such a scan the output row count
95683    ** reduction is not valid because it does not update the "pCost->used"
95684    ** bitmap.  The notReady bitmap will also be a power of two when we
95685    ** are scanning for the last table in a 64-way join.  We are willing
95686    ** to bypass this optimization in that corner case.
95687    */
95688    if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
95689      int k;                       /* Loop counter */
95690      int nSkipEq = nEq;           /* Number of == constraints to skip */
95691      int nSkipRange = nBound;     /* Number of < constraints to skip */
95692      Bitmask thisTab;             /* Bitmap for pSrc */
95693
95694      thisTab = getMask(pWC->pMaskSet, iCur);
95695      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
95696        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
95697        if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
95698        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
95699          if( nSkipEq ){
95700            /* Ignore the first nEq equality matches since the index
95701            ** has already accounted for these */
95702            nSkipEq--;
95703          }else{
95704            /* Assume each additional equality match reduces the result
95705            ** set size by a factor of 10 */
95706            nRow /= 10;
95707          }
95708        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
95709          if( nSkipRange ){
95710            /* Ignore the first nBound range constraints since the index
95711            ** has already accounted for these */
95712            nSkipRange--;
95713          }else{
95714            /* Assume each additional range constraint reduces the result
95715            ** set size by a factor of 3 */
95716            nRow /= 3;
95717          }
95718        }else{
95719          /* Any other expression lowers the output row count by half */
95720          nRow /= 2;
95721        }
95722      }
95723      if( nRow<2 ) nRow = 2;
95724    }
95725
95726
95727    WHERETRACE((
95728      "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
95729      "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
95730      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
95731      nEq, nInMul, estBound, bSort, bLookup, wsFlags,
95732      notReady, nRow, cost, used
95733    ));
95734
95735    /* If this index is the best we have seen so far, then record this
95736    ** index and its cost in the pCost structure.
95737    */
95738    if( (!pIdx || wsFlags)
95739     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
95740    ){
95741      pCost->rCost = cost;
95742      pCost->nRow = nRow;
95743      pCost->used = used;
95744      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
95745      pCost->plan.nEq = nEq;
95746      pCost->plan.u.pIdx = pIdx;
95747    }
95748
95749    /* If there was an INDEXED BY clause, then only that one index is
95750    ** considered. */
95751    if( pSrc->pIndex ) break;
95752
95753    /* Reset masks for the next index in the loop */
95754    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
95755    eqTermMask = idxEqTermMask;
95756  }
95757
95758  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
95759  ** is set, then reverse the order that the index will be scanned
95760  ** in. This is used for application testing, to help find cases
95761  ** where application behaviour depends on the (undefined) order that
95762  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
95763  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
95764    pCost->plan.wsFlags |= WHERE_REVERSE;
95765  }
95766
95767  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
95768  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
95769  assert( pSrc->pIndex==0
95770       || pCost->plan.u.pIdx==0
95771       || pCost->plan.u.pIdx==pSrc->pIndex
95772  );
95773
95774  WHERETRACE(("best index is: %s\n",
95775    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
95776         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
95777  ));
95778
95779  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
95780  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
95781  pCost->plan.wsFlags |= eqTermMask;
95782}
95783
95784/*
95785** Find the query plan for accessing table pSrc->pTab. Write the
95786** best query plan and its cost into the WhereCost object supplied
95787** as the last parameter. This function may calculate the cost of
95788** both real and virtual table scans.
95789*/
95790static void bestIndex(
95791  Parse *pParse,              /* The parsing context */
95792  WhereClause *pWC,           /* The WHERE clause */
95793  struct SrcList_item *pSrc,  /* The FROM clause term to search */
95794  Bitmask notReady,           /* Mask of cursors that are not available */
95795  ExprList *pOrderBy,         /* The ORDER BY clause */
95796  WhereCost *pCost            /* Lowest cost query plan */
95797){
95798#ifndef SQLITE_OMIT_VIRTUALTABLE
95799  if( IsVirtual(pSrc->pTab) ){
95800    sqlite3_index_info *p = 0;
95801    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
95802    if( p->needToFreeIdxStr ){
95803      sqlite3_free(p->idxStr);
95804    }
95805    sqlite3DbFree(pParse->db, p);
95806  }else
95807#endif
95808  {
95809    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
95810  }
95811}
95812
95813/*
95814** Disable a term in the WHERE clause.  Except, do not disable the term
95815** if it controls a LEFT OUTER JOIN and it did not originate in the ON
95816** or USING clause of that join.
95817**
95818** Consider the term t2.z='ok' in the following queries:
95819**
95820**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
95821**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
95822**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
95823**
95824** The t2.z='ok' is disabled in the in (2) because it originates
95825** in the ON clause.  The term is disabled in (3) because it is not part
95826** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
95827**
95828** Disabling a term causes that term to not be tested in the inner loop
95829** of the join.  Disabling is an optimization.  When terms are satisfied
95830** by indices, we disable them to prevent redundant tests in the inner
95831** loop.  We would get the correct results if nothing were ever disabled,
95832** but joins might run a little slower.  The trick is to disable as much
95833** as we can without disabling too much.  If we disabled in (1), we'd get
95834** the wrong answer.  See ticket #813.
95835*/
95836static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
95837  if( pTerm
95838      && (pTerm->wtFlags & TERM_CODED)==0
95839      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
95840  ){
95841    pTerm->wtFlags |= TERM_CODED;
95842    if( pTerm->iParent>=0 ){
95843      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
95844      if( (--pOther->nChild)==0 ){
95845        disableTerm(pLevel, pOther);
95846      }
95847    }
95848  }
95849}
95850
95851/*
95852** Code an OP_Affinity opcode to apply the column affinity string zAff
95853** to the n registers starting at base.
95854**
95855** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
95856** beginning and end of zAff are ignored.  If all entries in zAff are
95857** SQLITE_AFF_NONE, then no code gets generated.
95858**
95859** This routine makes its own copy of zAff so that the caller is free
95860** to modify zAff after this routine returns.
95861*/
95862static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
95863  Vdbe *v = pParse->pVdbe;
95864  if( zAff==0 ){
95865    assert( pParse->db->mallocFailed );
95866    return;
95867  }
95868  assert( v!=0 );
95869
95870  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
95871  ** and end of the affinity string.
95872  */
95873  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
95874    n--;
95875    base++;
95876    zAff++;
95877  }
95878  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
95879    n--;
95880  }
95881
95882  /* Code the OP_Affinity opcode if there is anything left to do. */
95883  if( n>0 ){
95884    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
95885    sqlite3VdbeChangeP4(v, -1, zAff, n);
95886    sqlite3ExprCacheAffinityChange(pParse, base, n);
95887  }
95888}
95889
95890
95891/*
95892** Generate code for a single equality term of the WHERE clause.  An equality
95893** term can be either X=expr or X IN (...).   pTerm is the term to be
95894** coded.
95895**
95896** The current value for the constraint is left in register iReg.
95897**
95898** For a constraint of the form X=expr, the expression is evaluated and its
95899** result is left on the stack.  For constraints of the form X IN (...)
95900** this routine sets up a loop that will iterate over all values of X.
95901*/
95902static int codeEqualityTerm(
95903  Parse *pParse,      /* The parsing context */
95904  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
95905  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
95906  int iTarget         /* Attempt to leave results in this register */
95907){
95908  Expr *pX = pTerm->pExpr;
95909  Vdbe *v = pParse->pVdbe;
95910  int iReg;                  /* Register holding results */
95911
95912  assert( iTarget>0 );
95913  if( pX->op==TK_EQ ){
95914    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
95915  }else if( pX->op==TK_ISNULL ){
95916    iReg = iTarget;
95917    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
95918#ifndef SQLITE_OMIT_SUBQUERY
95919  }else{
95920    int eType;
95921    int iTab;
95922    struct InLoop *pIn;
95923
95924    assert( pX->op==TK_IN );
95925    iReg = iTarget;
95926    eType = sqlite3FindInIndex(pParse, pX, 0);
95927    iTab = pX->iTable;
95928    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
95929    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
95930    if( pLevel->u.in.nIn==0 ){
95931      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
95932    }
95933    pLevel->u.in.nIn++;
95934    pLevel->u.in.aInLoop =
95935       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
95936                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
95937    pIn = pLevel->u.in.aInLoop;
95938    if( pIn ){
95939      pIn += pLevel->u.in.nIn - 1;
95940      pIn->iCur = iTab;
95941      if( eType==IN_INDEX_ROWID ){
95942        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
95943      }else{
95944        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
95945      }
95946      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
95947    }else{
95948      pLevel->u.in.nIn = 0;
95949    }
95950#endif
95951  }
95952  disableTerm(pLevel, pTerm);
95953  return iReg;
95954}
95955
95956/*
95957** Generate code that will evaluate all == and IN constraints for an
95958** index.
95959**
95960** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
95961** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
95962** The index has as many as three equality constraints, but in this
95963** example, the third "c" value is an inequality.  So only two
95964** constraints are coded.  This routine will generate code to evaluate
95965** a==5 and b IN (1,2,3).  The current values for a and b will be stored
95966** in consecutive registers and the index of the first register is returned.
95967**
95968** In the example above nEq==2.  But this subroutine works for any value
95969** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
95970** The only thing it does is allocate the pLevel->iMem memory cell and
95971** compute the affinity string.
95972**
95973** This routine always allocates at least one memory cell and returns
95974** the index of that memory cell. The code that
95975** calls this routine will use that memory cell to store the termination
95976** key value of the loop.  If one or more IN operators appear, then
95977** this routine allocates an additional nEq memory cells for internal
95978** use.
95979**
95980** Before returning, *pzAff is set to point to a buffer containing a
95981** copy of the column affinity string of the index allocated using
95982** sqlite3DbMalloc(). Except, entries in the copy of the string associated
95983** with equality constraints that use NONE affinity are set to
95984** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
95985**
95986**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
95987**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
95988**
95989** In the example above, the index on t1(a) has TEXT affinity. But since
95990** the right hand side of the equality constraint (t2.b) has NONE affinity,
95991** no conversion should be attempted before using a t2.b value as part of
95992** a key to search the index. Hence the first byte in the returned affinity
95993** string in this example would be set to SQLITE_AFF_NONE.
95994*/
95995static int codeAllEqualityTerms(
95996  Parse *pParse,        /* Parsing context */
95997  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
95998  WhereClause *pWC,     /* The WHERE clause */
95999  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
96000  int nExtraReg,        /* Number of extra registers to allocate */
96001  char **pzAff          /* OUT: Set to point to affinity string */
96002){
96003  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
96004  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
96005  Index *pIdx;                  /* The index being used for this loop */
96006  int iCur = pLevel->iTabCur;   /* The cursor of the table */
96007  WhereTerm *pTerm;             /* A single constraint term */
96008  int j;                        /* Loop counter */
96009  int regBase;                  /* Base register */
96010  int nReg;                     /* Number of registers to allocate */
96011  char *zAff;                   /* Affinity string to return */
96012
96013  /* This module is only called on query plans that use an index. */
96014  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
96015  pIdx = pLevel->plan.u.pIdx;
96016
96017  /* Figure out how many memory cells we will need then allocate them.
96018  */
96019  regBase = pParse->nMem + 1;
96020  nReg = pLevel->plan.nEq + nExtraReg;
96021  pParse->nMem += nReg;
96022
96023  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
96024  if( !zAff ){
96025    pParse->db->mallocFailed = 1;
96026  }
96027
96028  /* Evaluate the equality constraints
96029  */
96030  assert( pIdx->nColumn>=nEq );
96031  for(j=0; j<nEq; j++){
96032    int r1;
96033    int k = pIdx->aiColumn[j];
96034    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
96035    if( NEVER(pTerm==0) ) break;
96036    /* The following true for indices with redundant columns.
96037    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
96038    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
96039    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
96040    if( r1!=regBase+j ){
96041      if( nReg==1 ){
96042        sqlite3ReleaseTempReg(pParse, regBase);
96043        regBase = r1;
96044      }else{
96045        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
96046      }
96047    }
96048    testcase( pTerm->eOperator & WO_ISNULL );
96049    testcase( pTerm->eOperator & WO_IN );
96050    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
96051      Expr *pRight = pTerm->pExpr->pRight;
96052      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
96053      if( zAff ){
96054        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
96055          zAff[j] = SQLITE_AFF_NONE;
96056        }
96057        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
96058          zAff[j] = SQLITE_AFF_NONE;
96059        }
96060      }
96061    }
96062  }
96063  *pzAff = zAff;
96064  return regBase;
96065}
96066
96067/*
96068** Generate code for the start of the iLevel-th loop in the WHERE clause
96069** implementation described by pWInfo.
96070*/
96071static Bitmask codeOneLoopStart(
96072  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
96073  int iLevel,          /* Which level of pWInfo->a[] should be coded */
96074  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
96075  Bitmask notReady     /* Which tables are currently available */
96076){
96077  int j, k;            /* Loop counters */
96078  int iCur;            /* The VDBE cursor for the table */
96079  int addrNxt;         /* Where to jump to continue with the next IN case */
96080  int omitTable;       /* True if we use the index only */
96081  int bRev;            /* True if we need to scan in reverse order */
96082  WhereLevel *pLevel;  /* The where level to be coded */
96083  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
96084  WhereTerm *pTerm;               /* A WHERE clause term */
96085  Parse *pParse;                  /* Parsing context */
96086  Vdbe *v;                        /* The prepared stmt under constructions */
96087  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
96088  int addrBrk;                    /* Jump here to break out of the loop */
96089  int addrCont;                   /* Jump here to continue with next cycle */
96090  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
96091  int iReleaseReg = 0;      /* Temp register to free before returning */
96092
96093  pParse = pWInfo->pParse;
96094  v = pParse->pVdbe;
96095  pWC = pWInfo->pWC;
96096  pLevel = &pWInfo->a[iLevel];
96097  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
96098  iCur = pTabItem->iCursor;
96099  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
96100  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
96101           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
96102
96103  /* Create labels for the "break" and "continue" instructions
96104  ** for the current loop.  Jump to addrBrk to break out of a loop.
96105  ** Jump to cont to go immediately to the next iteration of the
96106  ** loop.
96107  **
96108  ** When there is an IN operator, we also have a "addrNxt" label that
96109  ** means to continue with the next IN value combination.  When
96110  ** there are no IN operators in the constraints, the "addrNxt" label
96111  ** is the same as "addrBrk".
96112  */
96113  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
96114  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
96115
96116  /* If this is the right table of a LEFT OUTER JOIN, allocate and
96117  ** initialize a memory cell that records if this table matches any
96118  ** row of the left table of the join.
96119  */
96120  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
96121    pLevel->iLeftJoin = ++pParse->nMem;
96122    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
96123    VdbeComment((v, "init LEFT JOIN no-match flag"));
96124  }
96125
96126#ifndef SQLITE_OMIT_VIRTUALTABLE
96127  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
96128    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
96129    **          to access the data.
96130    */
96131    int iReg;   /* P3 Value for OP_VFilter */
96132    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
96133    int nConstraint = pVtabIdx->nConstraint;
96134    struct sqlite3_index_constraint_usage *aUsage =
96135                                                pVtabIdx->aConstraintUsage;
96136    const struct sqlite3_index_constraint *aConstraint =
96137                                                pVtabIdx->aConstraint;
96138
96139    sqlite3ExprCachePush(pParse);
96140    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
96141    for(j=1; j<=nConstraint; j++){
96142      for(k=0; k<nConstraint; k++){
96143        if( aUsage[k].argvIndex==j ){
96144          int iTerm = aConstraint[k].iTermOffset;
96145          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
96146          break;
96147        }
96148      }
96149      if( k==nConstraint ) break;
96150    }
96151    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
96152    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
96153    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
96154                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
96155    pVtabIdx->needToFreeIdxStr = 0;
96156    for(j=0; j<nConstraint; j++){
96157      if( aUsage[j].omit ){
96158        int iTerm = aConstraint[j].iTermOffset;
96159        disableTerm(pLevel, &pWC->a[iTerm]);
96160      }
96161    }
96162    pLevel->op = OP_VNext;
96163    pLevel->p1 = iCur;
96164    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96165    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
96166    sqlite3ExprCachePop(pParse, 1);
96167  }else
96168#endif /* SQLITE_OMIT_VIRTUALTABLE */
96169
96170  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
96171    /* Case 1:  We can directly reference a single row using an
96172    **          equality comparison against the ROWID field.  Or
96173    **          we reference multiple rows using a "rowid IN (...)"
96174    **          construct.
96175    */
96176    iReleaseReg = sqlite3GetTempReg(pParse);
96177    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
96178    assert( pTerm!=0 );
96179    assert( pTerm->pExpr!=0 );
96180    assert( pTerm->leftCursor==iCur );
96181    assert( omitTable==0 );
96182    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
96183    addrNxt = pLevel->addrNxt;
96184    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
96185    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
96186    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96187    VdbeComment((v, "pk"));
96188    pLevel->op = OP_Noop;
96189  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
96190    /* Case 2:  We have an inequality comparison against the ROWID field.
96191    */
96192    int testOp = OP_Noop;
96193    int start;
96194    int memEndValue = 0;
96195    WhereTerm *pStart, *pEnd;
96196
96197    assert( omitTable==0 );
96198    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
96199    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
96200    if( bRev ){
96201      pTerm = pStart;
96202      pStart = pEnd;
96203      pEnd = pTerm;
96204    }
96205    if( pStart ){
96206      Expr *pX;             /* The expression that defines the start bound */
96207      int r1, rTemp;        /* Registers for holding the start boundary */
96208
96209      /* The following constant maps TK_xx codes into corresponding
96210      ** seek opcodes.  It depends on a particular ordering of TK_xx
96211      */
96212      const u8 aMoveOp[] = {
96213           /* TK_GT */  OP_SeekGt,
96214           /* TK_LE */  OP_SeekLe,
96215           /* TK_LT */  OP_SeekLt,
96216           /* TK_GE */  OP_SeekGe
96217      };
96218      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
96219      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
96220      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
96221
96222      pX = pStart->pExpr;
96223      assert( pX!=0 );
96224      assert( pStart->leftCursor==iCur );
96225      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
96226      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
96227      VdbeComment((v, "pk"));
96228      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
96229      sqlite3ReleaseTempReg(pParse, rTemp);
96230      disableTerm(pLevel, pStart);
96231    }else{
96232      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
96233    }
96234    if( pEnd ){
96235      Expr *pX;
96236      pX = pEnd->pExpr;
96237      assert( pX!=0 );
96238      assert( pEnd->leftCursor==iCur );
96239      memEndValue = ++pParse->nMem;
96240      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
96241      if( pX->op==TK_LT || pX->op==TK_GT ){
96242        testOp = bRev ? OP_Le : OP_Ge;
96243      }else{
96244        testOp = bRev ? OP_Lt : OP_Gt;
96245      }
96246      disableTerm(pLevel, pEnd);
96247    }
96248    start = sqlite3VdbeCurrentAddr(v);
96249    pLevel->op = bRev ? OP_Prev : OP_Next;
96250    pLevel->p1 = iCur;
96251    pLevel->p2 = start;
96252    if( pStart==0 && pEnd==0 ){
96253      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
96254    }else{
96255      assert( pLevel->p5==0 );
96256    }
96257    if( testOp!=OP_Noop ){
96258      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96259      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
96260      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96261      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
96262      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
96263    }
96264  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
96265    /* Case 3: A scan using an index.
96266    **
96267    **         The WHERE clause may contain zero or more equality
96268    **         terms ("==" or "IN" operators) that refer to the N
96269    **         left-most columns of the index. It may also contain
96270    **         inequality constraints (>, <, >= or <=) on the indexed
96271    **         column that immediately follows the N equalities. Only
96272    **         the right-most column can be an inequality - the rest must
96273    **         use the "==" and "IN" operators. For example, if the
96274    **         index is on (x,y,z), then the following clauses are all
96275    **         optimized:
96276    **
96277    **            x=5
96278    **            x=5 AND y=10
96279    **            x=5 AND y<10
96280    **            x=5 AND y>5 AND y<10
96281    **            x=5 AND y=5 AND z<=10
96282    **
96283    **         The z<10 term of the following cannot be used, only
96284    **         the x=5 term:
96285    **
96286    **            x=5 AND z<10
96287    **
96288    **         N may be zero if there are inequality constraints.
96289    **         If there are no inequality constraints, then N is at
96290    **         least one.
96291    **
96292    **         This case is also used when there are no WHERE clause
96293    **         constraints but an index is selected anyway, in order
96294    **         to force the output order to conform to an ORDER BY.
96295    */
96296    int aStartOp[] = {
96297      0,
96298      0,
96299      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
96300      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
96301      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
96302      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
96303      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
96304      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
96305    };
96306    int aEndOp[] = {
96307      OP_Noop,             /* 0: (!end_constraints) */
96308      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
96309      OP_IdxLT             /* 2: (end_constraints && bRev) */
96310    };
96311    int nEq = pLevel->plan.nEq;
96312    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
96313    int regBase;                 /* Base register holding constraint values */
96314    int r1;                      /* Temp register */
96315    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
96316    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
96317    int startEq;                 /* True if range start uses ==, >= or <= */
96318    int endEq;                   /* True if range end uses ==, >= or <= */
96319    int start_constraints;       /* Start of range is constrained */
96320    int nConstraint;             /* Number of constraint terms */
96321    Index *pIdx;         /* The index we will be using */
96322    int iIdxCur;         /* The VDBE cursor for the index */
96323    int nExtraReg = 0;   /* Number of extra registers needed */
96324    int op;              /* Instruction opcode */
96325    char *zStartAff;             /* Affinity for start of range constraint */
96326    char *zEndAff;               /* Affinity for end of range constraint */
96327
96328    pIdx = pLevel->plan.u.pIdx;
96329    iIdxCur = pLevel->iIdxCur;
96330    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
96331
96332    /* If this loop satisfies a sort order (pOrderBy) request that
96333    ** was passed to this function to implement a "SELECT min(x) ..."
96334    ** query, then the caller will only allow the loop to run for
96335    ** a single iteration. This means that the first row returned
96336    ** should not have a NULL value stored in 'x'. If column 'x' is
96337    ** the first one after the nEq equality constraints in the index,
96338    ** this requires some special handling.
96339    */
96340    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
96341     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
96342     && (pIdx->nColumn>nEq)
96343    ){
96344      /* assert( pOrderBy->nExpr==1 ); */
96345      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
96346      isMinQuery = 1;
96347      nExtraReg = 1;
96348    }
96349
96350    /* Find any inequality constraint terms for the start and end
96351    ** of the range.
96352    */
96353    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
96354      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
96355      nExtraReg = 1;
96356    }
96357    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
96358      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
96359      nExtraReg = 1;
96360    }
96361
96362    /* Generate code to evaluate all constraint terms using == or IN
96363    ** and store the values of those terms in an array of registers
96364    ** starting at regBase.
96365    */
96366    regBase = codeAllEqualityTerms(
96367        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
96368    );
96369    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
96370    addrNxt = pLevel->addrNxt;
96371
96372    /* If we are doing a reverse order scan on an ascending index, or
96373    ** a forward order scan on a descending index, interchange the
96374    ** start and end terms (pRangeStart and pRangeEnd).
96375    */
96376    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
96377      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
96378    }
96379
96380    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
96381    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
96382    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
96383    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
96384    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
96385    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
96386    start_constraints = pRangeStart || nEq>0;
96387
96388    /* Seek the index cursor to the start of the range. */
96389    nConstraint = nEq;
96390    if( pRangeStart ){
96391      Expr *pRight = pRangeStart->pExpr->pRight;
96392      sqlite3ExprCode(pParse, pRight, regBase+nEq);
96393      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96394      if( zStartAff ){
96395        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
96396          /* Since the comparison is to be performed with no conversions
96397          ** applied to the operands, set the affinity to apply to pRight to
96398          ** SQLITE_AFF_NONE.  */
96399          zStartAff[nEq] = SQLITE_AFF_NONE;
96400        }
96401        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
96402          zStartAff[nEq] = SQLITE_AFF_NONE;
96403        }
96404      }
96405      nConstraint++;
96406    }else if( isMinQuery ){
96407      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
96408      nConstraint++;
96409      startEq = 0;
96410      start_constraints = 1;
96411    }
96412    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
96413    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
96414    assert( op!=0 );
96415    testcase( op==OP_Rewind );
96416    testcase( op==OP_Last );
96417    testcase( op==OP_SeekGt );
96418    testcase( op==OP_SeekGe );
96419    testcase( op==OP_SeekLe );
96420    testcase( op==OP_SeekLt );
96421    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96422
96423    /* Load the value for the inequality constraint at the end of the
96424    ** range (if any).
96425    */
96426    nConstraint = nEq;
96427    if( pRangeEnd ){
96428      Expr *pRight = pRangeEnd->pExpr->pRight;
96429      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
96430      sqlite3ExprCode(pParse, pRight, regBase+nEq);
96431      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96432      if( zEndAff ){
96433        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
96434          /* Since the comparison is to be performed with no conversions
96435          ** applied to the operands, set the affinity to apply to pRight to
96436          ** SQLITE_AFF_NONE.  */
96437          zEndAff[nEq] = SQLITE_AFF_NONE;
96438        }
96439        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
96440          zEndAff[nEq] = SQLITE_AFF_NONE;
96441        }
96442      }
96443      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
96444      nConstraint++;
96445    }
96446    sqlite3DbFree(pParse->db, zStartAff);
96447    sqlite3DbFree(pParse->db, zEndAff);
96448
96449    /* Top of the loop body */
96450    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96451
96452    /* Check if the index cursor is past the end of the range. */
96453    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
96454    testcase( op==OP_Noop );
96455    testcase( op==OP_IdxGE );
96456    testcase( op==OP_IdxLT );
96457    if( op!=OP_Noop ){
96458      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96459      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
96460    }
96461
96462    /* If there are inequality constraints, check that the value
96463    ** of the table column that the inequality contrains is not NULL.
96464    ** If it is, jump to the next iteration of the loop.
96465    */
96466    r1 = sqlite3GetTempReg(pParse);
96467    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
96468    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
96469    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
96470      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
96471      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
96472    }
96473    sqlite3ReleaseTempReg(pParse, r1);
96474
96475    /* Seek the table cursor, if required */
96476    disableTerm(pLevel, pRangeStart);
96477    disableTerm(pLevel, pRangeEnd);
96478    if( !omitTable ){
96479      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96480      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
96481      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96482      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
96483    }
96484
96485    /* Record the instruction used to terminate the loop. Disable
96486    ** WHERE clause terms made redundant by the index range scan.
96487    */
96488    pLevel->op = bRev ? OP_Prev : OP_Next;
96489    pLevel->p1 = iIdxCur;
96490  }else
96491
96492#ifndef SQLITE_OMIT_OR_OPTIMIZATION
96493  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
96494    /* Case 4:  Two or more separately indexed terms connected by OR
96495    **
96496    ** Example:
96497    **
96498    **   CREATE TABLE t1(a,b,c,d);
96499    **   CREATE INDEX i1 ON t1(a);
96500    **   CREATE INDEX i2 ON t1(b);
96501    **   CREATE INDEX i3 ON t1(c);
96502    **
96503    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
96504    **
96505    ** In the example, there are three indexed terms connected by OR.
96506    ** The top of the loop looks like this:
96507    **
96508    **          Null       1                # Zero the rowset in reg 1
96509    **
96510    ** Then, for each indexed term, the following. The arguments to
96511    ** RowSetTest are such that the rowid of the current row is inserted
96512    ** into the RowSet. If it is already present, control skips the
96513    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
96514    **
96515    **        sqlite3WhereBegin(<term>)
96516    **          RowSetTest                  # Insert rowid into rowset
96517    **          Gosub      2 A
96518    **        sqlite3WhereEnd()
96519    **
96520    ** Following the above, code to terminate the loop. Label A, the target
96521    ** of the Gosub above, jumps to the instruction right after the Goto.
96522    **
96523    **          Null       1                # Zero the rowset in reg 1
96524    **          Goto       B                # The loop is finished.
96525    **
96526    **       A: <loop body>                 # Return data, whatever.
96527    **
96528    **          Return     2                # Jump back to the Gosub
96529    **
96530    **       B: <after the loop>
96531    **
96532    */
96533    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
96534    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
96535    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
96536
96537    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
96538    int regRowset = 0;                        /* Register for RowSet object */
96539    int regRowid = 0;                         /* Register holding rowid */
96540    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
96541    int iRetInit;                             /* Address of regReturn init */
96542    int untestedTerms = 0;             /* Some terms not completely tested */
96543    int ii;
96544
96545    pTerm = pLevel->plan.u.pTerm;
96546    assert( pTerm!=0 );
96547    assert( pTerm->eOperator==WO_OR );
96548    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
96549    pOrWc = &pTerm->u.pOrInfo->wc;
96550    pFinal = &pOrWc->a[pOrWc->nTerm-1];
96551    pLevel->op = OP_Return;
96552    pLevel->p1 = regReturn;
96553
96554    /* Set up a new SrcList ni pOrTab containing the table being scanned
96555    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
96556    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
96557    */
96558    if( pWInfo->nLevel>1 ){
96559      int nNotReady;                 /* The number of notReady tables */
96560      struct SrcList_item *origSrc;     /* Original list of tables */
96561      nNotReady = pWInfo->nLevel - iLevel - 1;
96562      pOrTab = sqlite3StackAllocRaw(pParse->db,
96563                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
96564      if( pOrTab==0 ) return notReady;
96565      pOrTab->nAlloc = (i16)(nNotReady + 1);
96566      pOrTab->nSrc = pOrTab->nAlloc;
96567      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
96568      origSrc = pWInfo->pTabList->a;
96569      for(k=1; k<=nNotReady; k++){
96570        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
96571      }
96572    }else{
96573      pOrTab = pWInfo->pTabList;
96574    }
96575
96576    /* Initialize the rowset register to contain NULL. An SQL NULL is
96577    ** equivalent to an empty rowset.
96578    **
96579    ** Also initialize regReturn to contain the address of the instruction
96580    ** immediately following the OP_Return at the bottom of the loop. This
96581    ** is required in a few obscure LEFT JOIN cases where control jumps
96582    ** over the top of the loop into the body of it. In this case the
96583    ** correct response for the end-of-loop code (the OP_Return) is to
96584    ** fall through to the next instruction, just as an OP_Next does if
96585    ** called on an uninitialized cursor.
96586    */
96587    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96588      regRowset = ++pParse->nMem;
96589      regRowid = ++pParse->nMem;
96590      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
96591    }
96592    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
96593
96594    for(ii=0; ii<pOrWc->nTerm; ii++){
96595      WhereTerm *pOrTerm = &pOrWc->a[ii];
96596      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
96597        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
96598        /* Loop through table entries that match term pOrTerm. */
96599        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
96600                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
96601                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
96602        if( pSubWInfo ){
96603          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96604            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
96605            int r;
96606            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
96607                                         regRowid);
96608            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
96609                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
96610          }
96611          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
96612
96613          /* The pSubWInfo->untestedTerms flag means that this OR term
96614          ** contained one or more AND term from a notReady table.  The
96615          ** terms from the notReady table could not be tested and will
96616          ** need to be tested later.
96617          */
96618          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
96619
96620          /* Finish the loop through table entries that match term pOrTerm. */
96621          sqlite3WhereEnd(pSubWInfo);
96622        }
96623      }
96624    }
96625    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
96626    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
96627    sqlite3VdbeResolveLabel(v, iLoopBody);
96628
96629    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
96630    if( !untestedTerms ) disableTerm(pLevel, pTerm);
96631  }else
96632#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96633
96634  {
96635    /* Case 5:  There is no usable index.  We must do a complete
96636    **          scan of the entire table.
96637    */
96638    static const u8 aStep[] = { OP_Next, OP_Prev };
96639    static const u8 aStart[] = { OP_Rewind, OP_Last };
96640    assert( bRev==0 || bRev==1 );
96641    assert( omitTable==0 );
96642    pLevel->op = aStep[bRev];
96643    pLevel->p1 = iCur;
96644    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
96645    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
96646  }
96647  notReady &= ~getMask(pWC->pMaskSet, iCur);
96648
96649  /* Insert code to test every subexpression that can be completely
96650  ** computed using the current set of tables.
96651  */
96652  k = 0;
96653  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
96654    Expr *pE;
96655    testcase( pTerm->wtFlags & TERM_VIRTUAL );
96656    testcase( pTerm->wtFlags & TERM_CODED );
96657    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
96658    if( (pTerm->prereqAll & notReady)!=0 ){
96659      testcase( pWInfo->untestedTerms==0
96660               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
96661      pWInfo->untestedTerms = 1;
96662      continue;
96663    }
96664    pE = pTerm->pExpr;
96665    assert( pE!=0 );
96666    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
96667      continue;
96668    }
96669    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
96670    k = 1;
96671    pTerm->wtFlags |= TERM_CODED;
96672  }
96673
96674  /* For a LEFT OUTER JOIN, generate code that will record the fact that
96675  ** at least one row of the right table has matched the left table.
96676  */
96677  if( pLevel->iLeftJoin ){
96678    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
96679    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
96680    VdbeComment((v, "record LEFT JOIN hit"));
96681    sqlite3ExprCacheClear(pParse);
96682    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
96683      testcase( pTerm->wtFlags & TERM_VIRTUAL );
96684      testcase( pTerm->wtFlags & TERM_CODED );
96685      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
96686      if( (pTerm->prereqAll & notReady)!=0 ){
96687        assert( pWInfo->untestedTerms );
96688        continue;
96689      }
96690      assert( pTerm->pExpr );
96691      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
96692      pTerm->wtFlags |= TERM_CODED;
96693    }
96694  }
96695  sqlite3ReleaseTempReg(pParse, iReleaseReg);
96696
96697  return notReady;
96698}
96699
96700#if defined(SQLITE_TEST)
96701/*
96702** The following variable holds a text description of query plan generated
96703** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
96704** overwrites the previous.  This information is used for testing and
96705** analysis only.
96706*/
96707SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
96708static int nQPlan = 0;              /* Next free slow in _query_plan[] */
96709
96710#endif /* SQLITE_TEST */
96711
96712
96713/*
96714** Free a WhereInfo structure
96715*/
96716static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
96717  if( ALWAYS(pWInfo) ){
96718    int i;
96719    for(i=0; i<pWInfo->nLevel; i++){
96720      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
96721      if( pInfo ){
96722        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
96723        if( pInfo->needToFreeIdxStr ){
96724          sqlite3_free(pInfo->idxStr);
96725        }
96726        sqlite3DbFree(db, pInfo);
96727      }
96728      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
96729        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
96730        if( pIdx ){
96731          sqlite3DbFree(db, pIdx->zColAff);
96732          sqlite3DbFree(db, pIdx);
96733        }
96734      }
96735    }
96736    whereClauseClear(pWInfo->pWC);
96737    sqlite3DbFree(db, pWInfo);
96738  }
96739}
96740
96741
96742/*
96743** Generate the beginning of the loop used for WHERE clause processing.
96744** The return value is a pointer to an opaque structure that contains
96745** information needed to terminate the loop.  Later, the calling routine
96746** should invoke sqlite3WhereEnd() with the return value of this function
96747** in order to complete the WHERE clause processing.
96748**
96749** If an error occurs, this routine returns NULL.
96750**
96751** The basic idea is to do a nested loop, one loop for each table in
96752** the FROM clause of a select.  (INSERT and UPDATE statements are the
96753** same as a SELECT with only a single table in the FROM clause.)  For
96754** example, if the SQL is this:
96755**
96756**       SELECT * FROM t1, t2, t3 WHERE ...;
96757**
96758** Then the code generated is conceptually like the following:
96759**
96760**      foreach row1 in t1 do       \    Code generated
96761**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
96762**          foreach row3 in t3 do   /
96763**            ...
96764**          end                     \    Code generated
96765**        end                        |-- by sqlite3WhereEnd()
96766**      end                         /
96767**
96768** Note that the loops might not be nested in the order in which they
96769** appear in the FROM clause if a different order is better able to make
96770** use of indices.  Note also that when the IN operator appears in
96771** the WHERE clause, it might result in additional nested loops for
96772** scanning through all values on the right-hand side of the IN.
96773**
96774** There are Btree cursors associated with each table.  t1 uses cursor
96775** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
96776** And so forth.  This routine generates code to open those VDBE cursors
96777** and sqlite3WhereEnd() generates the code to close them.
96778**
96779** The code that sqlite3WhereBegin() generates leaves the cursors named
96780** in pTabList pointing at their appropriate entries.  The [...] code
96781** can use OP_Column and OP_Rowid opcodes on these cursors to extract
96782** data from the various tables of the loop.
96783**
96784** If the WHERE clause is empty, the foreach loops must each scan their
96785** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
96786** the tables have indices and there are terms in the WHERE clause that
96787** refer to those indices, a complete table scan can be avoided and the
96788** code will run much faster.  Most of the work of this routine is checking
96789** to see if there are indices that can be used to speed up the loop.
96790**
96791** Terms of the WHERE clause are also used to limit which rows actually
96792** make it to the "..." in the middle of the loop.  After each "foreach",
96793** terms of the WHERE clause that use only terms in that loop and outer
96794** loops are evaluated and if false a jump is made around all subsequent
96795** inner loops (or around the "..." if the test occurs within the inner-
96796** most loop)
96797**
96798** OUTER JOINS
96799**
96800** An outer join of tables t1 and t2 is conceptally coded as follows:
96801**
96802**    foreach row1 in t1 do
96803**      flag = 0
96804**      foreach row2 in t2 do
96805**        start:
96806**          ...
96807**          flag = 1
96808**      end
96809**      if flag==0 then
96810**        move the row2 cursor to a null row
96811**        goto start
96812**      fi
96813**    end
96814**
96815** ORDER BY CLAUSE PROCESSING
96816**
96817** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
96818** if there is one.  If there is no ORDER BY clause or if this routine
96819** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
96820**
96821** If an index can be used so that the natural output order of the table
96822** scan is correct for the ORDER BY clause, then that index is used and
96823** *ppOrderBy is set to NULL.  This is an optimization that prevents an
96824** unnecessary sort of the result set if an index appropriate for the
96825** ORDER BY clause already exists.
96826**
96827** If the where clause loops cannot be arranged to provide the correct
96828** output order, then the *ppOrderBy is unchanged.
96829*/
96830SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
96831  Parse *pParse,        /* The parser context */
96832  SrcList *pTabList,    /* A list of all tables to be scanned */
96833  Expr *pWhere,         /* The WHERE clause */
96834  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
96835  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
96836){
96837  int i;                     /* Loop counter */
96838  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
96839  int nTabList;              /* Number of elements in pTabList */
96840  WhereInfo *pWInfo;         /* Will become the return value of this function */
96841  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
96842  Bitmask notReady;          /* Cursors that are not yet positioned */
96843  WhereMaskSet *pMaskSet;    /* The expression mask set */
96844  WhereClause *pWC;               /* Decomposition of the WHERE clause */
96845  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
96846  WhereLevel *pLevel;             /* A single level in the pWInfo list */
96847  int iFrom;                      /* First unused FROM clause element */
96848  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
96849  sqlite3 *db;               /* Database connection */
96850
96851  /* The number of tables in the FROM clause is limited by the number of
96852  ** bits in a Bitmask
96853  */
96854  testcase( pTabList->nSrc==BMS );
96855  if( pTabList->nSrc>BMS ){
96856    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
96857    return 0;
96858  }
96859
96860  /* This function normally generates a nested loop for all tables in
96861  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
96862  ** only generate code for the first table in pTabList and assume that
96863  ** any cursors associated with subsequent tables are uninitialized.
96864  */
96865  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
96866
96867  /* Allocate and initialize the WhereInfo structure that will become the
96868  ** return value. A single allocation is used to store the WhereInfo
96869  ** struct, the contents of WhereInfo.a[], the WhereClause structure
96870  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
96871  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
96872  ** some architectures. Hence the ROUND8() below.
96873  */
96874  db = pParse->db;
96875  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
96876  pWInfo = sqlite3DbMallocZero(db,
96877      nByteWInfo +
96878      sizeof(WhereClause) +
96879      sizeof(WhereMaskSet)
96880  );
96881  if( db->mallocFailed ){
96882    sqlite3DbFree(db, pWInfo);
96883    pWInfo = 0;
96884    goto whereBeginError;
96885  }
96886  pWInfo->nLevel = nTabList;
96887  pWInfo->pParse = pParse;
96888  pWInfo->pTabList = pTabList;
96889  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
96890  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
96891  pWInfo->wctrlFlags = wctrlFlags;
96892  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
96893  pMaskSet = (WhereMaskSet*)&pWC[1];
96894
96895  /* Split the WHERE clause into separate subexpressions where each
96896  ** subexpression is separated by an AND operator.
96897  */
96898  initMaskSet(pMaskSet);
96899  whereClauseInit(pWC, pParse, pMaskSet);
96900  sqlite3ExprCodeConstants(pParse, pWhere);
96901  whereSplit(pWC, pWhere, TK_AND);
96902
96903  /* Special case: a WHERE clause that is constant.  Evaluate the
96904  ** expression and either jump over all of the code or fall thru.
96905  */
96906  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
96907    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
96908    pWhere = 0;
96909  }
96910
96911  /* Assign a bit from the bitmask to every term in the FROM clause.
96912  **
96913  ** When assigning bitmask values to FROM clause cursors, it must be
96914  ** the case that if X is the bitmask for the N-th FROM clause term then
96915  ** the bitmask for all FROM clause terms to the left of the N-th term
96916  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
96917  ** its Expr.iRightJoinTable value to find the bitmask of the right table
96918  ** of the join.  Subtracting one from the right table bitmask gives a
96919  ** bitmask for all tables to the left of the join.  Knowing the bitmask
96920  ** for all tables to the left of a left join is important.  Ticket #3015.
96921  **
96922  ** Configure the WhereClause.vmask variable so that bits that correspond
96923  ** to virtual table cursors are set. This is used to selectively disable
96924  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
96925  ** with virtual tables.
96926  **
96927  ** Note that bitmasks are created for all pTabList->nSrc tables in
96928  ** pTabList, not just the first nTabList tables.  nTabList is normally
96929  ** equal to pTabList->nSrc but might be shortened to 1 if the
96930  ** WHERE_ONETABLE_ONLY flag is set.
96931  */
96932  assert( pWC->vmask==0 && pMaskSet->n==0 );
96933  for(i=0; i<pTabList->nSrc; i++){
96934    createMask(pMaskSet, pTabList->a[i].iCursor);
96935#ifndef SQLITE_OMIT_VIRTUALTABLE
96936    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
96937      pWC->vmask |= ((Bitmask)1 << i);
96938    }
96939#endif
96940  }
96941#ifndef NDEBUG
96942  {
96943    Bitmask toTheLeft = 0;
96944    for(i=0; i<pTabList->nSrc; i++){
96945      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
96946      assert( (m-1)==toTheLeft );
96947      toTheLeft |= m;
96948    }
96949  }
96950#endif
96951
96952  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
96953  ** add new virtual terms onto the end of the WHERE clause.  We do not
96954  ** want to analyze these virtual terms, so start analyzing at the end
96955  ** and work forward so that the added virtual terms are never processed.
96956  */
96957  exprAnalyzeAll(pTabList, pWC);
96958  if( db->mallocFailed ){
96959    goto whereBeginError;
96960  }
96961
96962  /* Chose the best index to use for each table in the FROM clause.
96963  **
96964  ** This loop fills in the following fields:
96965  **
96966  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
96967  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
96968  **   pWInfo->a[].nEq       The number of == and IN constraints
96969  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
96970  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
96971  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
96972  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
96973  **
96974  ** This loop also figures out the nesting order of tables in the FROM
96975  ** clause.
96976  */
96977  notReady = ~(Bitmask)0;
96978  pTabItem = pTabList->a;
96979  pLevel = pWInfo->a;
96980  andFlags = ~0;
96981  WHERETRACE(("*** Optimizer Start ***\n"));
96982  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
96983    WhereCost bestPlan;         /* Most efficient plan seen so far */
96984    Index *pIdx;                /* Index for FROM table at pTabItem */
96985    int j;                      /* For looping over FROM tables */
96986    int bestJ = -1;             /* The value of j */
96987    Bitmask m;                  /* Bitmask value for j or bestJ */
96988    int isOptimal;              /* Iterator for optimal/non-optimal search */
96989
96990    memset(&bestPlan, 0, sizeof(bestPlan));
96991    bestPlan.rCost = SQLITE_BIG_DBL;
96992
96993    /* Loop through the remaining entries in the FROM clause to find the
96994    ** next nested loop. The loop tests all FROM clause entries
96995    ** either once or twice.
96996    **
96997    ** The first test is always performed if there are two or more entries
96998    ** remaining and never performed if there is only one FROM clause entry
96999    ** to choose from.  The first test looks for an "optimal" scan.  In
97000    ** this context an optimal scan is one that uses the same strategy
97001    ** for the given FROM clause entry as would be selected if the entry
97002    ** were used as the innermost nested loop.  In other words, a table
97003    ** is chosen such that the cost of running that table cannot be reduced
97004    ** by waiting for other tables to run first.  This "optimal" test works
97005    ** by first assuming that the FROM clause is on the inner loop and finding
97006    ** its query plan, then checking to see if that query plan uses any
97007    ** other FROM clause terms that are notReady.  If no notReady terms are
97008    ** used then the "optimal" query plan works.
97009    **
97010    ** The second loop iteration is only performed if no optimal scan
97011    ** strategies were found by the first loop. This 2nd iteration is used to
97012    ** search for the lowest cost scan overall.
97013    **
97014    ** Previous versions of SQLite performed only the second iteration -
97015    ** the next outermost loop was always that with the lowest overall
97016    ** cost. However, this meant that SQLite could select the wrong plan
97017    ** for scripts such as the following:
97018    **
97019    **   CREATE TABLE t1(a, b);
97020    **   CREATE TABLE t2(c, d);
97021    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
97022    **
97023    ** The best strategy is to iterate through table t1 first. However it
97024    ** is not possible to determine this with a simple greedy algorithm.
97025    ** However, since the cost of a linear scan through table t2 is the same
97026    ** as the cost of a linear scan through table t1, a simple greedy
97027    ** algorithm may choose to use t2 for the outer loop, which is a much
97028    ** costlier approach.
97029    */
97030    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
97031      Bitmask mask;  /* Mask of tables not yet ready */
97032      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
97033        int doNotReorder;    /* True if this table should not be reordered */
97034        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
97035        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
97036
97037        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
97038        if( j!=iFrom && doNotReorder ) break;
97039        m = getMask(pMaskSet, pTabItem->iCursor);
97040        if( (m & notReady)==0 ){
97041          if( j==iFrom ) iFrom++;
97042          continue;
97043        }
97044        mask = (isOptimal ? m : notReady);
97045        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
97046
97047        assert( pTabItem->pTab );
97048#ifndef SQLITE_OMIT_VIRTUALTABLE
97049        if( IsVirtual(pTabItem->pTab) ){
97050          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
97051          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
97052        }else
97053#endif
97054        {
97055          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
97056        }
97057        assert( isOptimal || (sCost.used&notReady)==0 );
97058
97059        if( (sCost.used&notReady)==0
97060         && (bestJ<0 || sCost.rCost<bestPlan.rCost
97061             || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
97062        ){
97063          WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
97064                      sCost.rCost, sCost.nRow));
97065          bestPlan = sCost;
97066          bestJ = j;
97067        }
97068        if( doNotReorder ) break;
97069      }
97070    }
97071    assert( bestJ>=0 );
97072    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
97073    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
97074           pLevel-pWInfo->a));
97075    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
97076      *ppOrderBy = 0;
97077    }
97078    andFlags &= bestPlan.plan.wsFlags;
97079    pLevel->plan = bestPlan.plan;
97080    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
97081    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
97082    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
97083      pLevel->iIdxCur = pParse->nTab++;
97084    }else{
97085      pLevel->iIdxCur = -1;
97086    }
97087    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
97088    pLevel->iFrom = (u8)bestJ;
97089    if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
97090
97091    /* Check that if the table scanned by this loop iteration had an
97092    ** INDEXED BY clause attached to it, that the named index is being
97093    ** used for the scan. If not, then query compilation has failed.
97094    ** Return an error.
97095    */
97096    pIdx = pTabList->a[bestJ].pIndex;
97097    if( pIdx ){
97098      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
97099        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
97100        goto whereBeginError;
97101      }else{
97102        /* If an INDEXED BY clause is used, the bestIndex() function is
97103        ** guaranteed to find the index specified in the INDEXED BY clause
97104        ** if it find an index at all. */
97105        assert( bestPlan.plan.u.pIdx==pIdx );
97106      }
97107    }
97108  }
97109  WHERETRACE(("*** Optimizer Finished ***\n"));
97110  if( pParse->nErr || db->mallocFailed ){
97111    goto whereBeginError;
97112  }
97113
97114  /* If the total query only selects a single row, then the ORDER BY
97115  ** clause is irrelevant.
97116  */
97117  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
97118    *ppOrderBy = 0;
97119  }
97120
97121  /* If the caller is an UPDATE or DELETE statement that is requesting
97122  ** to use a one-pass algorithm, determine if this is appropriate.
97123  ** The one-pass algorithm only works if the WHERE clause constraints
97124  ** the statement to update a single row.
97125  */
97126  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
97127  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
97128    pWInfo->okOnePass = 1;
97129    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
97130  }
97131
97132  /* Open all tables in the pTabList and any indices selected for
97133  ** searching those tables.
97134  */
97135  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
97136  notReady = ~(Bitmask)0;
97137  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
97138    Table *pTab;     /* Table to open */
97139    int iDb;         /* Index of database containing table/index */
97140
97141#ifndef SQLITE_OMIT_EXPLAIN
97142    if( pParse->explain==2 ){
97143      char *zMsg;
97144      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
97145      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
97146      if( pItem->zAlias ){
97147        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
97148      }
97149      if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97150        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
97151      }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97152        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
97153           zMsg, pLevel->plan.u.pIdx->zName);
97154      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
97155        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
97156      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97157        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
97158      }
97159#ifndef SQLITE_OMIT_VIRTUALTABLE
97160      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97161        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
97162        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
97163                    pVtabIdx->idxNum, pVtabIdx->idxStr);
97164      }
97165#endif
97166      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
97167        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
97168      }
97169      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
97170    }
97171#endif /* SQLITE_OMIT_EXPLAIN */
97172    pTabItem = &pTabList->a[pLevel->iFrom];
97173    pTab = pTabItem->pTab;
97174    pLevel->iTabCur = pTabItem->iCursor;
97175    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97176    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
97177      /* Do nothing */
97178    }else
97179#ifndef SQLITE_OMIT_VIRTUALTABLE
97180    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97181      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
97182      int iCur = pTabItem->iCursor;
97183      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
97184    }else
97185#endif
97186    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97187         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
97188      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
97189      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
97190      testcase( pTab->nCol==BMS-1 );
97191      testcase( pTab->nCol==BMS );
97192      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
97193        Bitmask b = pTabItem->colUsed;
97194        int n = 0;
97195        for(; b; b=b>>1, n++){}
97196        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
97197                            SQLITE_INT_TO_PTR(n), P4_INT32);
97198        assert( n<=pTab->nCol );
97199      }
97200    }else{
97201      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97202    }
97203#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97204    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97205      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
97206    }else
97207#endif
97208    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97209      Index *pIx = pLevel->plan.u.pIdx;
97210      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
97211      int iIdxCur = pLevel->iIdxCur;
97212      assert( pIx->pSchema==pTab->pSchema );
97213      assert( iIdxCur>=0 );
97214      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
97215                        (char*)pKey, P4_KEYINFO_HANDOFF);
97216      VdbeComment((v, "%s", pIx->zName));
97217    }
97218    sqlite3CodeVerifySchema(pParse, iDb);
97219    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
97220  }
97221  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
97222  if( db->mallocFailed ) goto whereBeginError;
97223
97224  /* Generate the code to do the search.  Each iteration of the for
97225  ** loop below generates code for a single nested loop of the VM
97226  ** program.
97227  */
97228  notReady = ~(Bitmask)0;
97229  for(i=0; i<nTabList; i++){
97230    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
97231    pWInfo->iContinue = pWInfo->a[i].addrCont;
97232  }
97233
97234#ifdef SQLITE_TEST  /* For testing and debugging use only */
97235  /* Record in the query plan information about the current table
97236  ** and the index used to access it (if any).  If the table itself
97237  ** is not used, its name is just '{}'.  If no index is used
97238  ** the index is listed as "{}".  If the primary key is used the
97239  ** index name is '*'.
97240  */
97241  for(i=0; i<nTabList; i++){
97242    char *z;
97243    int n;
97244    pLevel = &pWInfo->a[i];
97245    pTabItem = &pTabList->a[pLevel->iFrom];
97246    z = pTabItem->zAlias;
97247    if( z==0 ) z = pTabItem->pTab->zName;
97248    n = sqlite3Strlen30(z);
97249    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
97250      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
97251        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
97252        nQPlan += 2;
97253      }else{
97254        memcpy(&sqlite3_query_plan[nQPlan], z, n);
97255        nQPlan += n;
97256      }
97257      sqlite3_query_plan[nQPlan++] = ' ';
97258    }
97259    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
97260    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
97261    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97262      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
97263      nQPlan += 2;
97264    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97265      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
97266      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
97267        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
97268        nQPlan += n;
97269        sqlite3_query_plan[nQPlan++] = ' ';
97270      }
97271    }else{
97272      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
97273      nQPlan += 3;
97274    }
97275  }
97276  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
97277    sqlite3_query_plan[--nQPlan] = 0;
97278  }
97279  sqlite3_query_plan[nQPlan] = 0;
97280  nQPlan = 0;
97281#endif /* SQLITE_TEST // Testing and debugging use only */
97282
97283  /* Record the continuation address in the WhereInfo structure.  Then
97284  ** clean up and return.
97285  */
97286  return pWInfo;
97287
97288  /* Jump here if malloc fails */
97289whereBeginError:
97290  if( pWInfo ){
97291    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97292    whereInfoFree(db, pWInfo);
97293  }
97294  return 0;
97295}
97296
97297/*
97298** Generate the end of the WHERE loop.  See comments on
97299** sqlite3WhereBegin() for additional information.
97300*/
97301SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
97302  Parse *pParse = pWInfo->pParse;
97303  Vdbe *v = pParse->pVdbe;
97304  int i;
97305  WhereLevel *pLevel;
97306  SrcList *pTabList = pWInfo->pTabList;
97307  sqlite3 *db = pParse->db;
97308
97309  /* Generate loop termination code.
97310  */
97311  sqlite3ExprCacheClear(pParse);
97312  for(i=pWInfo->nLevel-1; i>=0; i--){
97313    pLevel = &pWInfo->a[i];
97314    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
97315    if( pLevel->op!=OP_Noop ){
97316      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
97317      sqlite3VdbeChangeP5(v, pLevel->p5);
97318    }
97319    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
97320      struct InLoop *pIn;
97321      int j;
97322      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
97323      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
97324        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
97325        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
97326        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
97327      }
97328      sqlite3DbFree(db, pLevel->u.in.aInLoop);
97329    }
97330    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
97331    if( pLevel->iLeftJoin ){
97332      int addr;
97333      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
97334      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97335           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
97336      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
97337        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
97338      }
97339      if( pLevel->iIdxCur>=0 ){
97340        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
97341      }
97342      if( pLevel->op==OP_Return ){
97343        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
97344      }else{
97345        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
97346      }
97347      sqlite3VdbeJumpHere(v, addr);
97348    }
97349  }
97350
97351  /* The "break" point is here, just past the end of the outer loop.
97352  ** Set it.
97353  */
97354  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
97355
97356  /* Close all of the cursors that were opened by sqlite3WhereBegin.
97357  */
97358  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
97359  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
97360    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
97361    Table *pTab = pTabItem->pTab;
97362    assert( pTab!=0 );
97363    if( (pTab->tabFlags & TF_Ephemeral)==0
97364     && pTab->pSelect==0
97365     && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
97366    ){
97367      int ws = pLevel->plan.wsFlags;
97368      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
97369        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
97370      }
97371      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
97372        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
97373      }
97374    }
97375
97376    /* If this scan uses an index, make code substitutions to read data
97377    ** from the index in preference to the table. Sometimes, this means
97378    ** the table need never be read from. This is a performance boost,
97379    ** as the vdbe level waits until the table is read before actually
97380    ** seeking the table cursor to the record corresponding to the current
97381    ** position in the index.
97382    **
97383    ** Calls to the code generator in between sqlite3WhereBegin and
97384    ** sqlite3WhereEnd will have created code that references the table
97385    ** directly.  This loop scans all that code looking for opcodes
97386    ** that reference the table and converts them into opcodes that
97387    ** reference the index.
97388    */
97389    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
97390      int k, j, last;
97391      VdbeOp *pOp;
97392      Index *pIdx = pLevel->plan.u.pIdx;
97393
97394      assert( pIdx!=0 );
97395      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
97396      last = sqlite3VdbeCurrentAddr(v);
97397      for(k=pWInfo->iTop; k<last; k++, pOp++){
97398        if( pOp->p1!=pLevel->iTabCur ) continue;
97399        if( pOp->opcode==OP_Column ){
97400          for(j=0; j<pIdx->nColumn; j++){
97401            if( pOp->p2==pIdx->aiColumn[j] ){
97402              pOp->p2 = j;
97403              pOp->p1 = pLevel->iIdxCur;
97404              break;
97405            }
97406          }
97407          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97408               || j<pIdx->nColumn );
97409        }else if( pOp->opcode==OP_Rowid ){
97410          pOp->p1 = pLevel->iIdxCur;
97411          pOp->opcode = OP_IdxRowid;
97412        }
97413      }
97414    }
97415  }
97416
97417  /* Final cleanup
97418  */
97419  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97420  whereInfoFree(db, pWInfo);
97421  return;
97422}
97423
97424/************** End of where.c ***********************************************/
97425/************** Begin file parse.c *******************************************/
97426/* Driver template for the LEMON parser generator.
97427** The author disclaims copyright to this source code.
97428**
97429** This version of "lempar.c" is modified, slightly, for use by SQLite.
97430** The only modifications are the addition of a couple of NEVER()
97431** macros to disable tests that are needed in the case of a general
97432** LALR(1) grammar but which are always false in the
97433** specific grammar used by SQLite.
97434*/
97435/* First off, code is included that follows the "include" declaration
97436** in the input grammar file. */
97437
97438
97439/*
97440** Disable all error recovery processing in the parser push-down
97441** automaton.
97442*/
97443#define YYNOERRORRECOVERY 1
97444
97445/*
97446** Make yytestcase() the same as testcase()
97447*/
97448#define yytestcase(X) testcase(X)
97449
97450/*
97451** An instance of this structure holds information about the
97452** LIMIT clause of a SELECT statement.
97453*/
97454struct LimitVal {
97455  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
97456  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
97457};
97458
97459/*
97460** An instance of this structure is used to store the LIKE,
97461** GLOB, NOT LIKE, and NOT GLOB operators.
97462*/
97463struct LikeOp {
97464  Token eOperator;  /* "like" or "glob" or "regexp" */
97465  int not;         /* True if the NOT keyword is present */
97466};
97467
97468/*
97469** An instance of the following structure describes the event of a
97470** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
97471** TK_DELETE, or TK_INSTEAD.  If the event is of the form
97472**
97473**      UPDATE ON (a,b,c)
97474**
97475** Then the "b" IdList records the list "a,b,c".
97476*/
97477struct TrigEvent { int a; IdList * b; };
97478
97479/*
97480** An instance of this structure holds the ATTACH key and the key type.
97481*/
97482struct AttachKey { int type;  Token key; };
97483
97484
97485  /* This is a utility routine used to set the ExprSpan.zStart and
97486  ** ExprSpan.zEnd values of pOut so that the span covers the complete
97487  ** range of text beginning with pStart and going to the end of pEnd.
97488  */
97489  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
97490    pOut->zStart = pStart->z;
97491    pOut->zEnd = &pEnd->z[pEnd->n];
97492  }
97493
97494  /* Construct a new Expr object from a single identifier.  Use the
97495  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
97496  ** that created the expression.
97497  */
97498  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
97499    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
97500    pOut->zStart = pValue->z;
97501    pOut->zEnd = &pValue->z[pValue->n];
97502  }
97503
97504  /* This routine constructs a binary expression node out of two ExprSpan
97505  ** objects and uses the result to populate a new ExprSpan object.
97506  */
97507  static void spanBinaryExpr(
97508    ExprSpan *pOut,     /* Write the result here */
97509    Parse *pParse,      /* The parsing context.  Errors accumulate here */
97510    int op,             /* The binary operation */
97511    ExprSpan *pLeft,    /* The left operand */
97512    ExprSpan *pRight    /* The right operand */
97513  ){
97514    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
97515    pOut->zStart = pLeft->zStart;
97516    pOut->zEnd = pRight->zEnd;
97517  }
97518
97519  /* Construct an expression node for a unary postfix operator
97520  */
97521  static void spanUnaryPostfix(
97522    ExprSpan *pOut,        /* Write the new expression node here */
97523    Parse *pParse,         /* Parsing context to record errors */
97524    int op,                /* The operator */
97525    ExprSpan *pOperand,    /* The operand */
97526    Token *pPostOp         /* The operand token for setting the span */
97527  ){
97528    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97529    pOut->zStart = pOperand->zStart;
97530    pOut->zEnd = &pPostOp->z[pPostOp->n];
97531  }
97532
97533  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
97534  ** unary TK_ISNULL or TK_NOTNULL expression. */
97535  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
97536    sqlite3 *db = pParse->db;
97537    if( db->mallocFailed==0 && pY->op==TK_NULL ){
97538      pA->op = (u8)op;
97539      sqlite3ExprDelete(db, pA->pRight);
97540      pA->pRight = 0;
97541    }
97542  }
97543
97544  /* Construct an expression node for a unary prefix operator
97545  */
97546  static void spanUnaryPrefix(
97547    ExprSpan *pOut,        /* Write the new expression node here */
97548    Parse *pParse,         /* Parsing context to record errors */
97549    int op,                /* The operator */
97550    ExprSpan *pOperand,    /* The operand */
97551    Token *pPreOp         /* The operand token for setting the span */
97552  ){
97553    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97554    pOut->zStart = pPreOp->z;
97555    pOut->zEnd = pOperand->zEnd;
97556  }
97557/* Next is all token values, in a form suitable for use by makeheaders.
97558** This section will be null unless lemon is run with the -m switch.
97559*/
97560/*
97561** These constants (all generated automatically by the parser generator)
97562** specify the various kinds of tokens (terminals) that the parser
97563** understands.
97564**
97565** Each symbol here is a terminal symbol in the grammar.
97566*/
97567/* Make sure the INTERFACE macro is defined.
97568*/
97569#ifndef INTERFACE
97570# define INTERFACE 1
97571#endif
97572/* The next thing included is series of defines which control
97573** various aspects of the generated parser.
97574**    YYCODETYPE         is the data type used for storing terminal
97575**                       and nonterminal numbers.  "unsigned char" is
97576**                       used if there are fewer than 250 terminals
97577**                       and nonterminals.  "int" is used otherwise.
97578**    YYNOCODE           is a number of type YYCODETYPE which corresponds
97579**                       to no legal terminal or nonterminal number.  This
97580**                       number is used to fill in empty slots of the hash
97581**                       table.
97582**    YYFALLBACK         If defined, this indicates that one or more tokens
97583**                       have fall-back values which should be used if the
97584**                       original value of the token will not parse.
97585**    YYACTIONTYPE       is the data type used for storing terminal
97586**                       and nonterminal numbers.  "unsigned char" is
97587**                       used if there are fewer than 250 rules and
97588**                       states combined.  "int" is used otherwise.
97589**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
97590**                       directly to the parser from the tokenizer.
97591**    YYMINORTYPE        is the data type used for all minor tokens.
97592**                       This is typically a union of many types, one of
97593**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
97594**                       for base tokens is called "yy0".
97595**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
97596**                       zero the stack is dynamically sized using realloc()
97597**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
97598**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
97599**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
97600**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
97601**    YYNSTATE           the combined number of states.
97602**    YYNRULE            the number of rules in the grammar
97603**    YYERRORSYMBOL      is the code number of the error symbol.  If not
97604**                       defined, then do no error processing.
97605*/
97606#define YYCODETYPE unsigned char
97607#define YYNOCODE 254
97608#define YYACTIONTYPE unsigned short int
97609#define YYWILDCARD 67
97610#define sqlite3ParserTOKENTYPE Token
97611typedef union {
97612  int yyinit;
97613  sqlite3ParserTOKENTYPE yy0;
97614  Select* yy3;
97615  ExprList* yy14;
97616  SrcList* yy65;
97617  struct LikeOp yy96;
97618  Expr* yy132;
97619  u8 yy186;
97620  int yy328;
97621  ExprSpan yy346;
97622  struct TrigEvent yy378;
97623  IdList* yy408;
97624  struct {int value; int mask;} yy429;
97625  TriggerStep* yy473;
97626  struct LimitVal yy476;
97627} YYMINORTYPE;
97628#ifndef YYSTACKDEPTH
97629#define YYSTACKDEPTH 100
97630#endif
97631#define sqlite3ParserARG_SDECL Parse *pParse;
97632#define sqlite3ParserARG_PDECL ,Parse *pParse
97633#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
97634#define sqlite3ParserARG_STORE yypParser->pParse = pParse
97635#define YYNSTATE 631
97636#define YYNRULE 330
97637#define YYFALLBACK 1
97638#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
97639#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
97640#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
97641
97642/* The yyzerominor constant is used to initialize instances of
97643** YYMINORTYPE objects to zero. */
97644static const YYMINORTYPE yyzerominor = { 0 };
97645
97646/* Define the yytestcase() macro to be a no-op if is not already defined
97647** otherwise.
97648**
97649** Applications can choose to define yytestcase() in the %include section
97650** to a macro that can assist in verifying code coverage.  For production
97651** code the yytestcase() macro should be turned off.  But it is useful
97652** for testing.
97653*/
97654#ifndef yytestcase
97655# define yytestcase(X)
97656#endif
97657
97658
97659/* Next are the tables used to determine what action to take based on the
97660** current state and lookahead token.  These tables are used to implement
97661** functions that take a state number and lookahead value and return an
97662** action integer.
97663**
97664** Suppose the action integer is N.  Then the action is determined as
97665** follows
97666**
97667**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
97668**                                      token onto the stack and goto state N.
97669**
97670**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
97671**
97672**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
97673**
97674**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
97675**
97676**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
97677**                                      slots in the yy_action[] table.
97678**
97679** The action table is constructed as a single large table named yy_action[].
97680** Given state S and lookahead X, the action is computed as
97681**
97682**      yy_action[ yy_shift_ofst[S] + X ]
97683**
97684** If the index value yy_shift_ofst[S]+X is out of range or if the value
97685** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
97686** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
97687** and that yy_default[S] should be used instead.
97688**
97689** The formula above is for computing the action when the lookahead is
97690** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
97691** a reduce action) then the yy_reduce_ofst[] array is used in place of
97692** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
97693** YY_SHIFT_USE_DFLT.
97694**
97695** The following are the tables generated in this section:
97696**
97697**  yy_action[]        A single table containing all actions.
97698**  yy_lookahead[]     A table containing the lookahead for each entry in
97699**                     yy_action.  Used to detect hash collisions.
97700**  yy_shift_ofst[]    For each state, the offset into yy_action for
97701**                     shifting terminals.
97702**  yy_reduce_ofst[]   For each state, the offset into yy_action for
97703**                     shifting non-terminals after a reduce.
97704**  yy_default[]       Default action for each state.
97705*/
97706#define YY_ACTTAB_COUNT (1550)
97707static const YYACTIONTYPE yy_action[] = {
97708 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
97709 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
97710 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
97711 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
97712 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
97713 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
97714 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
97715 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
97716 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
97717 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
97718 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
97719 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
97720 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
97721 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
97722 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
97723 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
97724 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
97725 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
97726 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
97727 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
97728 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
97729 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
97730 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
97731 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
97732 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
97733 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
97734 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
97735 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
97736 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
97737 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
97738 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
97739 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
97740 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
97741 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
97742 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
97743 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
97744 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
97745 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
97746 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
97747 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
97748 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
97749 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
97750 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
97751 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
97752 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
97753 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
97754 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
97755 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
97756 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
97757 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
97758 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
97759 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
97760 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
97761 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
97762 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
97763 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
97764 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
97765 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
97766 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
97767 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
97768 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
97769 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
97770 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
97771 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
97772 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
97773 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
97774 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
97775 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
97776 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
97777 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
97778 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
97779 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
97780 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
97781 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
97782 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
97783 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
97784 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
97785 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
97786 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
97787 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
97788 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
97789 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
97790 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
97791 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
97792 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
97793 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
97794 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
97795 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
97796 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
97797 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
97798 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
97799 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
97800 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
97801 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
97802 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
97803 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
97804 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
97805 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
97806 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
97807 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
97808 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
97809 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
97810 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
97811 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
97812 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
97813 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
97814 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
97815 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
97816 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
97817 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
97818 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
97819 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
97820 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
97821 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
97822 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
97823 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
97824 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
97825 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
97826 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
97827 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
97828 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
97829 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
97830 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
97831 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
97832 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
97833 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
97834 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
97835 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
97836 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
97837 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
97838 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
97839 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
97840 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
97841 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
97842 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
97843 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
97844 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
97845 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
97846 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
97847 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
97848 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
97849 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
97850 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
97851 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
97852 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
97853 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
97854 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
97855 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
97856 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  347,  117,  116,
97857 /*  1490 */   115,  112,  114,  448,  182,   22,  320,  433,  432,  431,
97858 /*  1500 */    19,  428,  610,  597,  574,  193,  572,   63,  298,  404,
97859 /*  1510 */   555,  552,  290,  281,  510,  460,  498,  499,  495,  447,
97860 /*  1520 */   356,  497,  256,  380,  306,  570,    5,  250,  345,  238,
97861 /*  1530 */   299,  550,  527,  490,  508,  525,  502,  401,  501,  963,
97862 /*  1540 */   211,  963,  483,  963,  963,  963,  963,  963,  963,  370,
97863};
97864static const YYCODETYPE yy_lookahead[] = {
97865 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
97866 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
97867 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
97868 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
97869 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
97870 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
97871 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
97872 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
97873 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
97874 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
97875 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
97876 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
97877 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
97878 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
97879 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
97880 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
97881 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
97882 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
97883 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
97884 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
97885 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
97886 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
97887 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
97888 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
97889 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
97890 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
97891 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
97892 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
97893 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
97894 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
97895 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
97896 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
97897 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
97898 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
97899 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
97900 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
97901 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
97902 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
97903 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
97904 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
97905 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
97906 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
97907 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
97908 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
97909 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
97910 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
97911 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
97912 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
97913 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
97914 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
97915 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
97916 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
97917 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
97918 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
97919 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
97920 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
97921 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
97922 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
97923 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
97924 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
97925 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
97926 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
97927 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
97928 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
97929 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
97930 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
97931 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
97932 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
97933 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
97934 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
97935 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
97936 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
97937 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
97938 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
97939 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
97940 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
97941 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
97942 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
97943 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
97944 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
97945 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
97946 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
97947 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
97948 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
97949 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
97950 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
97951 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
97952 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
97953 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
97954 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
97955 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
97956 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
97957 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
97958 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
97959 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
97960 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
97961 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
97962 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
97963 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
97964 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
97965 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
97966 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
97967 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
97968 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
97969 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
97970 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
97971 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
97972 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
97973 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
97974 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
97975 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
97976 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
97977 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
97978 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
97979 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
97980 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
97981 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
97982 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
97983 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
97984 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
97985 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
97986 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
97987 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
97988 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
97989 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
97990 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
97991 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
97992 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
97993 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
97994 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
97995 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
97996 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
97997 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
97998 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
97999 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
98000 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
98001 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
98002 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
98003 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
98004 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
98005 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
98006 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
98007 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
98008 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
98009 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
98010 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
98011 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
98012 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
98013 /*  1480 */    68,  189,  139,  219,   22,  199,  157,   18,  192,  192,
98014 /*  1490 */   192,  189,  192,  199,  219,  243,  157,   40,  157,  157,
98015 /*  1500 */   243,   38,  153,  166,  233,  196,  233,  246,  198,  228,
98016 /*  1510 */   177,  177,  209,  177,  182,  199,  166,  177,  166,  199,
98017 /*  1520 */   242,  177,  242,  178,  148,  166,  196,  209,  209,   92,
98018 /*  1530 */   195,  208,  174,  186,  183,  174,  183,  191,  183,  253,
98019 /*  1540 */   236,  253,  186,  253,  253,  253,  253,  253,  253,  237,
98020};
98021#define YY_SHIFT_USE_DFLT (-90)
98022#define YY_SHIFT_COUNT (418)
98023#define YY_SHIFT_MIN   (-89)
98024#define YY_SHIFT_MAX   (1469)
98025static const short yy_shift_ofst[] = {
98026 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
98027 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
98028 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98029 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98030 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
98031 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98032 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
98033 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
98034 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
98035 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
98036 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
98037 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
98038 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
98039 /*   130 */   517,  517,  517,  382,  885, 1437,  -90,  -90,  -90, 1293,
98040 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
98041 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
98042 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
98043 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
98044 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
98045 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
98046 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
98047 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
98048 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
98049 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
98050 /*   240 */   -89,  801, 1463, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
98051 /*   250 */  1188, 1469, 1469, 1469, 1469, 1244, 1188, 1462, 1412, 1412,
98052 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
98053 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
98054 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
98055 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
98056 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
98057 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
98058 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
98059 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
98060 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
98061 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
98062 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
98063 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
98064 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
98065 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
98066 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
98067 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
98068};
98069#define YY_REDUCE_USE_DFLT (-222)
98070#define YY_REDUCE_COUNT (312)
98071#define YY_REDUCE_MIN   (-221)
98072#define YY_REDUCE_MAX   (1376)
98073static const short yy_reduce_ofst[] = {
98074 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
98075 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
98076 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
98077 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
98078 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
98079 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
98080 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
98081 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
98082 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
98083 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
98084 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
98085 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
98086 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
98087 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
98088 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
98089 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
98090 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
98091 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
98092 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
98093 /*   190 */   460,  464,  572,  584, 1356, 1361, 1358, 1347, 1355, 1353,
98094 /*   200 */  1351, 1323, 1335, 1346, 1335, 1335, 1335, 1335, 1335, 1335,
98095 /*   210 */  1335, 1312, 1304, 1335, 1335, 1323, 1359, 1330, 1376, 1320,
98096 /*   220 */  1319, 1318, 1280, 1316, 1278, 1345, 1352, 1344, 1350, 1340,
98097 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1273, 1271, 1337, 1310,
98098 /*   240 */  1309, 1349, 1261, 1342, 1341, 1257, 1252, 1339, 1275, 1302,
98099 /*   250 */  1294, 1300, 1298, 1297, 1296, 1329, 1286, 1264, 1292, 1289,
98100 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
98101 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
98102 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
98103 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
98104 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
98105 /*   310 */  1061, 1038, 1053,
98106};
98107static const YYACTIONTYPE yy_default[] = {
98108 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
98109 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
98110 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98111 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98112 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98113 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98114 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
98115 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
98116 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
98117 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
98118 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
98119 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98120 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
98121 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
98122 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98123 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
98124 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98125 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98126 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
98127 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
98128 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
98129 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
98130 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
98131 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
98132 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
98133 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
98134 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
98135 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
98136 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
98137 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
98138 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
98139 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
98140 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98141 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
98142 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98143 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
98144 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
98145 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98146 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
98147 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
98148 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
98149 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
98150 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
98151 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
98152 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
98153 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
98154 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
98155 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
98156 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
98157 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
98158 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
98159 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
98160 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
98161 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
98162 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
98163 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
98164 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
98165 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
98166 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
98167 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
98168 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
98169 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
98170 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
98171 /*   630 */   632,
98172};
98173
98174/* The next table maps tokens into fallback tokens.  If a construct
98175** like the following:
98176**
98177**      %fallback ID X Y Z.
98178**
98179** appears in the grammar, then ID becomes a fallback token for X, Y,
98180** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
98181** but it does not parse, the type of the token is changed to ID and
98182** the parse is retried before an error is thrown.
98183*/
98184#ifdef YYFALLBACK
98185static const YYCODETYPE yyFallback[] = {
98186    0,  /*          $ => nothing */
98187    0,  /*       SEMI => nothing */
98188   26,  /*    EXPLAIN => ID */
98189   26,  /*      QUERY => ID */
98190   26,  /*       PLAN => ID */
98191   26,  /*      BEGIN => ID */
98192    0,  /* TRANSACTION => nothing */
98193   26,  /*   DEFERRED => ID */
98194   26,  /*  IMMEDIATE => ID */
98195   26,  /*  EXCLUSIVE => ID */
98196    0,  /*     COMMIT => nothing */
98197   26,  /*        END => ID */
98198   26,  /*   ROLLBACK => ID */
98199   26,  /*  SAVEPOINT => ID */
98200   26,  /*    RELEASE => ID */
98201    0,  /*         TO => nothing */
98202    0,  /*      TABLE => nothing */
98203    0,  /*     CREATE => nothing */
98204   26,  /*         IF => ID */
98205    0,  /*        NOT => nothing */
98206    0,  /*     EXISTS => nothing */
98207   26,  /*       TEMP => ID */
98208    0,  /*         LP => nothing */
98209    0,  /*         RP => nothing */
98210    0,  /*         AS => nothing */
98211    0,  /*      COMMA => nothing */
98212    0,  /*         ID => nothing */
98213    0,  /*    INDEXED => nothing */
98214   26,  /*      ABORT => ID */
98215   26,  /*     ACTION => ID */
98216   26,  /*      AFTER => ID */
98217   26,  /*    ANALYZE => ID */
98218   26,  /*        ASC => ID */
98219   26,  /*     ATTACH => ID */
98220   26,  /*     BEFORE => ID */
98221   26,  /*         BY => ID */
98222   26,  /*    CASCADE => ID */
98223   26,  /*       CAST => ID */
98224   26,  /*   COLUMNKW => ID */
98225   26,  /*   CONFLICT => ID */
98226   26,  /*   DATABASE => ID */
98227   26,  /*       DESC => ID */
98228   26,  /*     DETACH => ID */
98229   26,  /*       EACH => ID */
98230   26,  /*       FAIL => ID */
98231   26,  /*        FOR => ID */
98232   26,  /*     IGNORE => ID */
98233   26,  /*  INITIALLY => ID */
98234   26,  /*    INSTEAD => ID */
98235   26,  /*    LIKE_KW => ID */
98236   26,  /*      MATCH => ID */
98237   26,  /*         NO => ID */
98238   26,  /*        KEY => ID */
98239   26,  /*         OF => ID */
98240   26,  /*     OFFSET => ID */
98241   26,  /*     PRAGMA => ID */
98242   26,  /*      RAISE => ID */
98243   26,  /*    REPLACE => ID */
98244   26,  /*   RESTRICT => ID */
98245   26,  /*        ROW => ID */
98246   26,  /*    TRIGGER => ID */
98247   26,  /*     VACUUM => ID */
98248   26,  /*       VIEW => ID */
98249   26,  /*    VIRTUAL => ID */
98250   26,  /*    REINDEX => ID */
98251   26,  /*     RENAME => ID */
98252   26,  /*   CTIME_KW => ID */
98253};
98254#endif /* YYFALLBACK */
98255
98256/* The following structure represents a single element of the
98257** parser's stack.  Information stored includes:
98258**
98259**   +  The state number for the parser at this level of the stack.
98260**
98261**   +  The value of the token stored at this level of the stack.
98262**      (In other words, the "major" token.)
98263**
98264**   +  The semantic value stored at this level of the stack.  This is
98265**      the information used by the action routines in the grammar.
98266**      It is sometimes called the "minor" token.
98267*/
98268struct yyStackEntry {
98269  YYACTIONTYPE stateno;  /* The state-number */
98270  YYCODETYPE major;      /* The major token value.  This is the code
98271                         ** number for the token at this stack level */
98272  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
98273                         ** is the value of the token  */
98274};
98275typedef struct yyStackEntry yyStackEntry;
98276
98277/* The state of the parser is completely contained in an instance of
98278** the following structure */
98279struct yyParser {
98280  int yyidx;                    /* Index of top element in stack */
98281#ifdef YYTRACKMAXSTACKDEPTH
98282  int yyidxMax;                 /* Maximum value of yyidx */
98283#endif
98284  int yyerrcnt;                 /* Shifts left before out of the error */
98285  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
98286#if YYSTACKDEPTH<=0
98287  int yystksz;                  /* Current side of the stack */
98288  yyStackEntry *yystack;        /* The parser's stack */
98289#else
98290  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
98291#endif
98292};
98293typedef struct yyParser yyParser;
98294
98295#ifndef NDEBUG
98296static FILE *yyTraceFILE = 0;
98297static char *yyTracePrompt = 0;
98298#endif /* NDEBUG */
98299
98300#ifndef NDEBUG
98301/*
98302** Turn parser tracing on by giving a stream to which to write the trace
98303** and a prompt to preface each trace message.  Tracing is turned off
98304** by making either argument NULL
98305**
98306** Inputs:
98307** <ul>
98308** <li> A FILE* to which trace output should be written.
98309**      If NULL, then tracing is turned off.
98310** <li> A prefix string written at the beginning of every
98311**      line of trace output.  If NULL, then tracing is
98312**      turned off.
98313** </ul>
98314**
98315** Outputs:
98316** None.
98317*/
98318SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
98319  yyTraceFILE = TraceFILE;
98320  yyTracePrompt = zTracePrompt;
98321  if( yyTraceFILE==0 ) yyTracePrompt = 0;
98322  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
98323}
98324#endif /* NDEBUG */
98325
98326#ifndef NDEBUG
98327/* For tracing shifts, the names of all terminals and nonterminals
98328** are required.  The following table supplies these names */
98329static const char *const yyTokenName[] = {
98330  "$",             "SEMI",          "EXPLAIN",       "QUERY",
98331  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
98332  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
98333  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
98334  "TABLE",         "CREATE",        "IF",            "NOT",
98335  "EXISTS",        "TEMP",          "LP",            "RP",
98336  "AS",            "COMMA",         "ID",            "INDEXED",
98337  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
98338  "ASC",           "ATTACH",        "BEFORE",        "BY",
98339  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
98340  "DATABASE",      "DESC",          "DETACH",        "EACH",
98341  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
98342  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
98343  "KEY",           "OF",            "OFFSET",        "PRAGMA",
98344  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
98345  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
98346  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
98347  "OR",            "AND",           "IS",            "BETWEEN",
98348  "IN",            "ISNULL",        "NOTNULL",       "NE",
98349  "EQ",            "GT",            "LE",            "LT",
98350  "GE",            "ESCAPE",        "BITAND",        "BITOR",
98351  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
98352  "STAR",          "SLASH",         "REM",           "CONCAT",
98353  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
98354  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
98355  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
98356  "ON",            "INSERT",        "DELETE",        "UPDATE",
98357  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
98358  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
98359  "SELECT",        "DISTINCT",      "DOT",           "FROM",
98360  "JOIN",          "USING",         "ORDER",         "GROUP",
98361  "HAVING",        "LIMIT",         "WHERE",         "INTO",
98362  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
98363  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
98364  "THEN",          "ELSE",          "INDEX",         "ALTER",
98365  "ADD",           "error",         "input",         "cmdlist",
98366  "ecmd",          "explain",       "cmdx",          "cmd",
98367  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
98368  "create_table",  "create_table_args",  "createkw",      "temp",
98369  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
98370  "select",        "column",        "columnid",      "type",
98371  "carglist",      "id",            "ids",           "typetoken",
98372  "typename",      "signed",        "plus_num",      "minus_num",
98373  "carg",          "ccons",         "term",          "expr",
98374  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
98375  "refargs",       "defer_subclause",  "refarg",        "refact",
98376  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
98377  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
98378  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
98379  "distinct",      "selcollist",    "from",          "where_opt",
98380  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
98381  "sclp",          "as",            "seltablist",    "stl_prefix",
98382  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
98383  "joinop2",       "inscollist",    "sortlist",      "sortitem",
98384  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
98385  "itemlist",      "exprlist",      "likeop",        "escape",
98386  "between_op",    "in_op",         "case_operand",  "case_exprlist",
98387  "case_else",     "uniqueflag",    "collate",       "nmnum",
98388  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
98389  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
98390  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
98391  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
98392  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
98393  "anylist",
98394};
98395#endif /* NDEBUG */
98396
98397#ifndef NDEBUG
98398/* For tracing reduce actions, the names of all rules are required.
98399*/
98400static const char *const yyRuleName[] = {
98401 /*   0 */ "input ::= cmdlist",
98402 /*   1 */ "cmdlist ::= cmdlist ecmd",
98403 /*   2 */ "cmdlist ::= ecmd",
98404 /*   3 */ "ecmd ::= SEMI",
98405 /*   4 */ "ecmd ::= explain cmdx SEMI",
98406 /*   5 */ "explain ::=",
98407 /*   6 */ "explain ::= EXPLAIN",
98408 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
98409 /*   8 */ "cmdx ::= cmd",
98410 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
98411 /*  10 */ "trans_opt ::=",
98412 /*  11 */ "trans_opt ::= TRANSACTION",
98413 /*  12 */ "trans_opt ::= TRANSACTION nm",
98414 /*  13 */ "transtype ::=",
98415 /*  14 */ "transtype ::= DEFERRED",
98416 /*  15 */ "transtype ::= IMMEDIATE",
98417 /*  16 */ "transtype ::= EXCLUSIVE",
98418 /*  17 */ "cmd ::= COMMIT trans_opt",
98419 /*  18 */ "cmd ::= END trans_opt",
98420 /*  19 */ "cmd ::= ROLLBACK trans_opt",
98421 /*  20 */ "savepoint_opt ::= SAVEPOINT",
98422 /*  21 */ "savepoint_opt ::=",
98423 /*  22 */ "cmd ::= SAVEPOINT nm",
98424 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
98425 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
98426 /*  25 */ "cmd ::= create_table create_table_args",
98427 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
98428 /*  27 */ "createkw ::= CREATE",
98429 /*  28 */ "ifnotexists ::=",
98430 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
98431 /*  30 */ "temp ::= TEMP",
98432 /*  31 */ "temp ::=",
98433 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
98434 /*  33 */ "create_table_args ::= AS select",
98435 /*  34 */ "columnlist ::= columnlist COMMA column",
98436 /*  35 */ "columnlist ::= column",
98437 /*  36 */ "column ::= columnid type carglist",
98438 /*  37 */ "columnid ::= nm",
98439 /*  38 */ "id ::= ID",
98440 /*  39 */ "id ::= INDEXED",
98441 /*  40 */ "ids ::= ID|STRING",
98442 /*  41 */ "nm ::= id",
98443 /*  42 */ "nm ::= STRING",
98444 /*  43 */ "nm ::= JOIN_KW",
98445 /*  44 */ "type ::=",
98446 /*  45 */ "type ::= typetoken",
98447 /*  46 */ "typetoken ::= typename",
98448 /*  47 */ "typetoken ::= typename LP signed RP",
98449 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
98450 /*  49 */ "typename ::= ids",
98451 /*  50 */ "typename ::= typename ids",
98452 /*  51 */ "signed ::= plus_num",
98453 /*  52 */ "signed ::= minus_num",
98454 /*  53 */ "carglist ::= carglist carg",
98455 /*  54 */ "carglist ::=",
98456 /*  55 */ "carg ::= CONSTRAINT nm ccons",
98457 /*  56 */ "carg ::= ccons",
98458 /*  57 */ "ccons ::= DEFAULT term",
98459 /*  58 */ "ccons ::= DEFAULT LP expr RP",
98460 /*  59 */ "ccons ::= DEFAULT PLUS term",
98461 /*  60 */ "ccons ::= DEFAULT MINUS term",
98462 /*  61 */ "ccons ::= DEFAULT id",
98463 /*  62 */ "ccons ::= NULL onconf",
98464 /*  63 */ "ccons ::= NOT NULL onconf",
98465 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
98466 /*  65 */ "ccons ::= UNIQUE onconf",
98467 /*  66 */ "ccons ::= CHECK LP expr RP",
98468 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
98469 /*  68 */ "ccons ::= defer_subclause",
98470 /*  69 */ "ccons ::= COLLATE ids",
98471 /*  70 */ "autoinc ::=",
98472 /*  71 */ "autoinc ::= AUTOINCR",
98473 /*  72 */ "refargs ::=",
98474 /*  73 */ "refargs ::= refargs refarg",
98475 /*  74 */ "refarg ::= MATCH nm",
98476 /*  75 */ "refarg ::= ON INSERT refact",
98477 /*  76 */ "refarg ::= ON DELETE refact",
98478 /*  77 */ "refarg ::= ON UPDATE refact",
98479 /*  78 */ "refact ::= SET NULL",
98480 /*  79 */ "refact ::= SET DEFAULT",
98481 /*  80 */ "refact ::= CASCADE",
98482 /*  81 */ "refact ::= RESTRICT",
98483 /*  82 */ "refact ::= NO ACTION",
98484 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
98485 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
98486 /*  85 */ "init_deferred_pred_opt ::=",
98487 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
98488 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
98489 /*  88 */ "conslist_opt ::=",
98490 /*  89 */ "conslist_opt ::= COMMA conslist",
98491 /*  90 */ "conslist ::= conslist COMMA tcons",
98492 /*  91 */ "conslist ::= conslist tcons",
98493 /*  92 */ "conslist ::= tcons",
98494 /*  93 */ "tcons ::= CONSTRAINT nm",
98495 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
98496 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
98497 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
98498 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
98499 /*  98 */ "defer_subclause_opt ::=",
98500 /*  99 */ "defer_subclause_opt ::= defer_subclause",
98501 /* 100 */ "onconf ::=",
98502 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
98503 /* 102 */ "orconf ::=",
98504 /* 103 */ "orconf ::= OR resolvetype",
98505 /* 104 */ "resolvetype ::= raisetype",
98506 /* 105 */ "resolvetype ::= IGNORE",
98507 /* 106 */ "resolvetype ::= REPLACE",
98508 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
98509 /* 108 */ "ifexists ::= IF EXISTS",
98510 /* 109 */ "ifexists ::=",
98511 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
98512 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
98513 /* 112 */ "cmd ::= select",
98514 /* 113 */ "select ::= oneselect",
98515 /* 114 */ "select ::= select multiselect_op oneselect",
98516 /* 115 */ "multiselect_op ::= UNION",
98517 /* 116 */ "multiselect_op ::= UNION ALL",
98518 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
98519 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
98520 /* 119 */ "distinct ::= DISTINCT",
98521 /* 120 */ "distinct ::= ALL",
98522 /* 121 */ "distinct ::=",
98523 /* 122 */ "sclp ::= selcollist COMMA",
98524 /* 123 */ "sclp ::=",
98525 /* 124 */ "selcollist ::= sclp expr as",
98526 /* 125 */ "selcollist ::= sclp STAR",
98527 /* 126 */ "selcollist ::= sclp nm DOT STAR",
98528 /* 127 */ "as ::= AS nm",
98529 /* 128 */ "as ::= ids",
98530 /* 129 */ "as ::=",
98531 /* 130 */ "from ::=",
98532 /* 131 */ "from ::= FROM seltablist",
98533 /* 132 */ "stl_prefix ::= seltablist joinop",
98534 /* 133 */ "stl_prefix ::=",
98535 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
98536 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
98537 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
98538 /* 137 */ "dbnm ::=",
98539 /* 138 */ "dbnm ::= DOT nm",
98540 /* 139 */ "fullname ::= nm dbnm",
98541 /* 140 */ "joinop ::= COMMA|JOIN",
98542 /* 141 */ "joinop ::= JOIN_KW JOIN",
98543 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
98544 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
98545 /* 144 */ "on_opt ::= ON expr",
98546 /* 145 */ "on_opt ::=",
98547 /* 146 */ "indexed_opt ::=",
98548 /* 147 */ "indexed_opt ::= INDEXED BY nm",
98549 /* 148 */ "indexed_opt ::= NOT INDEXED",
98550 /* 149 */ "using_opt ::= USING LP inscollist RP",
98551 /* 150 */ "using_opt ::=",
98552 /* 151 */ "orderby_opt ::=",
98553 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
98554 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
98555 /* 154 */ "sortlist ::= sortitem sortorder",
98556 /* 155 */ "sortitem ::= expr",
98557 /* 156 */ "sortorder ::= ASC",
98558 /* 157 */ "sortorder ::= DESC",
98559 /* 158 */ "sortorder ::=",
98560 /* 159 */ "groupby_opt ::=",
98561 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
98562 /* 161 */ "having_opt ::=",
98563 /* 162 */ "having_opt ::= HAVING expr",
98564 /* 163 */ "limit_opt ::=",
98565 /* 164 */ "limit_opt ::= LIMIT expr",
98566 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
98567 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
98568 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
98569 /* 168 */ "where_opt ::=",
98570 /* 169 */ "where_opt ::= WHERE expr",
98571 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
98572 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
98573 /* 172 */ "setlist ::= nm EQ expr",
98574 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
98575 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
98576 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
98577 /* 176 */ "insert_cmd ::= INSERT orconf",
98578 /* 177 */ "insert_cmd ::= REPLACE",
98579 /* 178 */ "itemlist ::= itemlist COMMA expr",
98580 /* 179 */ "itemlist ::= expr",
98581 /* 180 */ "inscollist_opt ::=",
98582 /* 181 */ "inscollist_opt ::= LP inscollist RP",
98583 /* 182 */ "inscollist ::= inscollist COMMA nm",
98584 /* 183 */ "inscollist ::= nm",
98585 /* 184 */ "expr ::= term",
98586 /* 185 */ "expr ::= LP expr RP",
98587 /* 186 */ "term ::= NULL",
98588 /* 187 */ "expr ::= id",
98589 /* 188 */ "expr ::= JOIN_KW",
98590 /* 189 */ "expr ::= nm DOT nm",
98591 /* 190 */ "expr ::= nm DOT nm DOT nm",
98592 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
98593 /* 192 */ "term ::= STRING",
98594 /* 193 */ "expr ::= REGISTER",
98595 /* 194 */ "expr ::= VARIABLE",
98596 /* 195 */ "expr ::= expr COLLATE ids",
98597 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
98598 /* 197 */ "expr ::= ID LP distinct exprlist RP",
98599 /* 198 */ "expr ::= ID LP STAR RP",
98600 /* 199 */ "term ::= CTIME_KW",
98601 /* 200 */ "expr ::= expr AND expr",
98602 /* 201 */ "expr ::= expr OR expr",
98603 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
98604 /* 203 */ "expr ::= expr EQ|NE expr",
98605 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
98606 /* 205 */ "expr ::= expr PLUS|MINUS expr",
98607 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
98608 /* 207 */ "expr ::= expr CONCAT expr",
98609 /* 208 */ "likeop ::= LIKE_KW",
98610 /* 209 */ "likeop ::= NOT LIKE_KW",
98611 /* 210 */ "likeop ::= MATCH",
98612 /* 211 */ "likeop ::= NOT MATCH",
98613 /* 212 */ "escape ::= ESCAPE expr",
98614 /* 213 */ "escape ::=",
98615 /* 214 */ "expr ::= expr likeop expr escape",
98616 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
98617 /* 216 */ "expr ::= expr NOT NULL",
98618 /* 217 */ "expr ::= expr IS expr",
98619 /* 218 */ "expr ::= expr IS NOT expr",
98620 /* 219 */ "expr ::= NOT expr",
98621 /* 220 */ "expr ::= BITNOT expr",
98622 /* 221 */ "expr ::= MINUS expr",
98623 /* 222 */ "expr ::= PLUS expr",
98624 /* 223 */ "between_op ::= BETWEEN",
98625 /* 224 */ "between_op ::= NOT BETWEEN",
98626 /* 225 */ "expr ::= expr between_op expr AND expr",
98627 /* 226 */ "in_op ::= IN",
98628 /* 227 */ "in_op ::= NOT IN",
98629 /* 228 */ "expr ::= expr in_op LP exprlist RP",
98630 /* 229 */ "expr ::= LP select RP",
98631 /* 230 */ "expr ::= expr in_op LP select RP",
98632 /* 231 */ "expr ::= expr in_op nm dbnm",
98633 /* 232 */ "expr ::= EXISTS LP select RP",
98634 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
98635 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
98636 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
98637 /* 236 */ "case_else ::= ELSE expr",
98638 /* 237 */ "case_else ::=",
98639 /* 238 */ "case_operand ::= expr",
98640 /* 239 */ "case_operand ::=",
98641 /* 240 */ "exprlist ::= nexprlist",
98642 /* 241 */ "exprlist ::=",
98643 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
98644 /* 243 */ "nexprlist ::= expr",
98645 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
98646 /* 245 */ "uniqueflag ::= UNIQUE",
98647 /* 246 */ "uniqueflag ::=",
98648 /* 247 */ "idxlist_opt ::=",
98649 /* 248 */ "idxlist_opt ::= LP idxlist RP",
98650 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
98651 /* 250 */ "idxlist ::= nm collate sortorder",
98652 /* 251 */ "collate ::=",
98653 /* 252 */ "collate ::= COLLATE ids",
98654 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
98655 /* 254 */ "cmd ::= VACUUM",
98656 /* 255 */ "cmd ::= VACUUM nm",
98657 /* 256 */ "cmd ::= PRAGMA nm dbnm",
98658 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
98659 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
98660 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
98661 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
98662 /* 261 */ "nmnum ::= plus_num",
98663 /* 262 */ "nmnum ::= nm",
98664 /* 263 */ "nmnum ::= ON",
98665 /* 264 */ "nmnum ::= DELETE",
98666 /* 265 */ "nmnum ::= DEFAULT",
98667 /* 266 */ "plus_num ::= plus_opt number",
98668 /* 267 */ "minus_num ::= MINUS number",
98669 /* 268 */ "number ::= INTEGER|FLOAT",
98670 /* 269 */ "plus_opt ::= PLUS",
98671 /* 270 */ "plus_opt ::=",
98672 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
98673 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
98674 /* 273 */ "trigger_time ::= BEFORE",
98675 /* 274 */ "trigger_time ::= AFTER",
98676 /* 275 */ "trigger_time ::= INSTEAD OF",
98677 /* 276 */ "trigger_time ::=",
98678 /* 277 */ "trigger_event ::= DELETE|INSERT",
98679 /* 278 */ "trigger_event ::= UPDATE",
98680 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
98681 /* 280 */ "foreach_clause ::=",
98682 /* 281 */ "foreach_clause ::= FOR EACH ROW",
98683 /* 282 */ "when_clause ::=",
98684 /* 283 */ "when_clause ::= WHEN expr",
98685 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
98686 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
98687 /* 286 */ "trnm ::= nm",
98688 /* 287 */ "trnm ::= nm DOT nm",
98689 /* 288 */ "tridxby ::=",
98690 /* 289 */ "tridxby ::= INDEXED BY nm",
98691 /* 290 */ "tridxby ::= NOT INDEXED",
98692 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
98693 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
98694 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
98695 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
98696 /* 295 */ "trigger_cmd ::= select",
98697 /* 296 */ "expr ::= RAISE LP IGNORE RP",
98698 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
98699 /* 298 */ "raisetype ::= ROLLBACK",
98700 /* 299 */ "raisetype ::= ABORT",
98701 /* 300 */ "raisetype ::= FAIL",
98702 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
98703 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
98704 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
98705 /* 304 */ "key_opt ::=",
98706 /* 305 */ "key_opt ::= KEY expr",
98707 /* 306 */ "database_kw_opt ::= DATABASE",
98708 /* 307 */ "database_kw_opt ::=",
98709 /* 308 */ "cmd ::= REINDEX",
98710 /* 309 */ "cmd ::= REINDEX nm dbnm",
98711 /* 310 */ "cmd ::= ANALYZE",
98712 /* 311 */ "cmd ::= ANALYZE nm dbnm",
98713 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
98714 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
98715 /* 314 */ "add_column_fullname ::= fullname",
98716 /* 315 */ "kwcolumn_opt ::=",
98717 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
98718 /* 317 */ "cmd ::= create_vtab",
98719 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
98720 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
98721 /* 320 */ "vtabarglist ::= vtabarg",
98722 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
98723 /* 322 */ "vtabarg ::=",
98724 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
98725 /* 324 */ "vtabargtoken ::= ANY",
98726 /* 325 */ "vtabargtoken ::= lp anylist RP",
98727 /* 326 */ "lp ::= LP",
98728 /* 327 */ "anylist ::=",
98729 /* 328 */ "anylist ::= anylist LP anylist RP",
98730 /* 329 */ "anylist ::= anylist ANY",
98731};
98732#endif /* NDEBUG */
98733
98734
98735#if YYSTACKDEPTH<=0
98736/*
98737** Try to increase the size of the parser stack.
98738*/
98739static void yyGrowStack(yyParser *p){
98740  int newSize;
98741  yyStackEntry *pNew;
98742
98743  newSize = p->yystksz*2 + 100;
98744  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
98745  if( pNew ){
98746    p->yystack = pNew;
98747    p->yystksz = newSize;
98748#ifndef NDEBUG
98749    if( yyTraceFILE ){
98750      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
98751              yyTracePrompt, p->yystksz);
98752    }
98753#endif
98754  }
98755}
98756#endif
98757
98758/*
98759** This function allocates a new parser.
98760** The only argument is a pointer to a function which works like
98761** malloc.
98762**
98763** Inputs:
98764** A pointer to the function used to allocate memory.
98765**
98766** Outputs:
98767** A pointer to a parser.  This pointer is used in subsequent calls
98768** to sqlite3Parser and sqlite3ParserFree.
98769*/
98770SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
98771  yyParser *pParser;
98772  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
98773  if( pParser ){
98774    pParser->yyidx = -1;
98775#ifdef YYTRACKMAXSTACKDEPTH
98776    pParser->yyidxMax = 0;
98777#endif
98778#if YYSTACKDEPTH<=0
98779    pParser->yystack = NULL;
98780    pParser->yystksz = 0;
98781    yyGrowStack(pParser);
98782#endif
98783  }
98784  return pParser;
98785}
98786
98787/* The following function deletes the value associated with a
98788** symbol.  The symbol can be either a terminal or nonterminal.
98789** "yymajor" is the symbol code, and "yypminor" is a pointer to
98790** the value.
98791*/
98792static void yy_destructor(
98793  yyParser *yypParser,    /* The parser */
98794  YYCODETYPE yymajor,     /* Type code for object to destroy */
98795  YYMINORTYPE *yypminor   /* The object to be destroyed */
98796){
98797  sqlite3ParserARG_FETCH;
98798  switch( yymajor ){
98799    /* Here is inserted the actions which take place when a
98800    ** terminal or non-terminal is destroyed.  This can happen
98801    ** when the symbol is popped from the stack during a
98802    ** reduce or during error processing or when a parser is
98803    ** being destroyed before it is finished parsing.
98804    **
98805    ** Note: during a reduce, the only symbols destroyed are those
98806    ** which appear on the RHS of the rule, but which are not used
98807    ** inside the C code.
98808    */
98809    case 160: /* select */
98810    case 194: /* oneselect */
98811{
98812sqlite3SelectDelete(pParse->db, (yypminor->yy3));
98813}
98814      break;
98815    case 174: /* term */
98816    case 175: /* expr */
98817    case 223: /* escape */
98818{
98819sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
98820}
98821      break;
98822    case 179: /* idxlist_opt */
98823    case 187: /* idxlist */
98824    case 197: /* selcollist */
98825    case 200: /* groupby_opt */
98826    case 202: /* orderby_opt */
98827    case 204: /* sclp */
98828    case 214: /* sortlist */
98829    case 216: /* nexprlist */
98830    case 217: /* setlist */
98831    case 220: /* itemlist */
98832    case 221: /* exprlist */
98833    case 227: /* case_exprlist */
98834{
98835sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
98836}
98837      break;
98838    case 193: /* fullname */
98839    case 198: /* from */
98840    case 206: /* seltablist */
98841    case 207: /* stl_prefix */
98842{
98843sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
98844}
98845      break;
98846    case 199: /* where_opt */
98847    case 201: /* having_opt */
98848    case 210: /* on_opt */
98849    case 215: /* sortitem */
98850    case 226: /* case_operand */
98851    case 228: /* case_else */
98852    case 239: /* when_clause */
98853    case 244: /* key_opt */
98854{
98855sqlite3ExprDelete(pParse->db, (yypminor->yy132));
98856}
98857      break;
98858    case 211: /* using_opt */
98859    case 213: /* inscollist */
98860    case 219: /* inscollist_opt */
98861{
98862sqlite3IdListDelete(pParse->db, (yypminor->yy408));
98863}
98864      break;
98865    case 235: /* trigger_cmd_list */
98866    case 240: /* trigger_cmd */
98867{
98868sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
98869}
98870      break;
98871    case 237: /* trigger_event */
98872{
98873sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
98874}
98875      break;
98876    default:  break;   /* If no destructor action specified: do nothing */
98877  }
98878}
98879
98880/*
98881** Pop the parser's stack once.
98882**
98883** If there is a destructor routine associated with the token which
98884** is popped from the stack, then call it.
98885**
98886** Return the major token number for the symbol popped.
98887*/
98888static int yy_pop_parser_stack(yyParser *pParser){
98889  YYCODETYPE yymajor;
98890  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
98891
98892  /* There is no mechanism by which the parser stack can be popped below
98893  ** empty in SQLite.  */
98894  if( NEVER(pParser->yyidx<0) ) return 0;
98895#ifndef NDEBUG
98896  if( yyTraceFILE && pParser->yyidx>=0 ){
98897    fprintf(yyTraceFILE,"%sPopping %s\n",
98898      yyTracePrompt,
98899      yyTokenName[yytos->major]);
98900  }
98901#endif
98902  yymajor = yytos->major;
98903  yy_destructor(pParser, yymajor, &yytos->minor);
98904  pParser->yyidx--;
98905  return yymajor;
98906}
98907
98908/*
98909** Deallocate and destroy a parser.  Destructors are all called for
98910** all stack elements before shutting the parser down.
98911**
98912** Inputs:
98913** <ul>
98914** <li>  A pointer to the parser.  This should be a pointer
98915**       obtained from sqlite3ParserAlloc.
98916** <li>  A pointer to a function used to reclaim memory obtained
98917**       from malloc.
98918** </ul>
98919*/
98920SQLITE_PRIVATE void sqlite3ParserFree(
98921  void *p,                    /* The parser to be deleted */
98922  void (*freeProc)(void*)     /* Function used to reclaim memory */
98923){
98924  yyParser *pParser = (yyParser*)p;
98925  /* In SQLite, we never try to destroy a parser that was not successfully
98926  ** created in the first place. */
98927  if( NEVER(pParser==0) ) return;
98928  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
98929#if YYSTACKDEPTH<=0
98930  free(pParser->yystack);
98931#endif
98932  (*freeProc)((void*)pParser);
98933}
98934
98935/*
98936** Return the peak depth of the stack for a parser.
98937*/
98938#ifdef YYTRACKMAXSTACKDEPTH
98939SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
98940  yyParser *pParser = (yyParser*)p;
98941  return pParser->yyidxMax;
98942}
98943#endif
98944
98945/*
98946** Find the appropriate action for a parser given the terminal
98947** look-ahead token iLookAhead.
98948**
98949** If the look-ahead token is YYNOCODE, then check to see if the action is
98950** independent of the look-ahead.  If it is, return the action, otherwise
98951** return YY_NO_ACTION.
98952*/
98953static int yy_find_shift_action(
98954  yyParser *pParser,        /* The parser */
98955  YYCODETYPE iLookAhead     /* The look-ahead token */
98956){
98957  int i;
98958  int stateno = pParser->yystack[pParser->yyidx].stateno;
98959
98960  if( stateno>YY_SHIFT_COUNT
98961   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
98962    return yy_default[stateno];
98963  }
98964  assert( iLookAhead!=YYNOCODE );
98965  i += iLookAhead;
98966  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
98967    if( iLookAhead>0 ){
98968#ifdef YYFALLBACK
98969      YYCODETYPE iFallback;            /* Fallback token */
98970      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
98971             && (iFallback = yyFallback[iLookAhead])!=0 ){
98972#ifndef NDEBUG
98973        if( yyTraceFILE ){
98974          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
98975             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
98976        }
98977#endif
98978        return yy_find_shift_action(pParser, iFallback);
98979      }
98980#endif
98981#ifdef YYWILDCARD
98982      {
98983        int j = i - iLookAhead + YYWILDCARD;
98984        if(
98985#if YY_SHIFT_MIN+YYWILDCARD<0
98986          j>=0 &&
98987#endif
98988#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
98989          j<YY_ACTTAB_COUNT &&
98990#endif
98991          yy_lookahead[j]==YYWILDCARD
98992        ){
98993#ifndef NDEBUG
98994          if( yyTraceFILE ){
98995            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
98996               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
98997          }
98998#endif /* NDEBUG */
98999          return yy_action[j];
99000        }
99001      }
99002#endif /* YYWILDCARD */
99003    }
99004    return yy_default[stateno];
99005  }else{
99006    return yy_action[i];
99007  }
99008}
99009
99010/*
99011** Find the appropriate action for a parser given the non-terminal
99012** look-ahead token iLookAhead.
99013**
99014** If the look-ahead token is YYNOCODE, then check to see if the action is
99015** independent of the look-ahead.  If it is, return the action, otherwise
99016** return YY_NO_ACTION.
99017*/
99018static int yy_find_reduce_action(
99019  int stateno,              /* Current state number */
99020  YYCODETYPE iLookAhead     /* The look-ahead token */
99021){
99022  int i;
99023#ifdef YYERRORSYMBOL
99024  if( stateno>YY_REDUCE_COUNT ){
99025    return yy_default[stateno];
99026  }
99027#else
99028  assert( stateno<=YY_REDUCE_COUNT );
99029#endif
99030  i = yy_reduce_ofst[stateno];
99031  assert( i!=YY_REDUCE_USE_DFLT );
99032  assert( iLookAhead!=YYNOCODE );
99033  i += iLookAhead;
99034#ifdef YYERRORSYMBOL
99035  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
99036    return yy_default[stateno];
99037  }
99038#else
99039  assert( i>=0 && i<YY_ACTTAB_COUNT );
99040  assert( yy_lookahead[i]==iLookAhead );
99041#endif
99042  return yy_action[i];
99043}
99044
99045/*
99046** The following routine is called if the stack overflows.
99047*/
99048static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
99049   sqlite3ParserARG_FETCH;
99050   yypParser->yyidx--;
99051#ifndef NDEBUG
99052   if( yyTraceFILE ){
99053     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
99054   }
99055#endif
99056   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
99057   /* Here code is inserted which will execute if the parser
99058   ** stack every overflows */
99059
99060  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
99061  sqlite3ErrorMsg(pParse, "parser stack overflow");
99062  pParse->parseError = 1;
99063   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
99064}
99065
99066/*
99067** Perform a shift action.
99068*/
99069static void yy_shift(
99070  yyParser *yypParser,          /* The parser to be shifted */
99071  int yyNewState,               /* The new state to shift in */
99072  int yyMajor,                  /* The major token to shift in */
99073  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
99074){
99075  yyStackEntry *yytos;
99076  yypParser->yyidx++;
99077#ifdef YYTRACKMAXSTACKDEPTH
99078  if( yypParser->yyidx>yypParser->yyidxMax ){
99079    yypParser->yyidxMax = yypParser->yyidx;
99080  }
99081#endif
99082#if YYSTACKDEPTH>0
99083  if( yypParser->yyidx>=YYSTACKDEPTH ){
99084    yyStackOverflow(yypParser, yypMinor);
99085    return;
99086  }
99087#else
99088  if( yypParser->yyidx>=yypParser->yystksz ){
99089    yyGrowStack(yypParser);
99090    if( yypParser->yyidx>=yypParser->yystksz ){
99091      yyStackOverflow(yypParser, yypMinor);
99092      return;
99093    }
99094  }
99095#endif
99096  yytos = &yypParser->yystack[yypParser->yyidx];
99097  yytos->stateno = (YYACTIONTYPE)yyNewState;
99098  yytos->major = (YYCODETYPE)yyMajor;
99099  yytos->minor = *yypMinor;
99100#ifndef NDEBUG
99101  if( yyTraceFILE && yypParser->yyidx>0 ){
99102    int i;
99103    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
99104    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
99105    for(i=1; i<=yypParser->yyidx; i++)
99106      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
99107    fprintf(yyTraceFILE,"\n");
99108  }
99109#endif
99110}
99111
99112/* The following table contains information about every rule that
99113** is used during the reduce.
99114*/
99115static const struct {
99116  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
99117  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
99118} yyRuleInfo[] = {
99119  { 142, 1 },
99120  { 143, 2 },
99121  { 143, 1 },
99122  { 144, 1 },
99123  { 144, 3 },
99124  { 145, 0 },
99125  { 145, 1 },
99126  { 145, 3 },
99127  { 146, 1 },
99128  { 147, 3 },
99129  { 149, 0 },
99130  { 149, 1 },
99131  { 149, 2 },
99132  { 148, 0 },
99133  { 148, 1 },
99134  { 148, 1 },
99135  { 148, 1 },
99136  { 147, 2 },
99137  { 147, 2 },
99138  { 147, 2 },
99139  { 151, 1 },
99140  { 151, 0 },
99141  { 147, 2 },
99142  { 147, 3 },
99143  { 147, 5 },
99144  { 147, 2 },
99145  { 152, 6 },
99146  { 154, 1 },
99147  { 156, 0 },
99148  { 156, 3 },
99149  { 155, 1 },
99150  { 155, 0 },
99151  { 153, 4 },
99152  { 153, 2 },
99153  { 158, 3 },
99154  { 158, 1 },
99155  { 161, 3 },
99156  { 162, 1 },
99157  { 165, 1 },
99158  { 165, 1 },
99159  { 166, 1 },
99160  { 150, 1 },
99161  { 150, 1 },
99162  { 150, 1 },
99163  { 163, 0 },
99164  { 163, 1 },
99165  { 167, 1 },
99166  { 167, 4 },
99167  { 167, 6 },
99168  { 168, 1 },
99169  { 168, 2 },
99170  { 169, 1 },
99171  { 169, 1 },
99172  { 164, 2 },
99173  { 164, 0 },
99174  { 172, 3 },
99175  { 172, 1 },
99176  { 173, 2 },
99177  { 173, 4 },
99178  { 173, 3 },
99179  { 173, 3 },
99180  { 173, 2 },
99181  { 173, 2 },
99182  { 173, 3 },
99183  { 173, 5 },
99184  { 173, 2 },
99185  { 173, 4 },
99186  { 173, 4 },
99187  { 173, 1 },
99188  { 173, 2 },
99189  { 178, 0 },
99190  { 178, 1 },
99191  { 180, 0 },
99192  { 180, 2 },
99193  { 182, 2 },
99194  { 182, 3 },
99195  { 182, 3 },
99196  { 182, 3 },
99197  { 183, 2 },
99198  { 183, 2 },
99199  { 183, 1 },
99200  { 183, 1 },
99201  { 183, 2 },
99202  { 181, 3 },
99203  { 181, 2 },
99204  { 184, 0 },
99205  { 184, 2 },
99206  { 184, 2 },
99207  { 159, 0 },
99208  { 159, 2 },
99209  { 185, 3 },
99210  { 185, 2 },
99211  { 185, 1 },
99212  { 186, 2 },
99213  { 186, 7 },
99214  { 186, 5 },
99215  { 186, 5 },
99216  { 186, 10 },
99217  { 188, 0 },
99218  { 188, 1 },
99219  { 176, 0 },
99220  { 176, 3 },
99221  { 189, 0 },
99222  { 189, 2 },
99223  { 190, 1 },
99224  { 190, 1 },
99225  { 190, 1 },
99226  { 147, 4 },
99227  { 192, 2 },
99228  { 192, 0 },
99229  { 147, 8 },
99230  { 147, 4 },
99231  { 147, 1 },
99232  { 160, 1 },
99233  { 160, 3 },
99234  { 195, 1 },
99235  { 195, 2 },
99236  { 195, 1 },
99237  { 194, 9 },
99238  { 196, 1 },
99239  { 196, 1 },
99240  { 196, 0 },
99241  { 204, 2 },
99242  { 204, 0 },
99243  { 197, 3 },
99244  { 197, 2 },
99245  { 197, 4 },
99246  { 205, 2 },
99247  { 205, 1 },
99248  { 205, 0 },
99249  { 198, 0 },
99250  { 198, 2 },
99251  { 207, 2 },
99252  { 207, 0 },
99253  { 206, 7 },
99254  { 206, 7 },
99255  { 206, 7 },
99256  { 157, 0 },
99257  { 157, 2 },
99258  { 193, 2 },
99259  { 208, 1 },
99260  { 208, 2 },
99261  { 208, 3 },
99262  { 208, 4 },
99263  { 210, 2 },
99264  { 210, 0 },
99265  { 209, 0 },
99266  { 209, 3 },
99267  { 209, 2 },
99268  { 211, 4 },
99269  { 211, 0 },
99270  { 202, 0 },
99271  { 202, 3 },
99272  { 214, 4 },
99273  { 214, 2 },
99274  { 215, 1 },
99275  { 177, 1 },
99276  { 177, 1 },
99277  { 177, 0 },
99278  { 200, 0 },
99279  { 200, 3 },
99280  { 201, 0 },
99281  { 201, 2 },
99282  { 203, 0 },
99283  { 203, 2 },
99284  { 203, 4 },
99285  { 203, 4 },
99286  { 147, 5 },
99287  { 199, 0 },
99288  { 199, 2 },
99289  { 147, 7 },
99290  { 217, 5 },
99291  { 217, 3 },
99292  { 147, 8 },
99293  { 147, 5 },
99294  { 147, 6 },
99295  { 218, 2 },
99296  { 218, 1 },
99297  { 220, 3 },
99298  { 220, 1 },
99299  { 219, 0 },
99300  { 219, 3 },
99301  { 213, 3 },
99302  { 213, 1 },
99303  { 175, 1 },
99304  { 175, 3 },
99305  { 174, 1 },
99306  { 175, 1 },
99307  { 175, 1 },
99308  { 175, 3 },
99309  { 175, 5 },
99310  { 174, 1 },
99311  { 174, 1 },
99312  { 175, 1 },
99313  { 175, 1 },
99314  { 175, 3 },
99315  { 175, 6 },
99316  { 175, 5 },
99317  { 175, 4 },
99318  { 174, 1 },
99319  { 175, 3 },
99320  { 175, 3 },
99321  { 175, 3 },
99322  { 175, 3 },
99323  { 175, 3 },
99324  { 175, 3 },
99325  { 175, 3 },
99326  { 175, 3 },
99327  { 222, 1 },
99328  { 222, 2 },
99329  { 222, 1 },
99330  { 222, 2 },
99331  { 223, 2 },
99332  { 223, 0 },
99333  { 175, 4 },
99334  { 175, 2 },
99335  { 175, 3 },
99336  { 175, 3 },
99337  { 175, 4 },
99338  { 175, 2 },
99339  { 175, 2 },
99340  { 175, 2 },
99341  { 175, 2 },
99342  { 224, 1 },
99343  { 224, 2 },
99344  { 175, 5 },
99345  { 225, 1 },
99346  { 225, 2 },
99347  { 175, 5 },
99348  { 175, 3 },
99349  { 175, 5 },
99350  { 175, 4 },
99351  { 175, 4 },
99352  { 175, 5 },
99353  { 227, 5 },
99354  { 227, 4 },
99355  { 228, 2 },
99356  { 228, 0 },
99357  { 226, 1 },
99358  { 226, 0 },
99359  { 221, 1 },
99360  { 221, 0 },
99361  { 216, 3 },
99362  { 216, 1 },
99363  { 147, 11 },
99364  { 229, 1 },
99365  { 229, 0 },
99366  { 179, 0 },
99367  { 179, 3 },
99368  { 187, 5 },
99369  { 187, 3 },
99370  { 230, 0 },
99371  { 230, 2 },
99372  { 147, 4 },
99373  { 147, 1 },
99374  { 147, 2 },
99375  { 147, 3 },
99376  { 147, 5 },
99377  { 147, 6 },
99378  { 147, 5 },
99379  { 147, 6 },
99380  { 231, 1 },
99381  { 231, 1 },
99382  { 231, 1 },
99383  { 231, 1 },
99384  { 231, 1 },
99385  { 170, 2 },
99386  { 171, 2 },
99387  { 233, 1 },
99388  { 232, 1 },
99389  { 232, 0 },
99390  { 147, 5 },
99391  { 234, 11 },
99392  { 236, 1 },
99393  { 236, 1 },
99394  { 236, 2 },
99395  { 236, 0 },
99396  { 237, 1 },
99397  { 237, 1 },
99398  { 237, 3 },
99399  { 238, 0 },
99400  { 238, 3 },
99401  { 239, 0 },
99402  { 239, 2 },
99403  { 235, 3 },
99404  { 235, 2 },
99405  { 241, 1 },
99406  { 241, 3 },
99407  { 242, 0 },
99408  { 242, 3 },
99409  { 242, 2 },
99410  { 240, 7 },
99411  { 240, 8 },
99412  { 240, 5 },
99413  { 240, 5 },
99414  { 240, 1 },
99415  { 175, 4 },
99416  { 175, 6 },
99417  { 191, 1 },
99418  { 191, 1 },
99419  { 191, 1 },
99420  { 147, 4 },
99421  { 147, 6 },
99422  { 147, 3 },
99423  { 244, 0 },
99424  { 244, 2 },
99425  { 243, 1 },
99426  { 243, 0 },
99427  { 147, 1 },
99428  { 147, 3 },
99429  { 147, 1 },
99430  { 147, 3 },
99431  { 147, 6 },
99432  { 147, 6 },
99433  { 245, 1 },
99434  { 246, 0 },
99435  { 246, 1 },
99436  { 147, 1 },
99437  { 147, 4 },
99438  { 247, 7 },
99439  { 248, 1 },
99440  { 248, 3 },
99441  { 249, 0 },
99442  { 249, 2 },
99443  { 250, 1 },
99444  { 250, 3 },
99445  { 251, 1 },
99446  { 252, 0 },
99447  { 252, 4 },
99448  { 252, 2 },
99449};
99450
99451static void yy_accept(yyParser*);  /* Forward Declaration */
99452
99453/*
99454** Perform a reduce action and the shift that must immediately
99455** follow the reduce.
99456*/
99457static void yy_reduce(
99458  yyParser *yypParser,         /* The parser */
99459  int yyruleno                 /* Number of the rule by which to reduce */
99460){
99461  int yygoto;                     /* The next state */
99462  int yyact;                      /* The next action */
99463  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
99464  yyStackEntry *yymsp;            /* The top of the parser's stack */
99465  int yysize;                     /* Amount to pop the stack */
99466  sqlite3ParserARG_FETCH;
99467  yymsp = &yypParser->yystack[yypParser->yyidx];
99468#ifndef NDEBUG
99469  if( yyTraceFILE && yyruleno>=0
99470        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
99471    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
99472      yyRuleName[yyruleno]);
99473  }
99474#endif /* NDEBUG */
99475
99476  /* Silence complaints from purify about yygotominor being uninitialized
99477  ** in some cases when it is copied into the stack after the following
99478  ** switch.  yygotominor is uninitialized when a rule reduces that does
99479  ** not set the value of its left-hand side nonterminal.  Leaving the
99480  ** value of the nonterminal uninitialized is utterly harmless as long
99481  ** as the value is never used.  So really the only thing this code
99482  ** accomplishes is to quieten purify.
99483  **
99484  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
99485  ** without this code, their parser segfaults.  I'm not sure what there
99486  ** parser is doing to make this happen.  This is the second bug report
99487  ** from wireshark this week.  Clearly they are stressing Lemon in ways
99488  ** that it has not been previously stressed...  (SQLite ticket #2172)
99489  */
99490  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
99491  yygotominor = yyzerominor;
99492
99493
99494  switch( yyruleno ){
99495  /* Beginning here are the reduction cases.  A typical example
99496  ** follows:
99497  **   case 0:
99498  **  #line <lineno> <grammarfile>
99499  **     { ... }           // User supplied code
99500  **  #line <lineno> <thisfile>
99501  **     break;
99502  */
99503      case 5: /* explain ::= */
99504{ sqlite3BeginParse(pParse, 0); }
99505        break;
99506      case 6: /* explain ::= EXPLAIN */
99507{ sqlite3BeginParse(pParse, 1); }
99508        break;
99509      case 7: /* explain ::= EXPLAIN QUERY PLAN */
99510{ sqlite3BeginParse(pParse, 2); }
99511        break;
99512      case 8: /* cmdx ::= cmd */
99513{ sqlite3FinishCoding(pParse); }
99514        break;
99515      case 9: /* cmd ::= BEGIN transtype trans_opt */
99516{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
99517        break;
99518      case 13: /* transtype ::= */
99519{yygotominor.yy328 = TK_DEFERRED;}
99520        break;
99521      case 14: /* transtype ::= DEFERRED */
99522      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
99523      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
99524      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
99525      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
99526{yygotominor.yy328 = yymsp[0].major;}
99527        break;
99528      case 17: /* cmd ::= COMMIT trans_opt */
99529      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
99530{sqlite3CommitTransaction(pParse);}
99531        break;
99532      case 19: /* cmd ::= ROLLBACK trans_opt */
99533{sqlite3RollbackTransaction(pParse);}
99534        break;
99535      case 22: /* cmd ::= SAVEPOINT nm */
99536{
99537  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
99538}
99539        break;
99540      case 23: /* cmd ::= RELEASE savepoint_opt nm */
99541{
99542  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
99543}
99544        break;
99545      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
99546{
99547  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
99548}
99549        break;
99550      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
99551{
99552   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
99553}
99554        break;
99555      case 27: /* createkw ::= CREATE */
99556{
99557  pParse->db->lookaside.bEnabled = 0;
99558  yygotominor.yy0 = yymsp[0].minor.yy0;
99559}
99560        break;
99561      case 28: /* ifnotexists ::= */
99562      case 31: /* temp ::= */ yytestcase(yyruleno==31);
99563      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
99564      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
99565      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
99566      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
99567      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
99568      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
99569      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
99570      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
99571      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
99572      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
99573{yygotominor.yy328 = 0;}
99574        break;
99575      case 29: /* ifnotexists ::= IF NOT EXISTS */
99576      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
99577      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
99578      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
99579      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
99580      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
99581      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
99582      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
99583{yygotominor.yy328 = 1;}
99584        break;
99585      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
99586{
99587  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
99588}
99589        break;
99590      case 33: /* create_table_args ::= AS select */
99591{
99592  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
99593  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
99594}
99595        break;
99596      case 36: /* column ::= columnid type carglist */
99597{
99598  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
99599  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
99600}
99601        break;
99602      case 37: /* columnid ::= nm */
99603{
99604  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
99605  yygotominor.yy0 = yymsp[0].minor.yy0;
99606}
99607        break;
99608      case 38: /* id ::= ID */
99609      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
99610      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
99611      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
99612      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
99613      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
99614      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
99615      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
99616      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
99617      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
99618      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
99619      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
99620      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
99621      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
99622      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
99623      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
99624      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
99625      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
99626      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
99627      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
99628      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
99629      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
99630{yygotominor.yy0 = yymsp[0].minor.yy0;}
99631        break;
99632      case 45: /* type ::= typetoken */
99633{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
99634        break;
99635      case 47: /* typetoken ::= typename LP signed RP */
99636{
99637  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
99638  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
99639}
99640        break;
99641      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
99642{
99643  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
99644  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
99645}
99646        break;
99647      case 50: /* typename ::= typename ids */
99648{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);}
99649        break;
99650      case 57: /* ccons ::= DEFAULT term */
99651      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
99652{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
99653        break;
99654      case 58: /* ccons ::= DEFAULT LP expr RP */
99655{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
99656        break;
99657      case 60: /* ccons ::= DEFAULT MINUS term */
99658{
99659  ExprSpan v;
99660  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
99661  v.zStart = yymsp[-1].minor.yy0.z;
99662  v.zEnd = yymsp[0].minor.yy346.zEnd;
99663  sqlite3AddDefaultValue(pParse,&v);
99664}
99665        break;
99666      case 61: /* ccons ::= DEFAULT id */
99667{
99668  ExprSpan v;
99669  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
99670  sqlite3AddDefaultValue(pParse,&v);
99671}
99672        break;
99673      case 63: /* ccons ::= NOT NULL onconf */
99674{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
99675        break;
99676      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
99677{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
99678        break;
99679      case 65: /* ccons ::= UNIQUE onconf */
99680{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
99681        break;
99682      case 66: /* ccons ::= CHECK LP expr RP */
99683{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
99684        break;
99685      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
99686{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
99687        break;
99688      case 68: /* ccons ::= defer_subclause */
99689{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
99690        break;
99691      case 69: /* ccons ::= COLLATE ids */
99692{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
99693        break;
99694      case 72: /* refargs ::= */
99695{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
99696        break;
99697      case 73: /* refargs ::= refargs refarg */
99698{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
99699        break;
99700      case 74: /* refarg ::= MATCH nm */
99701      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
99702{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
99703        break;
99704      case 76: /* refarg ::= ON DELETE refact */
99705{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
99706        break;
99707      case 77: /* refarg ::= ON UPDATE refact */
99708{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
99709        break;
99710      case 78: /* refact ::= SET NULL */
99711{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
99712        break;
99713      case 79: /* refact ::= SET DEFAULT */
99714{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
99715        break;
99716      case 80: /* refact ::= CASCADE */
99717{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
99718        break;
99719      case 81: /* refact ::= RESTRICT */
99720{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
99721        break;
99722      case 82: /* refact ::= NO ACTION */
99723{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
99724        break;
99725      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
99726      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
99727      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
99728      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
99729{yygotominor.yy328 = yymsp[0].minor.yy328;}
99730        break;
99731      case 88: /* conslist_opt ::= */
99732{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
99733        break;
99734      case 89: /* conslist_opt ::= COMMA conslist */
99735{yygotominor.yy0 = yymsp[-1].minor.yy0;}
99736        break;
99737      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
99738{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
99739        break;
99740      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
99741{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
99742        break;
99743      case 96: /* tcons ::= CHECK LP expr RP onconf */
99744{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
99745        break;
99746      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
99747{
99748    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
99749    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
99750}
99751        break;
99752      case 100: /* onconf ::= */
99753{yygotominor.yy328 = OE_Default;}
99754        break;
99755      case 102: /* orconf ::= */
99756{yygotominor.yy186 = OE_Default;}
99757        break;
99758      case 103: /* orconf ::= OR resolvetype */
99759{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
99760        break;
99761      case 105: /* resolvetype ::= IGNORE */
99762{yygotominor.yy328 = OE_Ignore;}
99763        break;
99764      case 106: /* resolvetype ::= REPLACE */
99765{yygotominor.yy328 = OE_Replace;}
99766        break;
99767      case 107: /* cmd ::= DROP TABLE ifexists fullname */
99768{
99769  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
99770}
99771        break;
99772      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
99773{
99774  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
99775}
99776        break;
99777      case 111: /* cmd ::= DROP VIEW ifexists fullname */
99778{
99779  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
99780}
99781        break;
99782      case 112: /* cmd ::= select */
99783{
99784  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
99785  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
99786  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
99787}
99788        break;
99789      case 113: /* select ::= oneselect */
99790{yygotominor.yy3 = yymsp[0].minor.yy3;}
99791        break;
99792      case 114: /* select ::= select multiselect_op oneselect */
99793{
99794  if( yymsp[0].minor.yy3 ){
99795    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
99796    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
99797  }else{
99798    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
99799  }
99800  yygotominor.yy3 = yymsp[0].minor.yy3;
99801}
99802        break;
99803      case 116: /* multiselect_op ::= UNION ALL */
99804{yygotominor.yy328 = TK_ALL;}
99805        break;
99806      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
99807{
99808  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
99809}
99810        break;
99811      case 122: /* sclp ::= selcollist COMMA */
99812      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
99813{yygotominor.yy14 = yymsp[-1].minor.yy14;}
99814        break;
99815      case 123: /* sclp ::= */
99816      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
99817      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
99818      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
99819      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
99820{yygotominor.yy14 = 0;}
99821        break;
99822      case 124: /* selcollist ::= sclp expr as */
99823{
99824   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
99825   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
99826   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
99827}
99828        break;
99829      case 125: /* selcollist ::= sclp STAR */
99830{
99831  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
99832  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
99833}
99834        break;
99835      case 126: /* selcollist ::= sclp nm DOT STAR */
99836{
99837  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
99838  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
99839  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
99840  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
99841}
99842        break;
99843      case 129: /* as ::= */
99844{yygotominor.yy0.n = 0;}
99845        break;
99846      case 130: /* from ::= */
99847{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
99848        break;
99849      case 131: /* from ::= FROM seltablist */
99850{
99851  yygotominor.yy65 = yymsp[0].minor.yy65;
99852  sqlite3SrcListShiftJoinType(yygotominor.yy65);
99853}
99854        break;
99855      case 132: /* stl_prefix ::= seltablist joinop */
99856{
99857   yygotominor.yy65 = yymsp[-1].minor.yy65;
99858   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
99859}
99860        break;
99861      case 133: /* stl_prefix ::= */
99862{yygotominor.yy65 = 0;}
99863        break;
99864      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
99865{
99866  yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
99867  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
99868}
99869        break;
99870      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
99871{
99872    yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
99873  }
99874        break;
99875      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
99876{
99877    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
99878      yygotominor.yy65 = yymsp[-4].minor.yy65;
99879    }else{
99880      Select *pSubquery;
99881      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
99882      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
99883      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
99884    }
99885  }
99886        break;
99887      case 137: /* dbnm ::= */
99888      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
99889{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
99890        break;
99891      case 139: /* fullname ::= nm dbnm */
99892{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
99893        break;
99894      case 140: /* joinop ::= COMMA|JOIN */
99895{ yygotominor.yy328 = JT_INNER; }
99896        break;
99897      case 141: /* joinop ::= JOIN_KW JOIN */
99898{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
99899        break;
99900      case 142: /* joinop ::= JOIN_KW nm JOIN */
99901{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
99902        break;
99903      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
99904{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
99905        break;
99906      case 144: /* on_opt ::= ON expr */
99907      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
99908      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
99909      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
99910      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
99911      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
99912{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
99913        break;
99914      case 145: /* on_opt ::= */
99915      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
99916      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
99917      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
99918      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
99919{yygotominor.yy132 = 0;}
99920        break;
99921      case 148: /* indexed_opt ::= NOT INDEXED */
99922{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
99923        break;
99924      case 149: /* using_opt ::= USING LP inscollist RP */
99925      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
99926{yygotominor.yy408 = yymsp[-1].minor.yy408;}
99927        break;
99928      case 150: /* using_opt ::= */
99929      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
99930{yygotominor.yy408 = 0;}
99931        break;
99932      case 152: /* orderby_opt ::= ORDER BY sortlist */
99933      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
99934      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
99935{yygotominor.yy14 = yymsp[0].minor.yy14;}
99936        break;
99937      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
99938{
99939  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
99940  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
99941}
99942        break;
99943      case 154: /* sortlist ::= sortitem sortorder */
99944{
99945  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
99946  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
99947}
99948        break;
99949      case 156: /* sortorder ::= ASC */
99950      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
99951{yygotominor.yy328 = SQLITE_SO_ASC;}
99952        break;
99953      case 157: /* sortorder ::= DESC */
99954{yygotominor.yy328 = SQLITE_SO_DESC;}
99955        break;
99956      case 163: /* limit_opt ::= */
99957{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
99958        break;
99959      case 164: /* limit_opt ::= LIMIT expr */
99960{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
99961        break;
99962      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
99963{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
99964        break;
99965      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
99966{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
99967        break;
99968      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
99969{
99970  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
99971  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
99972}
99973        break;
99974      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
99975{
99976  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
99977  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
99978  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
99979}
99980        break;
99981      case 171: /* setlist ::= setlist COMMA nm EQ expr */
99982{
99983  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
99984  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
99985}
99986        break;
99987      case 172: /* setlist ::= nm EQ expr */
99988{
99989  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
99990  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
99991}
99992        break;
99993      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
99994{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
99995        break;
99996      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
99997{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
99998        break;
99999      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
100000{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
100001        break;
100002      case 176: /* insert_cmd ::= INSERT orconf */
100003{yygotominor.yy186 = yymsp[0].minor.yy186;}
100004        break;
100005      case 177: /* insert_cmd ::= REPLACE */
100006{yygotominor.yy186 = OE_Replace;}
100007        break;
100008      case 178: /* itemlist ::= itemlist COMMA expr */
100009      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
100010{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
100011        break;
100012      case 179: /* itemlist ::= expr */
100013      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
100014{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
100015        break;
100016      case 182: /* inscollist ::= inscollist COMMA nm */
100017{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
100018        break;
100019      case 183: /* inscollist ::= nm */
100020{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
100021        break;
100022      case 184: /* expr ::= term */
100023      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
100024{yygotominor.yy346 = yymsp[0].minor.yy346;}
100025        break;
100026      case 185: /* expr ::= LP expr RP */
100027{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
100028        break;
100029      case 186: /* term ::= NULL */
100030      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
100031      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
100032{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
100033        break;
100034      case 187: /* expr ::= id */
100035      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
100036{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
100037        break;
100038      case 189: /* expr ::= nm DOT nm */
100039{
100040  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100041  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100042  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
100043  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
100044}
100045        break;
100046      case 190: /* expr ::= nm DOT nm DOT nm */
100047{
100048  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
100049  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100050  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100051  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
100052  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
100053  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100054}
100055        break;
100056      case 193: /* expr ::= REGISTER */
100057{
100058  /* When doing a nested parse, one can include terms in an expression
100059  ** that look like this:   #1 #2 ...  These terms refer to registers
100060  ** in the virtual machine.  #N is the N-th register. */
100061  if( pParse->nested==0 ){
100062    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
100063    yygotominor.yy346.pExpr = 0;
100064  }else{
100065    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
100066    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
100067  }
100068  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100069}
100070        break;
100071      case 194: /* expr ::= VARIABLE */
100072{
100073  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
100074  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
100075  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100076}
100077        break;
100078      case 195: /* expr ::= expr COLLATE ids */
100079{
100080  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
100081  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
100082  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100083}
100084        break;
100085      case 196: /* expr ::= CAST LP expr AS typetoken RP */
100086{
100087  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
100088  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
100089}
100090        break;
100091      case 197: /* expr ::= ID LP distinct exprlist RP */
100092{
100093  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
100094    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
100095  }
100096  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
100097  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100098  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
100099    yygotominor.yy346.pExpr->flags |= EP_Distinct;
100100  }
100101}
100102        break;
100103      case 198: /* expr ::= ID LP STAR RP */
100104{
100105  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
100106  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
100107}
100108        break;
100109      case 199: /* term ::= CTIME_KW */
100110{
100111  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
100112  ** treated as functions that return constants */
100113  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
100114  if( yygotominor.yy346.pExpr ){
100115    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
100116  }
100117  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100118}
100119        break;
100120      case 200: /* expr ::= expr AND expr */
100121      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
100122      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
100123      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
100124      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
100125      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
100126      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
100127      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
100128{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
100129        break;
100130      case 208: /* likeop ::= LIKE_KW */
100131      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
100132{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
100133        break;
100134      case 209: /* likeop ::= NOT LIKE_KW */
100135      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
100136{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
100137        break;
100138      case 213: /* escape ::= */
100139{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
100140        break;
100141      case 214: /* expr ::= expr likeop expr escape */
100142{
100143  ExprList *pList;
100144  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
100145  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
100146  if( yymsp[0].minor.yy346.pExpr ){
100147    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
100148  }
100149  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
100150  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
100151  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
100152  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
100153  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
100154}
100155        break;
100156      case 215: /* expr ::= expr ISNULL|NOTNULL */
100157{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
100158        break;
100159      case 216: /* expr ::= expr NOT NULL */
100160{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
100161        break;
100162      case 217: /* expr ::= expr IS expr */
100163{
100164  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
100165  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
100166}
100167        break;
100168      case 218: /* expr ::= expr IS NOT expr */
100169{
100170  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
100171  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
100172}
100173        break;
100174      case 219: /* expr ::= NOT expr */
100175      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
100176{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
100177        break;
100178      case 221: /* expr ::= MINUS expr */
100179{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
100180        break;
100181      case 222: /* expr ::= PLUS expr */
100182{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
100183        break;
100184      case 225: /* expr ::= expr between_op expr AND expr */
100185{
100186  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
100187  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
100188  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
100189  if( yygotominor.yy346.pExpr ){
100190    yygotominor.yy346.pExpr->x.pList = pList;
100191  }else{
100192    sqlite3ExprListDelete(pParse->db, pList);
100193  }
100194  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
100195  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
100196  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
100197}
100198        break;
100199      case 228: /* expr ::= expr in_op LP exprlist RP */
100200{
100201    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
100202    if( yygotominor.yy346.pExpr ){
100203      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
100204      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
100205    }else{
100206      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
100207    }
100208    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
100209    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
100210    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100211  }
100212        break;
100213      case 229: /* expr ::= LP select RP */
100214{
100215    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
100216    if( yygotominor.yy346.pExpr ){
100217      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
100218      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
100219      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
100220    }else{
100221      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
100222    }
100223    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
100224    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100225  }
100226        break;
100227      case 230: /* expr ::= expr in_op LP select RP */
100228{
100229    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
100230    if( yygotominor.yy346.pExpr ){
100231      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
100232      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
100233      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
100234    }else{
100235      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
100236    }
100237    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
100238    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
100239    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100240  }
100241        break;
100242      case 231: /* expr ::= expr in_op nm dbnm */
100243{
100244    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
100245    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
100246    if( yygotominor.yy346.pExpr ){
100247      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
100248      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
100249      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
100250    }else{
100251      sqlite3SrcListDelete(pParse->db, pSrc);
100252    }
100253    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
100254    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
100255    yygotominor.yy346.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];
100256  }
100257        break;
100258      case 232: /* expr ::= EXISTS LP select RP */
100259{
100260    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
100261    if( p ){
100262      p->x.pSelect = yymsp[-1].minor.yy3;
100263      ExprSetProperty(p, EP_xIsSelect);
100264      sqlite3ExprSetHeight(pParse, p);
100265    }else{
100266      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
100267    }
100268    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
100269    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100270  }
100271        break;
100272      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
100273{
100274  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
100275  if( yygotominor.yy346.pExpr ){
100276    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
100277    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
100278  }else{
100279    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
100280  }
100281  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
100282  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100283}
100284        break;
100285      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
100286{
100287  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
100288  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
100289}
100290        break;
100291      case 235: /* case_exprlist ::= WHEN expr THEN expr */
100292{
100293  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
100294  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
100295}
100296        break;
100297      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
100298{
100299  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
100300                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
100301                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
100302}
100303        break;
100304      case 245: /* uniqueflag ::= UNIQUE */
100305      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
100306{yygotominor.yy328 = OE_Abort;}
100307        break;
100308      case 246: /* uniqueflag ::= */
100309{yygotominor.yy328 = OE_None;}
100310        break;
100311      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
100312{
100313  Expr *p = 0;
100314  if( yymsp[-1].minor.yy0.n>0 ){
100315    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
100316    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100317  }
100318  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
100319  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
100320  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
100321  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
100322}
100323        break;
100324      case 250: /* idxlist ::= nm collate sortorder */
100325{
100326  Expr *p = 0;
100327  if( yymsp[-1].minor.yy0.n>0 ){
100328    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
100329    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100330  }
100331  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
100332  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
100333  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
100334  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
100335}
100336        break;
100337      case 251: /* collate ::= */
100338{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
100339        break;
100340      case 253: /* cmd ::= DROP INDEX ifexists fullname */
100341{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
100342        break;
100343      case 254: /* cmd ::= VACUUM */
100344      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
100345{sqlite3Vacuum(pParse);}
100346        break;
100347      case 256: /* cmd ::= PRAGMA nm dbnm */
100348{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
100349        break;
100350      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
100351{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
100352        break;
100353      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
100354{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
100355        break;
100356      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
100357{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
100358        break;
100359      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
100360{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
100361        break;
100362      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
100363{
100364  Token all;
100365  all.z = yymsp[-3].minor.yy0.z;
100366  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
100367  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
100368}
100369        break;
100370      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
100371{
100372  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
100373  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
100374}
100375        break;
100376      case 273: /* trigger_time ::= BEFORE */
100377      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
100378{ yygotominor.yy328 = TK_BEFORE; }
100379        break;
100380      case 274: /* trigger_time ::= AFTER */
100381{ yygotominor.yy328 = TK_AFTER;  }
100382        break;
100383      case 275: /* trigger_time ::= INSTEAD OF */
100384{ yygotominor.yy328 = TK_INSTEAD;}
100385        break;
100386      case 277: /* trigger_event ::= DELETE|INSERT */
100387      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
100388{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
100389        break;
100390      case 279: /* trigger_event ::= UPDATE OF inscollist */
100391{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
100392        break;
100393      case 282: /* when_clause ::= */
100394      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
100395{ yygotominor.yy132 = 0; }
100396        break;
100397      case 283: /* when_clause ::= WHEN expr */
100398      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
100399{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
100400        break;
100401      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
100402{
100403  assert( yymsp[-2].minor.yy473!=0 );
100404  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
100405  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
100406  yygotominor.yy473 = yymsp[-2].minor.yy473;
100407}
100408        break;
100409      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
100410{
100411  assert( yymsp[-1].minor.yy473!=0 );
100412  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
100413  yygotominor.yy473 = yymsp[-1].minor.yy473;
100414}
100415        break;
100416      case 287: /* trnm ::= nm DOT nm */
100417{
100418  yygotominor.yy0 = yymsp[0].minor.yy0;
100419  sqlite3ErrorMsg(pParse,
100420        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
100421        "statements within triggers");
100422}
100423        break;
100424      case 289: /* tridxby ::= INDEXED BY nm */
100425{
100426  sqlite3ErrorMsg(pParse,
100427        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
100428        "within triggers");
100429}
100430        break;
100431      case 290: /* tridxby ::= NOT INDEXED */
100432{
100433  sqlite3ErrorMsg(pParse,
100434        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
100435        "within triggers");
100436}
100437        break;
100438      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
100439{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
100440        break;
100441      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
100442{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
100443        break;
100444      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
100445{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
100446        break;
100447      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
100448{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
100449        break;
100450      case 295: /* trigger_cmd ::= select */
100451{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
100452        break;
100453      case 296: /* expr ::= RAISE LP IGNORE RP */
100454{
100455  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
100456  if( yygotominor.yy346.pExpr ){
100457    yygotominor.yy346.pExpr->affinity = OE_Ignore;
100458  }
100459  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
100460  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100461}
100462        break;
100463      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
100464{
100465  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
100466  if( yygotominor.yy346.pExpr ) {
100467    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
100468  }
100469  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
100470  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100471}
100472        break;
100473      case 298: /* raisetype ::= ROLLBACK */
100474{yygotominor.yy328 = OE_Rollback;}
100475        break;
100476      case 300: /* raisetype ::= FAIL */
100477{yygotominor.yy328 = OE_Fail;}
100478        break;
100479      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
100480{
100481  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
100482}
100483        break;
100484      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
100485{
100486  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
100487}
100488        break;
100489      case 303: /* cmd ::= DETACH database_kw_opt expr */
100490{
100491  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
100492}
100493        break;
100494      case 308: /* cmd ::= REINDEX */
100495{sqlite3Reindex(pParse, 0, 0);}
100496        break;
100497      case 309: /* cmd ::= REINDEX nm dbnm */
100498{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100499        break;
100500      case 310: /* cmd ::= ANALYZE */
100501{sqlite3Analyze(pParse, 0, 0);}
100502        break;
100503      case 311: /* cmd ::= ANALYZE nm dbnm */
100504{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100505        break;
100506      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
100507{
100508  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
100509}
100510        break;
100511      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
100512{
100513  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
100514}
100515        break;
100516      case 314: /* add_column_fullname ::= fullname */
100517{
100518  pParse->db->lookaside.bEnabled = 0;
100519  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
100520}
100521        break;
100522      case 317: /* cmd ::= create_vtab */
100523{sqlite3VtabFinishParse(pParse,0);}
100524        break;
100525      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
100526{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
100527        break;
100528      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
100529{
100530    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
100531}
100532        break;
100533      case 322: /* vtabarg ::= */
100534{sqlite3VtabArgInit(pParse);}
100535        break;
100536      case 324: /* vtabargtoken ::= ANY */
100537      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
100538      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
100539{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
100540        break;
100541      default:
100542      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
100543      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
100544      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
100545      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
100546      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
100547      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
100548      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
100549      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
100550      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
100551      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
100552      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
100553      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
100554      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
100555      /* (44) type ::= */ yytestcase(yyruleno==44);
100556      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
100557      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
100558      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
100559      /* (54) carglist ::= */ yytestcase(yyruleno==54);
100560      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
100561      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
100562      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
100563      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
100564      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
100565      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
100566      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
100567      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
100568      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
100569      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
100570      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
100571      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
100572      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
100573      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
100574      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
100575      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
100576      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
100577      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
100578      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
100579      /* (327) anylist ::= */ yytestcase(yyruleno==327);
100580      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
100581      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
100582        break;
100583  };
100584  yygoto = yyRuleInfo[yyruleno].lhs;
100585  yysize = yyRuleInfo[yyruleno].nrhs;
100586  yypParser->yyidx -= yysize;
100587  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
100588  if( yyact < YYNSTATE ){
100589#ifdef NDEBUG
100590    /* If we are not debugging and the reduce action popped at least
100591    ** one element off the stack, then we can push the new element back
100592    ** onto the stack here, and skip the stack overflow test in yy_shift().
100593    ** That gives a significant speed improvement. */
100594    if( yysize ){
100595      yypParser->yyidx++;
100596      yymsp -= yysize-1;
100597      yymsp->stateno = (YYACTIONTYPE)yyact;
100598      yymsp->major = (YYCODETYPE)yygoto;
100599      yymsp->minor = yygotominor;
100600    }else
100601#endif
100602    {
100603      yy_shift(yypParser,yyact,yygoto,&yygotominor);
100604    }
100605  }else{
100606    assert( yyact == YYNSTATE + YYNRULE + 1 );
100607    yy_accept(yypParser);
100608  }
100609}
100610
100611/*
100612** The following code executes when the parse fails
100613*/
100614#ifndef YYNOERRORRECOVERY
100615static void yy_parse_failed(
100616  yyParser *yypParser           /* The parser */
100617){
100618  sqlite3ParserARG_FETCH;
100619#ifndef NDEBUG
100620  if( yyTraceFILE ){
100621    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
100622  }
100623#endif
100624  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100625  /* Here code is inserted which will be executed whenever the
100626  ** parser fails */
100627  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
100628}
100629#endif /* YYNOERRORRECOVERY */
100630
100631/*
100632** The following code executes when a syntax error first occurs.
100633*/
100634static void yy_syntax_error(
100635  yyParser *yypParser,           /* The parser */
100636  int yymajor,                   /* The major type of the error token */
100637  YYMINORTYPE yyminor            /* The minor type of the error token */
100638){
100639  sqlite3ParserARG_FETCH;
100640#define TOKEN (yyminor.yy0)
100641
100642  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
100643  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
100644  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
100645  pParse->parseError = 1;
100646  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
100647}
100648
100649/*
100650** The following is executed when the parser accepts
100651*/
100652static void yy_accept(
100653  yyParser *yypParser           /* The parser */
100654){
100655  sqlite3ParserARG_FETCH;
100656#ifndef NDEBUG
100657  if( yyTraceFILE ){
100658    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
100659  }
100660#endif
100661  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100662  /* Here code is inserted which will be executed whenever the
100663  ** parser accepts */
100664  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
100665}
100666
100667/* The main parser program.
100668** The first argument is a pointer to a structure obtained from
100669** "sqlite3ParserAlloc" which describes the current state of the parser.
100670** The second argument is the major token number.  The third is
100671** the minor token.  The fourth optional argument is whatever the
100672** user wants (and specified in the grammar) and is available for
100673** use by the action routines.
100674**
100675** Inputs:
100676** <ul>
100677** <li> A pointer to the parser (an opaque structure.)
100678** <li> The major token number.
100679** <li> The minor token number.
100680** <li> An option argument of a grammar-specified type.
100681** </ul>
100682**
100683** Outputs:
100684** None.
100685*/
100686SQLITE_PRIVATE void sqlite3Parser(
100687  void *yyp,                   /* The parser */
100688  int yymajor,                 /* The major token code number */
100689  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
100690  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
100691){
100692  YYMINORTYPE yyminorunion;
100693  int yyact;            /* The parser action. */
100694  int yyendofinput;     /* True if we are at the end of input */
100695#ifdef YYERRORSYMBOL
100696  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
100697#endif
100698  yyParser *yypParser;  /* The parser */
100699
100700  /* (re)initialize the parser, if necessary */
100701  yypParser = (yyParser*)yyp;
100702  if( yypParser->yyidx<0 ){
100703#if YYSTACKDEPTH<=0
100704    if( yypParser->yystksz <=0 ){
100705      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
100706      yyminorunion = yyzerominor;
100707      yyStackOverflow(yypParser, &yyminorunion);
100708      return;
100709    }
100710#endif
100711    yypParser->yyidx = 0;
100712    yypParser->yyerrcnt = -1;
100713    yypParser->yystack[0].stateno = 0;
100714    yypParser->yystack[0].major = 0;
100715  }
100716  yyminorunion.yy0 = yyminor;
100717  yyendofinput = (yymajor==0);
100718  sqlite3ParserARG_STORE;
100719
100720#ifndef NDEBUG
100721  if( yyTraceFILE ){
100722    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
100723  }
100724#endif
100725
100726  do{
100727    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
100728    if( yyact<YYNSTATE ){
100729      assert( !yyendofinput );  /* Impossible to shift the $ token */
100730      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
100731      yypParser->yyerrcnt--;
100732      yymajor = YYNOCODE;
100733    }else if( yyact < YYNSTATE + YYNRULE ){
100734      yy_reduce(yypParser,yyact-YYNSTATE);
100735    }else{
100736      assert( yyact == YY_ERROR_ACTION );
100737#ifdef YYERRORSYMBOL
100738      int yymx;
100739#endif
100740#ifndef NDEBUG
100741      if( yyTraceFILE ){
100742        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
100743      }
100744#endif
100745#ifdef YYERRORSYMBOL
100746      /* A syntax error has occurred.
100747      ** The response to an error depends upon whether or not the
100748      ** grammar defines an error token "ERROR".
100749      **
100750      ** This is what we do if the grammar does define ERROR:
100751      **
100752      **  * Call the %syntax_error function.
100753      **
100754      **  * Begin popping the stack until we enter a state where
100755      **    it is legal to shift the error symbol, then shift
100756      **    the error symbol.
100757      **
100758      **  * Set the error count to three.
100759      **
100760      **  * Begin accepting and shifting new tokens.  No new error
100761      **    processing will occur until three tokens have been
100762      **    shifted successfully.
100763      **
100764      */
100765      if( yypParser->yyerrcnt<0 ){
100766        yy_syntax_error(yypParser,yymajor,yyminorunion);
100767      }
100768      yymx = yypParser->yystack[yypParser->yyidx].major;
100769      if( yymx==YYERRORSYMBOL || yyerrorhit ){
100770#ifndef NDEBUG
100771        if( yyTraceFILE ){
100772          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
100773             yyTracePrompt,yyTokenName[yymajor]);
100774        }
100775#endif
100776        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
100777        yymajor = YYNOCODE;
100778      }else{
100779         while(
100780          yypParser->yyidx >= 0 &&
100781          yymx != YYERRORSYMBOL &&
100782          (yyact = yy_find_reduce_action(
100783                        yypParser->yystack[yypParser->yyidx].stateno,
100784                        YYERRORSYMBOL)) >= YYNSTATE
100785        ){
100786          yy_pop_parser_stack(yypParser);
100787        }
100788        if( yypParser->yyidx < 0 || yymajor==0 ){
100789          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
100790          yy_parse_failed(yypParser);
100791          yymajor = YYNOCODE;
100792        }else if( yymx!=YYERRORSYMBOL ){
100793          YYMINORTYPE u2;
100794          u2.YYERRSYMDT = 0;
100795          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
100796        }
100797      }
100798      yypParser->yyerrcnt = 3;
100799      yyerrorhit = 1;
100800#elif defined(YYNOERRORRECOVERY)
100801      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
100802      ** do any kind of error recovery.  Instead, simply invoke the syntax
100803      ** error routine and continue going as if nothing had happened.
100804      **
100805      ** Applications can set this macro (for example inside %include) if
100806      ** they intend to abandon the parse upon the first syntax error seen.
100807      */
100808      yy_syntax_error(yypParser,yymajor,yyminorunion);
100809      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
100810      yymajor = YYNOCODE;
100811
100812#else  /* YYERRORSYMBOL is not defined */
100813      /* This is what we do if the grammar does not define ERROR:
100814      **
100815      **  * Report an error message, and throw away the input token.
100816      **
100817      **  * If the input token is $, then fail the parse.
100818      **
100819      ** As before, subsequent error messages are suppressed until
100820      ** three input tokens have been successfully shifted.
100821      */
100822      if( yypParser->yyerrcnt<=0 ){
100823        yy_syntax_error(yypParser,yymajor,yyminorunion);
100824      }
100825      yypParser->yyerrcnt = 3;
100826      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
100827      if( yyendofinput ){
100828        yy_parse_failed(yypParser);
100829      }
100830      yymajor = YYNOCODE;
100831#endif
100832    }
100833  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
100834  return;
100835}
100836
100837/************** End of parse.c ***********************************************/
100838/************** Begin file tokenize.c ****************************************/
100839/*
100840** 2001 September 15
100841**
100842** The author disclaims copyright to this source code.  In place of
100843** a legal notice, here is a blessing:
100844**
100845**    May you do good and not evil.
100846**    May you find forgiveness for yourself and forgive others.
100847**    May you share freely, never taking more than you give.
100848**
100849*************************************************************************
100850** An tokenizer for SQL
100851**
100852** This file contains C code that splits an SQL input string up into
100853** individual tokens and sends those tokens one-by-one over to the
100854** parser for analysis.
100855*/
100856
100857/*
100858** The charMap() macro maps alphabetic characters into their
100859** lower-case ASCII equivalent.  On ASCII machines, this is just
100860** an upper-to-lower case map.  On EBCDIC machines we also need
100861** to adjust the encoding.  Only alphabetic characters and underscores
100862** need to be translated.
100863*/
100864#ifdef SQLITE_ASCII
100865# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
100866#endif
100867#ifdef SQLITE_EBCDIC
100868# define charMap(X) ebcdicToAscii[(unsigned char)X]
100869const unsigned char ebcdicToAscii[] = {
100870/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
100871   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
100872   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
100873   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
100874   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
100875   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
100876   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
100877   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
100878   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
100879   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
100880   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
100881   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
100882   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
100883   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
100884   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
100885   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
100886   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
100887};
100888#endif
100889
100890/*
100891** The sqlite3KeywordCode function looks up an identifier to determine if
100892** it is a keyword.  If it is a keyword, the token code of that keyword is
100893** returned.  If the input is not a keyword, TK_ID is returned.
100894**
100895** The implementation of this routine was generated by a program,
100896** mkkeywordhash.h, located in the tool subdirectory of the distribution.
100897** The output of the mkkeywordhash.c program is written into a file
100898** named keywordhash.h and then included into this source file by
100899** the #include below.
100900*/
100901/************** Include keywordhash.h in the middle of tokenize.c ************/
100902/************** Begin file keywordhash.h *************************************/
100903/***** This file contains automatically generated code ******
100904**
100905** The code in this file has been automatically generated by
100906**
100907**   sqlite/tool/mkkeywordhash.c
100908**
100909** The code in this file implements a function that determines whether
100910** or not a given identifier is really an SQL keyword.  The same thing
100911** might be implemented more directly using a hand-written hash table.
100912** But by using this automatically generated code, the size of the code
100913** is substantially reduced.  This is important for embedded applications
100914** on platforms with limited memory.
100915*/
100916/* Hash score: 175 */
100917static int keywordCode(const char *z, int n){
100918  /* zText[] encodes 811 bytes of keywords in 541 bytes */
100919  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
100920  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
100921  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
100922  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
100923  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
100924  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
100925  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
100926  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
100927  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
100928  /*   INITIALLY                                                          */
100929  static const char zText[540] = {
100930    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
100931    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
100932    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
100933    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
100934    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
100935    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
100936    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
100937    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
100938    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
100939    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
100940    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
100941    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
100942    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
100943    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
100944    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
100945    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
100946    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
100947    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
100948    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
100949    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
100950    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
100951    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
100952    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
100953    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
100954    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
100955    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
100956    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
100957    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
100958    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
100959    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
100960  };
100961  static const unsigned char aHash[127] = {
100962      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
100963      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
100964     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
100965       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
100966       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
100967      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
100968      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
100969      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
100970      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
100971      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
100972  };
100973  static const unsigned char aNext[121] = {
100974       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
100975       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
100976       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
100977       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
100978       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
100979      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
100980      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
100981       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
100982     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
100983      35,  64,   0,   0,
100984  };
100985  static const unsigned char aLen[121] = {
100986       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
100987       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
100988      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
100989       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
100990       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
100991       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
100992       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
100993       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
100994       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
100995       6,   4,   9,   3,
100996  };
100997  static const unsigned short int aOffset[121] = {
100998       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
100999      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
101000      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
101001     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
101002     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
101003     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
101004     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
101005     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
101006     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
101007     521, 527, 531, 536,
101008  };
101009  static const unsigned char aCode[121] = {
101010    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
101011    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
101012    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
101013    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
101014    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
101015    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
101016    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
101017    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
101018    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
101019    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
101020    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
101021    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
101022    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
101023    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
101024    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
101025    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
101026    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
101027    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
101028    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
101029    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
101030    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
101031    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
101032    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
101033    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
101034    TK_ALL,
101035  };
101036  int h, i;
101037  if( n<2 ) return TK_ID;
101038  h = ((charMap(z[0])*4) ^
101039      (charMap(z[n-1])*3) ^
101040      n) % 127;
101041  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
101042    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
101043      testcase( i==0 ); /* REINDEX */
101044      testcase( i==1 ); /* INDEXED */
101045      testcase( i==2 ); /* INDEX */
101046      testcase( i==3 ); /* DESC */
101047      testcase( i==4 ); /* ESCAPE */
101048      testcase( i==5 ); /* EACH */
101049      testcase( i==6 ); /* CHECK */
101050      testcase( i==7 ); /* KEY */
101051      testcase( i==8 ); /* BEFORE */
101052      testcase( i==9 ); /* FOREIGN */
101053      testcase( i==10 ); /* FOR */
101054      testcase( i==11 ); /* IGNORE */
101055      testcase( i==12 ); /* REGEXP */
101056      testcase( i==13 ); /* EXPLAIN */
101057      testcase( i==14 ); /* INSTEAD */
101058      testcase( i==15 ); /* ADD */
101059      testcase( i==16 ); /* DATABASE */
101060      testcase( i==17 ); /* AS */
101061      testcase( i==18 ); /* SELECT */
101062      testcase( i==19 ); /* TABLE */
101063      testcase( i==20 ); /* LEFT */
101064      testcase( i==21 ); /* THEN */
101065      testcase( i==22 ); /* END */
101066      testcase( i==23 ); /* DEFERRABLE */
101067      testcase( i==24 ); /* ELSE */
101068      testcase( i==25 ); /* EXCEPT */
101069      testcase( i==26 ); /* TRANSACTION */
101070      testcase( i==27 ); /* ACTION */
101071      testcase( i==28 ); /* ON */
101072      testcase( i==29 ); /* NATURAL */
101073      testcase( i==30 ); /* ALTER */
101074      testcase( i==31 ); /* RAISE */
101075      testcase( i==32 ); /* EXCLUSIVE */
101076      testcase( i==33 ); /* EXISTS */
101077      testcase( i==34 ); /* SAVEPOINT */
101078      testcase( i==35 ); /* INTERSECT */
101079      testcase( i==36 ); /* TRIGGER */
101080      testcase( i==37 ); /* REFERENCES */
101081      testcase( i==38 ); /* CONSTRAINT */
101082      testcase( i==39 ); /* INTO */
101083      testcase( i==40 ); /* OFFSET */
101084      testcase( i==41 ); /* OF */
101085      testcase( i==42 ); /* SET */
101086      testcase( i==43 ); /* TEMPORARY */
101087      testcase( i==44 ); /* TEMP */
101088      testcase( i==45 ); /* OR */
101089      testcase( i==46 ); /* UNIQUE */
101090      testcase( i==47 ); /* QUERY */
101091      testcase( i==48 ); /* ATTACH */
101092      testcase( i==49 ); /* HAVING */
101093      testcase( i==50 ); /* GROUP */
101094      testcase( i==51 ); /* UPDATE */
101095      testcase( i==52 ); /* BEGIN */
101096      testcase( i==53 ); /* INNER */
101097      testcase( i==54 ); /* RELEASE */
101098      testcase( i==55 ); /* BETWEEN */
101099      testcase( i==56 ); /* NOTNULL */
101100      testcase( i==57 ); /* NOT */
101101      testcase( i==58 ); /* NO */
101102      testcase( i==59 ); /* NULL */
101103      testcase( i==60 ); /* LIKE */
101104      testcase( i==61 ); /* CASCADE */
101105      testcase( i==62 ); /* ASC */
101106      testcase( i==63 ); /* DELETE */
101107      testcase( i==64 ); /* CASE */
101108      testcase( i==65 ); /* COLLATE */
101109      testcase( i==66 ); /* CREATE */
101110      testcase( i==67 ); /* CURRENT_DATE */
101111      testcase( i==68 ); /* DETACH */
101112      testcase( i==69 ); /* IMMEDIATE */
101113      testcase( i==70 ); /* JOIN */
101114      testcase( i==71 ); /* INSERT */
101115      testcase( i==72 ); /* MATCH */
101116      testcase( i==73 ); /* PLAN */
101117      testcase( i==74 ); /* ANALYZE */
101118      testcase( i==75 ); /* PRAGMA */
101119      testcase( i==76 ); /* ABORT */
101120      testcase( i==77 ); /* VALUES */
101121      testcase( i==78 ); /* VIRTUAL */
101122      testcase( i==79 ); /* LIMIT */
101123      testcase( i==80 ); /* WHEN */
101124      testcase( i==81 ); /* WHERE */
101125      testcase( i==82 ); /* RENAME */
101126      testcase( i==83 ); /* AFTER */
101127      testcase( i==84 ); /* REPLACE */
101128      testcase( i==85 ); /* AND */
101129      testcase( i==86 ); /* DEFAULT */
101130      testcase( i==87 ); /* AUTOINCREMENT */
101131      testcase( i==88 ); /* TO */
101132      testcase( i==89 ); /* IN */
101133      testcase( i==90 ); /* CAST */
101134      testcase( i==91 ); /* COLUMN */
101135      testcase( i==92 ); /* COMMIT */
101136      testcase( i==93 ); /* CONFLICT */
101137      testcase( i==94 ); /* CROSS */
101138      testcase( i==95 ); /* CURRENT_TIMESTAMP */
101139      testcase( i==96 ); /* CURRENT_TIME */
101140      testcase( i==97 ); /* PRIMARY */
101141      testcase( i==98 ); /* DEFERRED */
101142      testcase( i==99 ); /* DISTINCT */
101143      testcase( i==100 ); /* IS */
101144      testcase( i==101 ); /* DROP */
101145      testcase( i==102 ); /* FAIL */
101146      testcase( i==103 ); /* FROM */
101147      testcase( i==104 ); /* FULL */
101148      testcase( i==105 ); /* GLOB */
101149      testcase( i==106 ); /* BY */
101150      testcase( i==107 ); /* IF */
101151      testcase( i==108 ); /* ISNULL */
101152      testcase( i==109 ); /* ORDER */
101153      testcase( i==110 ); /* RESTRICT */
101154      testcase( i==111 ); /* OUTER */
101155      testcase( i==112 ); /* RIGHT */
101156      testcase( i==113 ); /* ROLLBACK */
101157      testcase( i==114 ); /* ROW */
101158      testcase( i==115 ); /* UNION */
101159      testcase( i==116 ); /* USING */
101160      testcase( i==117 ); /* VACUUM */
101161      testcase( i==118 ); /* VIEW */
101162      testcase( i==119 ); /* INITIALLY */
101163      testcase( i==120 ); /* ALL */
101164      return aCode[i];
101165    }
101166  }
101167  return TK_ID;
101168}
101169SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
101170  return keywordCode((char*)z, n);
101171}
101172#define SQLITE_N_KEYWORD 121
101173
101174/************** End of keywordhash.h *****************************************/
101175/************** Continuing where we left off in tokenize.c *******************/
101176
101177
101178/*
101179** If X is a character that can be used in an identifier then
101180** IdChar(X) will be true.  Otherwise it is false.
101181**
101182** For ASCII, any character with the high-order bit set is
101183** allowed in an identifier.  For 7-bit characters,
101184** sqlite3IsIdChar[X] must be 1.
101185**
101186** For EBCDIC, the rules are more complex but have the same
101187** end result.
101188**
101189** Ticket #1066.  the SQL standard does not allow '$' in the
101190** middle of identfiers.  But many SQL implementations do.
101191** SQLite will allow '$' in identifiers for compatibility.
101192** But the feature is undocumented.
101193*/
101194#ifdef SQLITE_ASCII
101195#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
101196#endif
101197#ifdef SQLITE_EBCDIC
101198SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
101199/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
101200    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
101201    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
101202    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
101203    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
101204    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
101205    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
101206    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
101207    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
101208    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
101209    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
101210    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
101211    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
101212};
101213#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
101214#endif
101215
101216
101217/*
101218** Return the length of the token that begins at z[0].
101219** Store the token type in *tokenType before returning.
101220*/
101221SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
101222  int i, c;
101223  switch( *z ){
101224    case ' ': case '\t': case '\n': case '\f': case '\r': {
101225      testcase( z[0]==' ' );
101226      testcase( z[0]=='\t' );
101227      testcase( z[0]=='\n' );
101228      testcase( z[0]=='\f' );
101229      testcase( z[0]=='\r' );
101230      for(i=1; sqlite3Isspace(z[i]); i++){}
101231      *tokenType = TK_SPACE;
101232      return i;
101233    }
101234    case '-': {
101235      if( z[1]=='-' ){
101236        /* IMP: R-15891-05542 -- syntax diagram for comments */
101237        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
101238        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101239        return i;
101240      }
101241      *tokenType = TK_MINUS;
101242      return 1;
101243    }
101244    case '(': {
101245      *tokenType = TK_LP;
101246      return 1;
101247    }
101248    case ')': {
101249      *tokenType = TK_RP;
101250      return 1;
101251    }
101252    case ';': {
101253      *tokenType = TK_SEMI;
101254      return 1;
101255    }
101256    case '+': {
101257      *tokenType = TK_PLUS;
101258      return 1;
101259    }
101260    case '*': {
101261      *tokenType = TK_STAR;
101262      return 1;
101263    }
101264    case '/': {
101265      if( z[1]!='*' || z[2]==0 ){
101266        *tokenType = TK_SLASH;
101267        return 1;
101268      }
101269      /* IMP: R-15891-05542 -- syntax diagram for comments */
101270      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
101271      if( c ) i++;
101272      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101273      return i;
101274    }
101275    case '%': {
101276      *tokenType = TK_REM;
101277      return 1;
101278    }
101279    case '=': {
101280      *tokenType = TK_EQ;
101281      return 1 + (z[1]=='=');
101282    }
101283    case '<': {
101284      if( (c=z[1])=='=' ){
101285        *tokenType = TK_LE;
101286        return 2;
101287      }else if( c=='>' ){
101288        *tokenType = TK_NE;
101289        return 2;
101290      }else if( c=='<' ){
101291        *tokenType = TK_LSHIFT;
101292        return 2;
101293      }else{
101294        *tokenType = TK_LT;
101295        return 1;
101296      }
101297    }
101298    case '>': {
101299      if( (c=z[1])=='=' ){
101300        *tokenType = TK_GE;
101301        return 2;
101302      }else if( c=='>' ){
101303        *tokenType = TK_RSHIFT;
101304        return 2;
101305      }else{
101306        *tokenType = TK_GT;
101307        return 1;
101308      }
101309    }
101310    case '!': {
101311      if( z[1]!='=' ){
101312        *tokenType = TK_ILLEGAL;
101313        return 2;
101314      }else{
101315        *tokenType = TK_NE;
101316        return 2;
101317      }
101318    }
101319    case '|': {
101320      if( z[1]!='|' ){
101321        *tokenType = TK_BITOR;
101322        return 1;
101323      }else{
101324        *tokenType = TK_CONCAT;
101325        return 2;
101326      }
101327    }
101328    case ',': {
101329      *tokenType = TK_COMMA;
101330      return 1;
101331    }
101332    case '&': {
101333      *tokenType = TK_BITAND;
101334      return 1;
101335    }
101336    case '~': {
101337      *tokenType = TK_BITNOT;
101338      return 1;
101339    }
101340    case '`':
101341    case '\'':
101342    case '"': {
101343      int delim = z[0];
101344      testcase( delim=='`' );
101345      testcase( delim=='\'' );
101346      testcase( delim=='"' );
101347      for(i=1; (c=z[i])!=0; i++){
101348        if( c==delim ){
101349          if( z[i+1]==delim ){
101350            i++;
101351          }else{
101352            break;
101353          }
101354        }
101355      }
101356      if( c=='\'' ){
101357        *tokenType = TK_STRING;
101358        return i+1;
101359      }else if( c!=0 ){
101360        *tokenType = TK_ID;
101361        return i+1;
101362      }else{
101363        *tokenType = TK_ILLEGAL;
101364        return i;
101365      }
101366    }
101367    case '.': {
101368#ifndef SQLITE_OMIT_FLOATING_POINT
101369      if( !sqlite3Isdigit(z[1]) )
101370#endif
101371      {
101372        *tokenType = TK_DOT;
101373        return 1;
101374      }
101375      /* If the next character is a digit, this is a floating point
101376      ** number that begins with ".".  Fall thru into the next case */
101377    }
101378    case '0': case '1': case '2': case '3': case '4':
101379    case '5': case '6': case '7': case '8': case '9': {
101380      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
101381      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
101382      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
101383      testcase( z[0]=='9' );
101384      *tokenType = TK_INTEGER;
101385      for(i=0; sqlite3Isdigit(z[i]); i++){}
101386#ifndef SQLITE_OMIT_FLOATING_POINT
101387      if( z[i]=='.' ){
101388        i++;
101389        while( sqlite3Isdigit(z[i]) ){ i++; }
101390        *tokenType = TK_FLOAT;
101391      }
101392      if( (z[i]=='e' || z[i]=='E') &&
101393           ( sqlite3Isdigit(z[i+1])
101394            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
101395           )
101396      ){
101397        i += 2;
101398        while( sqlite3Isdigit(z[i]) ){ i++; }
101399        *tokenType = TK_FLOAT;
101400      }
101401#endif
101402      while( IdChar(z[i]) ){
101403        *tokenType = TK_ILLEGAL;
101404        i++;
101405      }
101406      return i;
101407    }
101408    case '[': {
101409      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
101410      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
101411      return i;
101412    }
101413    case '?': {
101414      *tokenType = TK_VARIABLE;
101415      for(i=1; sqlite3Isdigit(z[i]); i++){}
101416      return i;
101417    }
101418    case '#': {
101419      for(i=1; sqlite3Isdigit(z[i]); i++){}
101420      if( i>1 ){
101421        /* Parameters of the form #NNN (where NNN is a number) are used
101422        ** internally by sqlite3NestedParse.  */
101423        *tokenType = TK_REGISTER;
101424        return i;
101425      }
101426      /* Fall through into the next case if the '#' is not followed by
101427      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
101428    }
101429#ifndef SQLITE_OMIT_TCL_VARIABLE
101430    case '$':
101431#endif
101432    case '@':  /* For compatibility with MS SQL Server */
101433    case ':': {
101434      int n = 0;
101435      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
101436      *tokenType = TK_VARIABLE;
101437      for(i=1; (c=z[i])!=0; i++){
101438        if( IdChar(c) ){
101439          n++;
101440#ifndef SQLITE_OMIT_TCL_VARIABLE
101441        }else if( c=='(' && n>0 ){
101442          do{
101443            i++;
101444          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
101445          if( c==')' ){
101446            i++;
101447          }else{
101448            *tokenType = TK_ILLEGAL;
101449          }
101450          break;
101451        }else if( c==':' && z[i+1]==':' ){
101452          i++;
101453#endif
101454        }else{
101455          break;
101456        }
101457      }
101458      if( n==0 ) *tokenType = TK_ILLEGAL;
101459      return i;
101460    }
101461#ifndef SQLITE_OMIT_BLOB_LITERAL
101462    case 'x': case 'X': {
101463      testcase( z[0]=='x' ); testcase( z[0]=='X' );
101464      if( z[1]=='\'' ){
101465        *tokenType = TK_BLOB;
101466        for(i=2; (c=z[i])!=0 && c!='\''; i++){
101467          if( !sqlite3Isxdigit(c) ){
101468            *tokenType = TK_ILLEGAL;
101469          }
101470        }
101471        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
101472        if( c ) i++;
101473        return i;
101474      }
101475      /* Otherwise fall through to the next case */
101476    }
101477#endif
101478    default: {
101479      if( !IdChar(*z) ){
101480        break;
101481      }
101482      for(i=1; IdChar(z[i]); i++){}
101483      *tokenType = keywordCode((char*)z, i);
101484      return i;
101485    }
101486  }
101487  *tokenType = TK_ILLEGAL;
101488  return 1;
101489}
101490
101491/*
101492** Run the parser on the given SQL string.  The parser structure is
101493** passed in.  An SQLITE_ status code is returned.  If an error occurs
101494** then an and attempt is made to write an error message into
101495** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
101496** error message.
101497*/
101498SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
101499  int nErr = 0;                   /* Number of errors encountered */
101500  int i;                          /* Loop counter */
101501  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
101502  int tokenType;                  /* type of the next token */
101503  int lastTokenParsed = -1;       /* type of the previous token */
101504  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
101505  sqlite3 *db = pParse->db;       /* The database connection */
101506  int mxSqlLen;                   /* Max length of an SQL string */
101507
101508
101509  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
101510  if( db->activeVdbeCnt==0 ){
101511    db->u1.isInterrupted = 0;
101512  }
101513  pParse->rc = SQLITE_OK;
101514  pParse->zTail = zSql;
101515  i = 0;
101516  assert( pzErrMsg!=0 );
101517  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
101518  if( pEngine==0 ){
101519    db->mallocFailed = 1;
101520    return SQLITE_NOMEM;
101521  }
101522  assert( pParse->pNewTable==0 );
101523  assert( pParse->pNewTrigger==0 );
101524  assert( pParse->nVar==0 );
101525  assert( pParse->nVarExpr==0 );
101526  assert( pParse->nVarExprAlloc==0 );
101527  assert( pParse->apVarExpr==0 );
101528  enableLookaside = db->lookaside.bEnabled;
101529  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
101530  while( !db->mallocFailed && zSql[i]!=0 ){
101531    assert( i>=0 );
101532    pParse->sLastToken.z = &zSql[i];
101533    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
101534    i += pParse->sLastToken.n;
101535    if( i>mxSqlLen ){
101536      pParse->rc = SQLITE_TOOBIG;
101537      break;
101538    }
101539    switch( tokenType ){
101540      case TK_SPACE: {
101541        if( db->u1.isInterrupted ){
101542          sqlite3ErrorMsg(pParse, "interrupt");
101543          pParse->rc = SQLITE_INTERRUPT;
101544          goto abort_parse;
101545        }
101546        break;
101547      }
101548      case TK_ILLEGAL: {
101549        sqlite3DbFree(db, *pzErrMsg);
101550        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
101551                        &pParse->sLastToken);
101552        nErr++;
101553        goto abort_parse;
101554      }
101555      case TK_SEMI: {
101556        pParse->zTail = &zSql[i];
101557        /* Fall thru into the default case */
101558      }
101559      default: {
101560        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
101561        lastTokenParsed = tokenType;
101562        if( pParse->rc!=SQLITE_OK ){
101563          goto abort_parse;
101564        }
101565        break;
101566      }
101567    }
101568  }
101569abort_parse:
101570  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
101571    if( lastTokenParsed!=TK_SEMI ){
101572      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
101573      pParse->zTail = &zSql[i];
101574    }
101575    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
101576  }
101577#ifdef YYTRACKMAXSTACKDEPTH
101578  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
101579      sqlite3ParserStackPeak(pEngine)
101580  );
101581#endif /* YYDEBUG */
101582  sqlite3ParserFree(pEngine, sqlite3_free);
101583  db->lookaside.bEnabled = enableLookaside;
101584  if( db->mallocFailed ){
101585    pParse->rc = SQLITE_NOMEM;
101586  }
101587  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
101588    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
101589  }
101590  assert( pzErrMsg!=0 );
101591  if( pParse->zErrMsg ){
101592    *pzErrMsg = pParse->zErrMsg;
101593    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
101594    pParse->zErrMsg = 0;
101595    nErr++;
101596  }
101597  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
101598    sqlite3VdbeDelete(pParse->pVdbe);
101599    pParse->pVdbe = 0;
101600  }
101601#ifndef SQLITE_OMIT_SHARED_CACHE
101602  if( pParse->nested==0 ){
101603    sqlite3DbFree(db, pParse->aTableLock);
101604    pParse->aTableLock = 0;
101605    pParse->nTableLock = 0;
101606  }
101607#endif
101608#ifndef SQLITE_OMIT_VIRTUALTABLE
101609  sqlite3DbFree(db, pParse->apVtabLock);
101610#endif
101611
101612  if( !IN_DECLARE_VTAB ){
101613    /* If the pParse->declareVtab flag is set, do not delete any table
101614    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
101615    ** will take responsibility for freeing the Table structure.
101616    */
101617    sqlite3DeleteTable(pParse->pNewTable);
101618  }
101619
101620  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
101621  sqlite3DbFree(db, pParse->apVarExpr);
101622  sqlite3DbFree(db, pParse->aAlias);
101623  while( pParse->pAinc ){
101624    AutoincInfo *p = pParse->pAinc;
101625    pParse->pAinc = p->pNext;
101626    sqlite3DbFree(db, p);
101627  }
101628  while( pParse->pZombieTab ){
101629    Table *p = pParse->pZombieTab;
101630    pParse->pZombieTab = p->pNextZombie;
101631    sqlite3DeleteTable(p);
101632  }
101633  if( nErr>0 && pParse->rc==SQLITE_OK ){
101634    pParse->rc = SQLITE_ERROR;
101635  }
101636  return nErr;
101637}
101638
101639/************** End of tokenize.c ********************************************/
101640/************** Begin file complete.c ****************************************/
101641/*
101642** 2001 September 15
101643**
101644** The author disclaims copyright to this source code.  In place of
101645** a legal notice, here is a blessing:
101646**
101647**    May you do good and not evil.
101648**    May you find forgiveness for yourself and forgive others.
101649**    May you share freely, never taking more than you give.
101650**
101651*************************************************************************
101652** An tokenizer for SQL
101653**
101654** This file contains C code that implements the sqlite3_complete() API.
101655** This code used to be part of the tokenizer.c source file.  But by
101656** separating it out, the code will be automatically omitted from
101657** static links that do not use it.
101658*/
101659#ifndef SQLITE_OMIT_COMPLETE
101660
101661/*
101662** This is defined in tokenize.c.  We just have to import the definition.
101663*/
101664#ifndef SQLITE_AMALGAMATION
101665#ifdef SQLITE_ASCII
101666#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
101667#endif
101668#ifdef SQLITE_EBCDIC
101669SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
101670#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
101671#endif
101672#endif /* SQLITE_AMALGAMATION */
101673
101674
101675/*
101676** Token types used by the sqlite3_complete() routine.  See the header
101677** comments on that procedure for additional information.
101678*/
101679#define tkSEMI    0
101680#define tkWS      1
101681#define tkOTHER   2
101682#ifndef SQLITE_OMIT_TRIGGER
101683#define tkEXPLAIN 3
101684#define tkCREATE  4
101685#define tkTEMP    5
101686#define tkTRIGGER 6
101687#define tkEND     7
101688#endif
101689
101690/*
101691** Return TRUE if the given SQL string ends in a semicolon.
101692**
101693** Special handling is require for CREATE TRIGGER statements.
101694** Whenever the CREATE TRIGGER keywords are seen, the statement
101695** must end with ";END;".
101696**
101697** This implementation uses a state machine with 8 states:
101698**
101699**   (0) INVALID   We have not yet seen a non-whitespace character.
101700**
101701**   (1) START     At the beginning or end of an SQL statement.  This routine
101702**                 returns 1 if it ends in the START state and 0 if it ends
101703**                 in any other state.
101704**
101705**   (2) NORMAL    We are in the middle of statement which ends with a single
101706**                 semicolon.
101707**
101708**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
101709**                 a statement.
101710**
101711**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
101712**                 statement, possibly preceeded by EXPLAIN and/or followed by
101713**                 TEMP or TEMPORARY
101714**
101715**   (5) TRIGGER   We are in the middle of a trigger definition that must be
101716**                 ended by a semicolon, the keyword END, and another semicolon.
101717**
101718**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
101719**                 the end of a trigger definition.
101720**
101721**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
101722**                 of a trigger difinition.
101723**
101724** Transitions between states above are determined by tokens extracted
101725** from the input.  The following tokens are significant:
101726**
101727**   (0) tkSEMI      A semicolon.
101728**   (1) tkWS        Whitespace.
101729**   (2) tkOTHER     Any other SQL token.
101730**   (3) tkEXPLAIN   The "explain" keyword.
101731**   (4) tkCREATE    The "create" keyword.
101732**   (5) tkTEMP      The "temp" or "temporary" keyword.
101733**   (6) tkTRIGGER   The "trigger" keyword.
101734**   (7) tkEND       The "end" keyword.
101735**
101736** Whitespace never causes a state transition and is always ignored.
101737** This means that a SQL string of all whitespace is invalid.
101738**
101739** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
101740** to recognize the end of a trigger can be omitted.  All we have to do
101741** is look for a semicolon that is not part of an string or comment.
101742*/
101743SQLITE_API int sqlite3_complete(const char *zSql){
101744  u8 state = 0;   /* Current state, using numbers defined in header comment */
101745  u8 token;       /* Value of the next token */
101746
101747#ifndef SQLITE_OMIT_TRIGGER
101748  /* A complex statement machine used to detect the end of a CREATE TRIGGER
101749  ** statement.  This is the normal case.
101750  */
101751  static const u8 trans[8][8] = {
101752                     /* Token:                                                */
101753     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
101754     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
101755     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
101756     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
101757     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
101758     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
101759     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
101760     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
101761     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
101762  };
101763#else
101764  /* If triggers are not supported by this compile then the statement machine
101765  ** used to detect the end of a statement is much simplier
101766  */
101767  static const u8 trans[3][3] = {
101768                     /* Token:           */
101769     /* State:       **  SEMI  WS  OTHER */
101770     /* 0 INVALID: */ {    1,  0,     2, },
101771     /* 1   START: */ {    1,  1,     2, },
101772     /* 2  NORMAL: */ {    1,  2,     2, },
101773  };
101774#endif /* SQLITE_OMIT_TRIGGER */
101775
101776  while( *zSql ){
101777    switch( *zSql ){
101778      case ';': {  /* A semicolon */
101779        token = tkSEMI;
101780        break;
101781      }
101782      case ' ':
101783      case '\r':
101784      case '\t':
101785      case '\n':
101786      case '\f': {  /* White space is ignored */
101787        token = tkWS;
101788        break;
101789      }
101790      case '/': {   /* C-style comments */
101791        if( zSql[1]!='*' ){
101792          token = tkOTHER;
101793          break;
101794        }
101795        zSql += 2;
101796        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
101797        if( zSql[0]==0 ) return 0;
101798        zSql++;
101799        token = tkWS;
101800        break;
101801      }
101802      case '-': {   /* SQL-style comments from "--" to end of line */
101803        if( zSql[1]!='-' ){
101804          token = tkOTHER;
101805          break;
101806        }
101807        while( *zSql && *zSql!='\n' ){ zSql++; }
101808        if( *zSql==0 ) return state==1;
101809        token = tkWS;
101810        break;
101811      }
101812      case '[': {   /* Microsoft-style identifiers in [...] */
101813        zSql++;
101814        while( *zSql && *zSql!=']' ){ zSql++; }
101815        if( *zSql==0 ) return 0;
101816        token = tkOTHER;
101817        break;
101818      }
101819      case '`':     /* Grave-accent quoted symbols used by MySQL */
101820      case '"':     /* single- and double-quoted strings */
101821      case '\'': {
101822        int c = *zSql;
101823        zSql++;
101824        while( *zSql && *zSql!=c ){ zSql++; }
101825        if( *zSql==0 ) return 0;
101826        token = tkOTHER;
101827        break;
101828      }
101829      default: {
101830#ifdef SQLITE_EBCDIC
101831        unsigned char c;
101832#endif
101833        if( IdChar((u8)*zSql) ){
101834          /* Keywords and unquoted identifiers */
101835          int nId;
101836          for(nId=1; IdChar(zSql[nId]); nId++){}
101837#ifdef SQLITE_OMIT_TRIGGER
101838          token = tkOTHER;
101839#else
101840          switch( *zSql ){
101841            case 'c': case 'C': {
101842              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
101843                token = tkCREATE;
101844              }else{
101845                token = tkOTHER;
101846              }
101847              break;
101848            }
101849            case 't': case 'T': {
101850              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
101851                token = tkTRIGGER;
101852              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
101853                token = tkTEMP;
101854              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
101855                token = tkTEMP;
101856              }else{
101857                token = tkOTHER;
101858              }
101859              break;
101860            }
101861            case 'e':  case 'E': {
101862              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
101863                token = tkEND;
101864              }else
101865#ifndef SQLITE_OMIT_EXPLAIN
101866              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
101867                token = tkEXPLAIN;
101868              }else
101869#endif
101870              {
101871                token = tkOTHER;
101872              }
101873              break;
101874            }
101875            default: {
101876              token = tkOTHER;
101877              break;
101878            }
101879          }
101880#endif /* SQLITE_OMIT_TRIGGER */
101881          zSql += nId-1;
101882        }else{
101883          /* Operators and special symbols */
101884          token = tkOTHER;
101885        }
101886        break;
101887      }
101888    }
101889    state = trans[state][token];
101890    zSql++;
101891  }
101892  return state==1;
101893}
101894
101895#ifndef SQLITE_OMIT_UTF16
101896/*
101897** This routine is the same as the sqlite3_complete() routine described
101898** above, except that the parameter is required to be UTF-16 encoded, not
101899** UTF-8.
101900*/
101901SQLITE_API int sqlite3_complete16(const void *zSql){
101902  sqlite3_value *pVal;
101903  char const *zSql8;
101904  int rc = SQLITE_NOMEM;
101905
101906#ifndef SQLITE_OMIT_AUTOINIT
101907  rc = sqlite3_initialize();
101908  if( rc ) return rc;
101909#endif
101910  pVal = sqlite3ValueNew(0);
101911  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
101912  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
101913  if( zSql8 ){
101914    rc = sqlite3_complete(zSql8);
101915  }else{
101916    rc = SQLITE_NOMEM;
101917  }
101918  sqlite3ValueFree(pVal);
101919  return sqlite3ApiExit(0, rc);
101920}
101921#endif /* SQLITE_OMIT_UTF16 */
101922#endif /* SQLITE_OMIT_COMPLETE */
101923
101924/************** End of complete.c ********************************************/
101925/************** Begin file main.c ********************************************/
101926/*
101927** 2001 September 15
101928**
101929** The author disclaims copyright to this source code.  In place of
101930** a legal notice, here is a blessing:
101931**
101932**    May you do good and not evil.
101933**    May you find forgiveness for yourself and forgive others.
101934**    May you share freely, never taking more than you give.
101935**
101936*************************************************************************
101937** Main file for the SQLite library.  The routines in this file
101938** implement the programmer interface to the library.  Routines in
101939** other files are for internal use by SQLite and should not be
101940** accessed by users of the library.
101941*/
101942
101943#ifdef SQLITE_ENABLE_FTS3
101944/************** Include fts3.h in the middle of main.c ***********************/
101945/************** Begin file fts3.h ********************************************/
101946/*
101947** 2006 Oct 10
101948**
101949** The author disclaims copyright to this source code.  In place of
101950** a legal notice, here is a blessing:
101951**
101952**    May you do good and not evil.
101953**    May you find forgiveness for yourself and forgive others.
101954**    May you share freely, never taking more than you give.
101955**
101956******************************************************************************
101957**
101958** This header file is used by programs that want to link against the
101959** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
101960*/
101961
101962#if 0
101963extern "C" {
101964#endif  /* __cplusplus */
101965
101966SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs); // Android Change
101967
101968#if 0
101969}  /* extern "C" */
101970#endif  /* __cplusplus */
101971
101972/************** End of fts3.h ************************************************/
101973/************** Continuing where we left off in main.c ***********************/
101974#endif
101975#ifdef SQLITE_ENABLE_RTREE
101976/************** Include rtree.h in the middle of main.c **********************/
101977/************** Begin file rtree.h *******************************************/
101978/*
101979** 2008 May 26
101980**
101981** The author disclaims copyright to this source code.  In place of
101982** a legal notice, here is a blessing:
101983**
101984**    May you do good and not evil.
101985**    May you find forgiveness for yourself and forgive others.
101986**    May you share freely, never taking more than you give.
101987**
101988******************************************************************************
101989**
101990** This header file is used by programs that want to link against the
101991** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
101992*/
101993
101994#if 0
101995extern "C" {
101996#endif  /* __cplusplus */
101997
101998SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
101999
102000#if 0
102001}  /* extern "C" */
102002#endif  /* __cplusplus */
102003
102004/************** End of rtree.h ***********************************************/
102005/************** Continuing where we left off in main.c ***********************/
102006#endif
102007#ifdef SQLITE_ENABLE_ICU
102008/************** Include sqliteicu.h in the middle of main.c ******************/
102009/************** Begin file sqliteicu.h ***************************************/
102010/*
102011** 2008 May 26
102012**
102013** The author disclaims copyright to this source code.  In place of
102014** a legal notice, here is a blessing:
102015**
102016**    May you do good and not evil.
102017**    May you find forgiveness for yourself and forgive others.
102018**    May you share freely, never taking more than you give.
102019**
102020******************************************************************************
102021**
102022** This header file is used by programs that want to link against the
102023** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
102024*/
102025
102026#if 0
102027extern "C" {
102028#endif  /* __cplusplus */
102029
102030SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
102031
102032#if 0
102033}  /* extern "C" */
102034#endif  /* __cplusplus */
102035
102036
102037/************** End of sqliteicu.h *******************************************/
102038/************** Continuing where we left off in main.c ***********************/
102039#endif
102040
102041/*
102042** The version of the library
102043*/
102044#ifndef SQLITE_AMALGAMATION
102045SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
102046#endif
102047SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
102048SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
102049SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
102050SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
102051
102052#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
102053/*
102054** If the following function pointer is not NULL and if
102055** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
102056** I/O active are written using this function.  These messages
102057** are intended for debugging activity only.
102058*/
102059SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
102060#endif
102061
102062/*
102063** If the following global variable points to a string which is the
102064** name of a directory, then that directory will be used to store
102065** temporary files.
102066**
102067** See also the "PRAGMA temp_store_directory" SQL command.
102068*/
102069SQLITE_API char *sqlite3_temp_directory = 0;
102070
102071/*
102072** Initialize SQLite.
102073**
102074** This routine must be called to initialize the memory allocation,
102075** VFS, and mutex subsystems prior to doing any serious work with
102076** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
102077** this routine will be called automatically by key routines such as
102078** sqlite3_open().
102079**
102080** This routine is a no-op except on its very first call for the process,
102081** or for the first call after a call to sqlite3_shutdown.
102082**
102083** The first thread to call this routine runs the initialization to
102084** completion.  If subsequent threads call this routine before the first
102085** thread has finished the initialization process, then the subsequent
102086** threads must block until the first thread finishes with the initialization.
102087**
102088** The first thread might call this routine recursively.  Recursive
102089** calls to this routine should not block, of course.  Otherwise the
102090** initialization process would never complete.
102091**
102092** Let X be the first thread to enter this routine.  Let Y be some other
102093** thread.  Then while the initial invocation of this routine by X is
102094** incomplete, it is required that:
102095**
102096**    *  Calls to this routine from Y must block until the outer-most
102097**       call by X completes.
102098**
102099**    *  Recursive calls to this routine from thread X return immediately
102100**       without blocking.
102101*/
102102SQLITE_API int sqlite3_initialize(void){
102103  sqlite3_mutex *pMaster;                      /* The main static mutex */
102104  int rc;                                      /* Result code */
102105
102106#ifdef SQLITE_OMIT_WSD
102107  rc = sqlite3_wsd_init(4096, 24);
102108  if( rc!=SQLITE_OK ){
102109    return rc;
102110  }
102111#endif
102112
102113  /* If SQLite is already completely initialized, then this call
102114  ** to sqlite3_initialize() should be a no-op.  But the initialization
102115  ** must be complete.  So isInit must not be set until the very end
102116  ** of this routine.
102117  */
102118  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
102119
102120  /* Make sure the mutex subsystem is initialized.  If unable to
102121  ** initialize the mutex subsystem, return early with the error.
102122  ** If the system is so sick that we are unable to allocate a mutex,
102123  ** there is not much SQLite is going to be able to do.
102124  **
102125  ** The mutex subsystem must take care of serializing its own
102126  ** initialization.
102127  */
102128  rc = sqlite3MutexInit();
102129  if( rc ) return rc;
102130
102131  /* Initialize the malloc() system and the recursive pInitMutex mutex.
102132  ** This operation is protected by the STATIC_MASTER mutex.  Note that
102133  ** MutexAlloc() is called for a static mutex prior to initializing the
102134  ** malloc subsystem - this implies that the allocation of a static
102135  ** mutex must not require support from the malloc subsystem.
102136  */
102137  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102138  sqlite3_mutex_enter(pMaster);
102139  sqlite3GlobalConfig.isMutexInit = 1;
102140  if( !sqlite3GlobalConfig.isMallocInit ){
102141    rc = sqlite3MallocInit();
102142  }
102143  if( rc==SQLITE_OK ){
102144    sqlite3GlobalConfig.isMallocInit = 1;
102145    if( !sqlite3GlobalConfig.pInitMutex ){
102146      sqlite3GlobalConfig.pInitMutex =
102147           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
102148      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
102149        rc = SQLITE_NOMEM;
102150      }
102151    }
102152  }
102153  if( rc==SQLITE_OK ){
102154    sqlite3GlobalConfig.nRefInitMutex++;
102155  }
102156  sqlite3_mutex_leave(pMaster);
102157
102158  /* If rc is not SQLITE_OK at this point, then either the malloc
102159  ** subsystem could not be initialized or the system failed to allocate
102160  ** the pInitMutex mutex. Return an error in either case.  */
102161  if( rc!=SQLITE_OK ){
102162    return rc;
102163  }
102164
102165  /* Do the rest of the initialization under the recursive mutex so
102166  ** that we will be able to handle recursive calls into
102167  ** sqlite3_initialize().  The recursive calls normally come through
102168  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
102169  ** recursive calls might also be possible.
102170  */
102171  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
102172  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
102173    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
102174    sqlite3GlobalConfig.inProgress = 1;
102175    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
102176    sqlite3RegisterGlobalFunctions();
102177    if( sqlite3GlobalConfig.isPCacheInit==0 ){
102178      rc = sqlite3PcacheInitialize();
102179    }
102180    if( rc==SQLITE_OK ){
102181      sqlite3GlobalConfig.isPCacheInit = 1;
102182      rc = sqlite3OsInit();
102183    }
102184    if( rc==SQLITE_OK ){
102185      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
102186          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
102187      sqlite3GlobalConfig.isInit = 1;
102188    }
102189    sqlite3GlobalConfig.inProgress = 0;
102190  }
102191  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
102192
102193  /* Go back under the static mutex and clean up the recursive
102194  ** mutex to prevent a resource leak.
102195  */
102196  sqlite3_mutex_enter(pMaster);
102197  sqlite3GlobalConfig.nRefInitMutex--;
102198  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
102199    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
102200    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
102201    sqlite3GlobalConfig.pInitMutex = 0;
102202  }
102203  sqlite3_mutex_leave(pMaster);
102204
102205  /* The following is just a sanity check to make sure SQLite has
102206  ** been compiled correctly.  It is important to run this code, but
102207  ** we don't want to run it too often and soak up CPU cycles for no
102208  ** reason.  So we run it once during initialization.
102209  */
102210#ifndef NDEBUG
102211#ifndef SQLITE_OMIT_FLOATING_POINT
102212  /* This section of code's only "output" is via assert() statements. */
102213  if ( rc==SQLITE_OK ){
102214    u64 x = (((u64)1)<<63)-1;
102215    double y;
102216    assert(sizeof(x)==8);
102217    assert(sizeof(x)==sizeof(y));
102218    memcpy(&y, &x, 8);
102219    assert( sqlite3IsNaN(y) );
102220  }
102221#endif
102222#endif
102223
102224  return rc;
102225}
102226
102227/*
102228** Undo the effects of sqlite3_initialize().  Must not be called while
102229** there are outstanding database connections or memory allocations or
102230** while any part of SQLite is otherwise in use in any thread.  This
102231** routine is not threadsafe.  But it is safe to invoke this routine
102232** on when SQLite is already shut down.  If SQLite is already shut down
102233** when this routine is invoked, then this routine is a harmless no-op.
102234*/
102235SQLITE_API int sqlite3_shutdown(void){
102236  if( sqlite3GlobalConfig.isInit ){
102237    sqlite3_os_end();
102238    sqlite3_reset_auto_extension();
102239    sqlite3GlobalConfig.isInit = 0;
102240  }
102241  if( sqlite3GlobalConfig.isPCacheInit ){
102242    sqlite3PcacheShutdown();
102243    sqlite3GlobalConfig.isPCacheInit = 0;
102244  }
102245  if( sqlite3GlobalConfig.isMallocInit ){
102246    sqlite3MallocEnd();
102247    sqlite3GlobalConfig.isMallocInit = 0;
102248  }
102249  if( sqlite3GlobalConfig.isMutexInit ){
102250    sqlite3MutexEnd();
102251    sqlite3GlobalConfig.isMutexInit = 0;
102252  }
102253
102254  return SQLITE_OK;
102255}
102256
102257/*
102258** This API allows applications to modify the global configuration of
102259** the SQLite library at run-time.
102260**
102261** This routine should only be called when there are no outstanding
102262** database connections or memory allocations.  This routine is not
102263** threadsafe.  Failure to heed these warnings can lead to unpredictable
102264** behavior.
102265*/
102266SQLITE_API int sqlite3_config(int op, ...){
102267  va_list ap;
102268  int rc = SQLITE_OK;
102269
102270  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
102271  ** the SQLite library is in use. */
102272  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
102273
102274  va_start(ap, op);
102275  switch( op ){
102276
102277    /* Mutex configuration options are only available in a threadsafe
102278    ** compile.
102279    */
102280#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
102281    case SQLITE_CONFIG_SINGLETHREAD: {
102282      /* Disable all mutexing */
102283      sqlite3GlobalConfig.bCoreMutex = 0;
102284      sqlite3GlobalConfig.bFullMutex = 0;
102285      break;
102286    }
102287    case SQLITE_CONFIG_MULTITHREAD: {
102288      /* Disable mutexing of database connections */
102289      /* Enable mutexing of core data structures */
102290      sqlite3GlobalConfig.bCoreMutex = 1;
102291      sqlite3GlobalConfig.bFullMutex = 0;
102292      break;
102293    }
102294    case SQLITE_CONFIG_SERIALIZED: {
102295      /* Enable all mutexing */
102296      sqlite3GlobalConfig.bCoreMutex = 1;
102297      sqlite3GlobalConfig.bFullMutex = 1;
102298      break;
102299    }
102300    case SQLITE_CONFIG_MUTEX: {
102301      /* Specify an alternative mutex implementation */
102302      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
102303      break;
102304    }
102305    case SQLITE_CONFIG_GETMUTEX: {
102306      /* Retrieve the current mutex implementation */
102307      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
102308      break;
102309    }
102310#endif
102311
102312
102313    case SQLITE_CONFIG_MALLOC: {
102314      /* Specify an alternative malloc implementation */
102315      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
102316      break;
102317    }
102318    case SQLITE_CONFIG_GETMALLOC: {
102319      /* Retrieve the current malloc() implementation */
102320      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
102321      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
102322      break;
102323    }
102324    case SQLITE_CONFIG_MEMSTATUS: {
102325      /* Enable or disable the malloc status collection */
102326      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
102327      break;
102328    }
102329    case SQLITE_CONFIG_SCRATCH: {
102330      /* Designate a buffer for scratch memory space */
102331      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
102332      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
102333      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
102334      break;
102335    }
102336    case SQLITE_CONFIG_PAGECACHE: {
102337      /* Designate a buffer for page cache memory space */
102338      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
102339      sqlite3GlobalConfig.szPage = va_arg(ap, int);
102340      sqlite3GlobalConfig.nPage = va_arg(ap, int);
102341      break;
102342    }
102343
102344    case SQLITE_CONFIG_PCACHE: {
102345      /* Specify an alternative page cache implementation */
102346      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
102347      break;
102348    }
102349
102350    case SQLITE_CONFIG_GETPCACHE: {
102351      if( sqlite3GlobalConfig.pcache.xInit==0 ){
102352        sqlite3PCacheSetDefault();
102353      }
102354      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
102355      break;
102356    }
102357
102358#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
102359    case SQLITE_CONFIG_HEAP: {
102360      /* Designate a buffer for heap memory space */
102361      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
102362      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
102363      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
102364
102365      if( sqlite3GlobalConfig.pHeap==0 ){
102366        /* If the heap pointer is NULL, then restore the malloc implementation
102367        ** back to NULL pointers too.  This will cause the malloc to go
102368        ** back to its default implementation when sqlite3_initialize() is
102369        ** run.
102370        */
102371        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
102372      }else{
102373        /* The heap pointer is not NULL, then install one of the
102374        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
102375        ** ENABLE_MEMSYS5 is defined, return an error.
102376        */
102377#ifdef SQLITE_ENABLE_MEMSYS3
102378        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
102379#endif
102380#ifdef SQLITE_ENABLE_MEMSYS5
102381        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
102382#endif
102383      }
102384      break;
102385    }
102386#endif
102387
102388    case SQLITE_CONFIG_LOOKASIDE: {
102389      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
102390      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
102391      break;
102392    }
102393
102394    /* Record a pointer to the logger funcction and its first argument.
102395    ** The default is NULL.  Logging is disabled if the function pointer is
102396    ** NULL.
102397    */
102398    case SQLITE_CONFIG_LOG: {
102399      /* MSVC is picky about pulling func ptrs from va lists.
102400      ** http://support.microsoft.com/kb/47961
102401      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
102402      */
102403      typedef void(*LOGFUNC_t)(void*,int,const char*);
102404      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
102405      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
102406      break;
102407    }
102408
102409    default: {
102410      rc = SQLITE_ERROR;
102411      break;
102412    }
102413  }
102414  va_end(ap);
102415  return rc;
102416}
102417
102418/*
102419** Set up the lookaside buffers for a database connection.
102420** Return SQLITE_OK on success.
102421** If lookaside is already active, return SQLITE_BUSY.
102422**
102423** The sz parameter is the number of bytes in each lookaside slot.
102424** The cnt parameter is the number of slots.  If pStart is NULL the
102425** space for the lookaside memory is obtained from sqlite3_malloc().
102426** If pStart is not NULL then it is sz*cnt bytes of memory to use for
102427** the lookaside memory.
102428*/
102429static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
102430  void *pStart;
102431  if( db->lookaside.nOut ){
102432    return SQLITE_BUSY;
102433  }
102434  /* Free any existing lookaside buffer for this handle before
102435  ** allocating a new one so we don't have to have space for
102436  ** both at the same time.
102437  */
102438  if( db->lookaside.bMalloced ){
102439    sqlite3_free(db->lookaside.pStart);
102440  }
102441  /* The size of a lookaside slot needs to be larger than a pointer
102442  ** to be useful.
102443  */
102444  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
102445  if( cnt<0 ) cnt = 0;
102446  if( sz==0 || cnt==0 ){
102447    sz = 0;
102448    pStart = 0;
102449  }else if( pBuf==0 ){
102450    sz = ROUND8(sz);
102451    sqlite3BeginBenignMalloc();
102452    pStart = sqlite3Malloc( sz*cnt );
102453    sqlite3EndBenignMalloc();
102454  }else{
102455    sz = ROUNDDOWN8(sz);
102456    pStart = pBuf;
102457  }
102458  db->lookaside.pStart = pStart;
102459  db->lookaside.pFree = 0;
102460  db->lookaside.sz = (u16)sz;
102461  if( pStart ){
102462    int i;
102463    LookasideSlot *p;
102464    assert( sz > (int)sizeof(LookasideSlot*) );
102465    p = (LookasideSlot*)pStart;
102466    for(i=cnt-1; i>=0; i--){
102467      p->pNext = db->lookaside.pFree;
102468      db->lookaside.pFree = p;
102469      p = (LookasideSlot*)&((u8*)p)[sz];
102470    }
102471    db->lookaside.pEnd = p;
102472    db->lookaside.bEnabled = 1;
102473    db->lookaside.bMalloced = pBuf==0 ?1:0;
102474  }else{
102475    db->lookaside.pEnd = 0;
102476    db->lookaside.bEnabled = 0;
102477    db->lookaside.bMalloced = 0;
102478  }
102479  return SQLITE_OK;
102480}
102481
102482/*
102483** Return the mutex associated with a database connection.
102484*/
102485SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
102486  return db->mutex;
102487}
102488
102489/*
102490** Configuration settings for an individual database connection
102491*/
102492SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
102493  va_list ap;
102494  int rc;
102495  va_start(ap, op);
102496  switch( op ){
102497    case SQLITE_DBCONFIG_LOOKASIDE: {
102498      void *pBuf = va_arg(ap, void*);
102499      int sz = va_arg(ap, int);
102500      int cnt = va_arg(ap, int);
102501      rc = setupLookaside(db, pBuf, sz, cnt);
102502      break;
102503    }
102504    default: {
102505      rc = SQLITE_ERROR;
102506      break;
102507    }
102508  }
102509  va_end(ap);
102510  return rc;
102511}
102512
102513
102514/*
102515** Return true if the buffer z[0..n-1] contains all spaces.
102516*/
102517static int allSpaces(const char *z, int n){
102518  while( n>0 && z[n-1]==' ' ){ n--; }
102519  return n==0;
102520}
102521
102522/*
102523** This is the default collating function named "BINARY" which is always
102524** available.
102525**
102526** If the padFlag argument is not NULL then space padding at the end
102527** of strings is ignored.  This implements the RTRIM collation.
102528*/
102529static int binCollFunc(
102530  void *padFlag,
102531  int nKey1, const void *pKey1,
102532  int nKey2, const void *pKey2
102533){
102534  int rc, n;
102535  n = nKey1<nKey2 ? nKey1 : nKey2;
102536  rc = memcmp(pKey1, pKey2, n);
102537  if( rc==0 ){
102538    if( padFlag
102539     && allSpaces(((char*)pKey1)+n, nKey1-n)
102540     && allSpaces(((char*)pKey2)+n, nKey2-n)
102541    ){
102542      /* Leave rc unchanged at 0 */
102543    }else{
102544      rc = nKey1 - nKey2;
102545    }
102546  }
102547  return rc;
102548}
102549
102550/*
102551** Another built-in collating sequence: NOCASE.
102552**
102553** This collating sequence is intended to be used for "case independant
102554** comparison". SQLite's knowledge of upper and lower case equivalents
102555** extends only to the 26 characters used in the English language.
102556**
102557** At the moment there is only a UTF-8 implementation.
102558*/
102559static int nocaseCollatingFunc(
102560  void *NotUsed,
102561  int nKey1, const void *pKey1,
102562  int nKey2, const void *pKey2
102563){
102564  int r = sqlite3StrNICmp(
102565      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
102566  UNUSED_PARAMETER(NotUsed);
102567  if( 0==r ){
102568    r = nKey1-nKey2;
102569  }
102570  return r;
102571}
102572
102573/*
102574** Return the ROWID of the most recent insert
102575*/
102576SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
102577  return db->lastRowid;
102578}
102579
102580/*
102581** Return the number of changes in the most recent call to sqlite3_exec().
102582*/
102583SQLITE_API int sqlite3_changes(sqlite3 *db){
102584  return db->nChange;
102585}
102586
102587/*
102588** Return the number of changes since the database handle was opened.
102589*/
102590SQLITE_API int sqlite3_total_changes(sqlite3 *db){
102591  return db->nTotalChange;
102592}
102593
102594/*
102595** Close all open savepoints. This function only manipulates fields of the
102596** database handle object, it does not close any savepoints that may be open
102597** at the b-tree/pager level.
102598*/
102599SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
102600  while( db->pSavepoint ){
102601    Savepoint *pTmp = db->pSavepoint;
102602    db->pSavepoint = pTmp->pNext;
102603    sqlite3DbFree(db, pTmp);
102604  }
102605  db->nSavepoint = 0;
102606  db->nStatement = 0;
102607  db->isTransactionSavepoint = 0;
102608}
102609
102610/*
102611** Close an existing SQLite database
102612*/
102613SQLITE_API int sqlite3_close(sqlite3 *db){
102614  HashElem *i;
102615  int j;
102616
102617  if( !db ){
102618    return SQLITE_OK;
102619  }
102620  if( !sqlite3SafetyCheckSickOrOk(db) ){
102621    return SQLITE_MISUSE_BKPT;
102622  }
102623  sqlite3_mutex_enter(db->mutex);
102624
102625  sqlite3ResetInternalSchema(db, 0);
102626
102627  /* If a transaction is open, the ResetInternalSchema() call above
102628  ** will not have called the xDisconnect() method on any virtual
102629  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
102630  ** call will do so. We need to do this before the check for active
102631  ** SQL statements below, as the v-table implementation may be storing
102632  ** some prepared statements internally.
102633  */
102634  sqlite3VtabRollback(db);
102635
102636  /* If there are any outstanding VMs, return SQLITE_BUSY. */
102637  if( db->pVdbe ){
102638    sqlite3Error(db, SQLITE_BUSY,
102639        "unable to close due to unfinalised statements");
102640    sqlite3_mutex_leave(db->mutex);
102641    return SQLITE_BUSY;
102642  }
102643  assert( sqlite3SafetyCheckSickOrOk(db) );
102644
102645  for(j=0; j<db->nDb; j++){
102646    Btree *pBt = db->aDb[j].pBt;
102647    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
102648      sqlite3Error(db, SQLITE_BUSY,
102649          "unable to close due to unfinished backup operation");
102650      sqlite3_mutex_leave(db->mutex);
102651      return SQLITE_BUSY;
102652    }
102653  }
102654
102655  /* Free any outstanding Savepoint structures. */
102656  sqlite3CloseSavepoints(db);
102657
102658  for(j=0; j<db->nDb; j++){
102659    struct Db *pDb = &db->aDb[j];
102660    if( pDb->pBt ){
102661      sqlite3BtreeClose(pDb->pBt);
102662      pDb->pBt = 0;
102663      if( j!=1 ){
102664        pDb->pSchema = 0;
102665      }
102666    }
102667  }
102668  sqlite3ResetInternalSchema(db, 0);
102669
102670  /* Tell the code in notify.c that the connection no longer holds any
102671  ** locks and does not require any further unlock-notify callbacks.
102672  */
102673  sqlite3ConnectionClosed(db);
102674
102675  assert( db->nDb<=2 );
102676  assert( db->aDb==db->aDbStatic );
102677  for(j=0; j<ArraySize(db->aFunc.a); j++){
102678    FuncDef *pNext, *pHash, *p;
102679    for(p=db->aFunc.a[j]; p; p=pHash){
102680      pHash = p->pHash;
102681      while( p ){
102682        pNext = p->pNext;
102683        sqlite3DbFree(db, p);
102684        p = pNext;
102685      }
102686    }
102687  }
102688  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
102689    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
102690    /* Invoke any destructors registered for collation sequence user data. */
102691    for(j=0; j<3; j++){
102692      if( pColl[j].xDel ){
102693        pColl[j].xDel(pColl[j].pUser);
102694      }
102695    }
102696    sqlite3DbFree(db, pColl);
102697  }
102698  sqlite3HashClear(&db->aCollSeq);
102699#ifndef SQLITE_OMIT_VIRTUALTABLE
102700  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
102701    Module *pMod = (Module *)sqliteHashData(i);
102702    if( pMod->xDestroy ){
102703      pMod->xDestroy(pMod->pAux);
102704    }
102705    sqlite3DbFree(db, pMod);
102706  }
102707  sqlite3HashClear(&db->aModule);
102708#endif
102709
102710  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
102711  if( db->pErr ){
102712    sqlite3ValueFree(db->pErr);
102713  }
102714  sqlite3CloseExtensions(db);
102715
102716  db->magic = SQLITE_MAGIC_ERROR;
102717
102718  /* The temp-database schema is allocated differently from the other schema
102719  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
102720  ** So it needs to be freed here. Todo: Why not roll the temp schema into
102721  ** the same sqliteMalloc() as the one that allocates the database
102722  ** structure?
102723  */
102724  sqlite3DbFree(db, db->aDb[1].pSchema);
102725  sqlite3_mutex_leave(db->mutex);
102726  db->magic = SQLITE_MAGIC_CLOSED;
102727  sqlite3_mutex_free(db->mutex);
102728  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
102729  if( db->lookaside.bMalloced ){
102730    sqlite3_free(db->lookaside.pStart);
102731  }
102732  sqlite3_free(db);
102733  return SQLITE_OK;
102734}
102735
102736/*
102737** Rollback all database files.
102738*/
102739SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
102740  int i;
102741  int inTrans = 0;
102742  assert( sqlite3_mutex_held(db->mutex) );
102743  sqlite3BeginBenignMalloc();
102744  for(i=0; i<db->nDb; i++){
102745    if( db->aDb[i].pBt ){
102746      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
102747        inTrans = 1;
102748      }
102749      sqlite3BtreeRollback(db->aDb[i].pBt);
102750      db->aDb[i].inTrans = 0;
102751    }
102752  }
102753  sqlite3VtabRollback(db);
102754  sqlite3EndBenignMalloc();
102755
102756  if( db->flags&SQLITE_InternChanges ){
102757    sqlite3ExpirePreparedStatements(db);
102758    sqlite3ResetInternalSchema(db, 0);
102759  }
102760
102761  /* Any deferred constraint violations have now been resolved. */
102762  db->nDeferredCons = 0;
102763
102764  /* If one has been configured, invoke the rollback-hook callback */
102765  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
102766    db->xRollbackCallback(db->pRollbackArg);
102767  }
102768}
102769
102770/*
102771** Return a static string that describes the kind of error specified in the
102772** argument.
102773*/
102774SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
102775  static const char* const aMsg[] = {
102776    /* SQLITE_OK          */ "not an error",
102777    /* SQLITE_ERROR       */ "SQL logic error or missing database",
102778    /* SQLITE_INTERNAL    */ 0,
102779    /* SQLITE_PERM        */ "access permission denied",
102780    /* SQLITE_ABORT       */ "callback requested query abort",
102781    /* SQLITE_BUSY        */ "database is locked",
102782    /* SQLITE_LOCKED      */ "database table is locked",
102783    /* SQLITE_NOMEM       */ "out of memory",
102784    /* SQLITE_READONLY    */ "attempt to write a readonly database",
102785    /* SQLITE_INTERRUPT   */ "interrupted",
102786    /* SQLITE_IOERR       */ "disk I/O error",
102787    /* SQLITE_CORRUPT     */ "database disk image is malformed",
102788    /* SQLITE_NOTFOUND    */ 0,
102789    /* SQLITE_FULL        */ "database or disk is full",
102790    /* SQLITE_CANTOPEN    */ "unable to open database file",
102791    /* SQLITE_PROTOCOL    */ "locking protocol",
102792    /* SQLITE_EMPTY       */ "table contains no data",
102793    /* SQLITE_SCHEMA      */ "database schema has changed",
102794    /* SQLITE_TOOBIG      */ "string or blob too big",
102795    /* SQLITE_CONSTRAINT  */ "constraint failed",
102796    /* SQLITE_MISMATCH    */ "datatype mismatch",
102797    /* SQLITE_MISUSE      */ "library routine called out of sequence",
102798    /* SQLITE_NOLFS       */ "large file support is disabled",
102799    /* SQLITE_AUTH        */ "authorization denied",
102800    /* SQLITE_FORMAT      */ "auxiliary database format error",
102801    /* SQLITE_RANGE       */ "bind or column index out of range",
102802    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
102803  };
102804  rc &= 0xff;
102805  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
102806    return aMsg[rc];
102807  }else{
102808    return "unknown error";
102809  }
102810}
102811
102812/*
102813** This routine implements a busy callback that sleeps and tries
102814** again until a timeout value is reached.  The timeout value is
102815** an integer number of milliseconds passed in as the first
102816** argument.
102817*/
102818static int sqliteDefaultBusyCallback(
102819 void *ptr,               /* Database connection */
102820 int count                /* Number of times table has been busy */
102821){
102822#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
102823  static const u8 delays[] =
102824     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
102825  static const u8 totals[] =
102826     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
102827# define NDELAY (sizeof(delays)/sizeof(delays[0]))
102828  sqlite3 *db = (sqlite3 *)ptr;
102829  int timeout = db->busyTimeout;
102830  int delay, prior;
102831
102832  assert( count>=0 );
102833  if( count < NDELAY ){
102834    delay = delays[count];
102835    prior = totals[count];
102836  }else{
102837    delay = delays[NDELAY-1];
102838    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
102839  }
102840  if( prior + delay > timeout ){
102841    delay = timeout - prior;
102842    if( delay<=0 ) return 0;
102843  }
102844  sqlite3OsSleep(db->pVfs, delay*1000);
102845  return 1;
102846#else
102847  sqlite3 *db = (sqlite3 *)ptr;
102848  int timeout = ((sqlite3 *)ptr)->busyTimeout;
102849  if( (count+1)*1000 > timeout ){
102850    return 0;
102851  }
102852  sqlite3OsSleep(db->pVfs, 1000000);
102853  return 1;
102854#endif
102855}
102856
102857/*
102858** Invoke the given busy handler.
102859**
102860** This routine is called when an operation failed with a lock.
102861** If this routine returns non-zero, the lock is retried.  If it
102862** returns 0, the operation aborts with an SQLITE_BUSY error.
102863*/
102864SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
102865  int rc;
102866  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
102867  rc = p->xFunc(p->pArg, p->nBusy);
102868  if( rc==0 ){
102869    p->nBusy = -1;
102870  }else{
102871    p->nBusy++;
102872  }
102873  return rc;
102874}
102875
102876/*
102877** This routine sets the busy callback for an Sqlite database to the
102878** given callback function with the given argument.
102879*/
102880SQLITE_API int sqlite3_busy_handler(
102881  sqlite3 *db,
102882  int (*xBusy)(void*,int),
102883  void *pArg
102884){
102885  sqlite3_mutex_enter(db->mutex);
102886  db->busyHandler.xFunc = xBusy;
102887  db->busyHandler.pArg = pArg;
102888  db->busyHandler.nBusy = 0;
102889  sqlite3_mutex_leave(db->mutex);
102890  return SQLITE_OK;
102891}
102892
102893#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
102894/*
102895** This routine sets the progress callback for an Sqlite database to the
102896** given callback function with the given argument. The progress callback will
102897** be invoked every nOps opcodes.
102898*/
102899SQLITE_API void sqlite3_progress_handler(
102900  sqlite3 *db,
102901  int nOps,
102902  int (*xProgress)(void*),
102903  void *pArg
102904){
102905  sqlite3_mutex_enter(db->mutex);
102906  if( nOps>0 ){
102907    db->xProgress = xProgress;
102908    db->nProgressOps = nOps;
102909    db->pProgressArg = pArg;
102910  }else{
102911    db->xProgress = 0;
102912    db->nProgressOps = 0;
102913    db->pProgressArg = 0;
102914  }
102915  sqlite3_mutex_leave(db->mutex);
102916}
102917#endif
102918
102919
102920/*
102921** This routine installs a default busy handler that waits for the
102922** specified number of milliseconds before returning 0.
102923*/
102924SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
102925  if( ms>0 ){
102926    db->busyTimeout = ms;
102927    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
102928  }else{
102929    sqlite3_busy_handler(db, 0, 0);
102930  }
102931  return SQLITE_OK;
102932}
102933
102934/*
102935** Cause any pending operation to stop at its earliest opportunity.
102936*/
102937SQLITE_API void sqlite3_interrupt(sqlite3 *db){
102938  db->u1.isInterrupted = 1;
102939}
102940
102941
102942/*
102943** This function is exactly the same as sqlite3_create_function(), except
102944** that it is designed to be called by internal code. The difference is
102945** that if a malloc() fails in sqlite3_create_function(), an error code
102946** is returned and the mallocFailed flag cleared.
102947*/
102948SQLITE_PRIVATE int sqlite3CreateFunc(
102949  sqlite3 *db,
102950  const char *zFunctionName,
102951  int nArg,
102952  int enc,
102953  void *pUserData,
102954  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
102955  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
102956  void (*xFinal)(sqlite3_context*)
102957){
102958  FuncDef *p;
102959  int nName;
102960
102961  assert( sqlite3_mutex_held(db->mutex) );
102962  if( zFunctionName==0 ||
102963      (xFunc && (xFinal || xStep)) ||
102964      (!xFunc && (xFinal && !xStep)) ||
102965      (!xFunc && (!xFinal && xStep)) ||
102966      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
102967      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
102968    return SQLITE_MISUSE_BKPT;
102969  }
102970
102971#ifndef SQLITE_OMIT_UTF16
102972  /* If SQLITE_UTF16 is specified as the encoding type, transform this
102973  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
102974  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
102975  **
102976  ** If SQLITE_ANY is specified, add three versions of the function
102977  ** to the hash table.
102978  */
102979  if( enc==SQLITE_UTF16 ){
102980    enc = SQLITE_UTF16NATIVE;
102981  }else if( enc==SQLITE_ANY ){
102982    int rc;
102983    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
102984         pUserData, xFunc, xStep, xFinal);
102985    if( rc==SQLITE_OK ){
102986      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
102987          pUserData, xFunc, xStep, xFinal);
102988    }
102989    if( rc!=SQLITE_OK ){
102990      return rc;
102991    }
102992    enc = SQLITE_UTF16BE;
102993  }
102994#else
102995  enc = SQLITE_UTF8;
102996#endif
102997
102998  /* Check if an existing function is being overridden or deleted. If so,
102999  ** and there are active VMs, then return SQLITE_BUSY. If a function
103000  ** is being overridden/deleted but there are no active VMs, allow the
103001  ** operation to continue but invalidate all precompiled statements.
103002  */
103003  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
103004  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
103005    if( db->activeVdbeCnt ){
103006      sqlite3Error(db, SQLITE_BUSY,
103007        "unable to delete/modify user-function due to active statements");
103008      assert( !db->mallocFailed );
103009      return SQLITE_BUSY;
103010    }else{
103011      sqlite3ExpirePreparedStatements(db);
103012    }
103013  }
103014
103015  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
103016  assert(p || db->mallocFailed);
103017  if( !p ){
103018    return SQLITE_NOMEM;
103019  }
103020  p->flags = 0;
103021  p->xFunc = xFunc;
103022  p->xStep = xStep;
103023  p->xFinalize = xFinal;
103024  p->pUserData = pUserData;
103025  p->nArg = (u16)nArg;
103026  return SQLITE_OK;
103027}
103028
103029/*
103030** Create new user functions.
103031*/
103032SQLITE_API int sqlite3_create_function(
103033  sqlite3 *db,
103034  const char *zFunctionName,
103035  int nArg,
103036  int enc,
103037  void *p,
103038  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
103039  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
103040  void (*xFinal)(sqlite3_context*)
103041){
103042  int rc;
103043  sqlite3_mutex_enter(db->mutex);
103044  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
103045  rc = sqlite3ApiExit(db, rc);
103046  sqlite3_mutex_leave(db->mutex);
103047  return rc;
103048}
103049
103050#ifndef SQLITE_OMIT_UTF16
103051SQLITE_API int sqlite3_create_function16(
103052  sqlite3 *db,
103053  const void *zFunctionName,
103054  int nArg,
103055  int eTextRep,
103056  void *p,
103057  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
103058  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
103059  void (*xFinal)(sqlite3_context*)
103060){
103061  int rc;
103062  char *zFunc8;
103063  sqlite3_mutex_enter(db->mutex);
103064  assert( !db->mallocFailed );
103065  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
103066  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
103067  sqlite3DbFree(db, zFunc8);
103068  rc = sqlite3ApiExit(db, rc);
103069  sqlite3_mutex_leave(db->mutex);
103070  return rc;
103071}
103072#endif
103073
103074
103075/*
103076** Declare that a function has been overloaded by a virtual table.
103077**
103078** If the function already exists as a regular global function, then
103079** this routine is a no-op.  If the function does not exist, then create
103080** a new one that always throws a run-time error.
103081**
103082** When virtual tables intend to provide an overloaded function, they
103083** should call this routine to make sure the global function exists.
103084** A global function must exist in order for name resolution to work
103085** properly.
103086*/
103087SQLITE_API int sqlite3_overload_function(
103088  sqlite3 *db,
103089  const char *zName,
103090  int nArg
103091){
103092  int nName = sqlite3Strlen30(zName);
103093  int rc;
103094  sqlite3_mutex_enter(db->mutex);
103095  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
103096    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
103097                      0, sqlite3InvalidFunction, 0, 0);
103098  }
103099  rc = sqlite3ApiExit(db, SQLITE_OK);
103100  sqlite3_mutex_leave(db->mutex);
103101  return rc;
103102}
103103
103104#ifndef SQLITE_OMIT_TRACE
103105/*
103106** Register a trace function.  The pArg from the previously registered trace
103107** is returned.
103108**
103109** A NULL trace function means that no tracing is executes.  A non-NULL
103110** trace is a pointer to a function that is invoked at the start of each
103111** SQL statement.
103112*/
103113SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
103114  void *pOld;
103115  sqlite3_mutex_enter(db->mutex);
103116  pOld = db->pTraceArg;
103117  db->xTrace = xTrace;
103118  db->pTraceArg = pArg;
103119  sqlite3_mutex_leave(db->mutex);
103120  return pOld;
103121}
103122/*
103123** Register a profile function.  The pArg from the previously registered
103124** profile function is returned.
103125**
103126** A NULL profile function means that no profiling is executes.  A non-NULL
103127** profile is a pointer to a function that is invoked at the conclusion of
103128** each SQL statement that is run.
103129*/
103130SQLITE_API void *sqlite3_profile(
103131  sqlite3 *db,
103132  void (*xProfile)(void*,const char*,sqlite_uint64),
103133  void *pArg
103134){
103135  void *pOld;
103136  sqlite3_mutex_enter(db->mutex);
103137  pOld = db->pProfileArg;
103138  db->xProfile = xProfile;
103139  db->pProfileArg = pArg;
103140  sqlite3_mutex_leave(db->mutex);
103141  return pOld;
103142}
103143#endif /* SQLITE_OMIT_TRACE */
103144
103145/*** EXPERIMENTAL ***
103146**
103147** Register a function to be invoked when a transaction comments.
103148** If the invoked function returns non-zero, then the commit becomes a
103149** rollback.
103150*/
103151SQLITE_API void *sqlite3_commit_hook(
103152  sqlite3 *db,              /* Attach the hook to this database */
103153  int (*xCallback)(void*),  /* Function to invoke on each commit */
103154  void *pArg                /* Argument to the function */
103155){
103156  void *pOld;
103157  sqlite3_mutex_enter(db->mutex);
103158  pOld = db->pCommitArg;
103159  db->xCommitCallback = xCallback;
103160  db->pCommitArg = pArg;
103161  sqlite3_mutex_leave(db->mutex);
103162  return pOld;
103163}
103164
103165/*
103166** Register a callback to be invoked each time a row is updated,
103167** inserted or deleted using this database connection.
103168*/
103169SQLITE_API void *sqlite3_update_hook(
103170  sqlite3 *db,              /* Attach the hook to this database */
103171  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
103172  void *pArg                /* Argument to the function */
103173){
103174  void *pRet;
103175  sqlite3_mutex_enter(db->mutex);
103176  pRet = db->pUpdateArg;
103177  db->xUpdateCallback = xCallback;
103178  db->pUpdateArg = pArg;
103179  sqlite3_mutex_leave(db->mutex);
103180  return pRet;
103181}
103182
103183/*
103184** Register a callback to be invoked each time a transaction is rolled
103185** back by this database connection.
103186*/
103187SQLITE_API void *sqlite3_rollback_hook(
103188  sqlite3 *db,              /* Attach the hook to this database */
103189  void (*xCallback)(void*), /* Callback function */
103190  void *pArg                /* Argument to the function */
103191){
103192  void *pRet;
103193  sqlite3_mutex_enter(db->mutex);
103194  pRet = db->pRollbackArg;
103195  db->xRollbackCallback = xCallback;
103196  db->pRollbackArg = pArg;
103197  sqlite3_mutex_leave(db->mutex);
103198  return pRet;
103199}
103200
103201#ifndef SQLITE_OMIT_WAL
103202/*
103203** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
103204** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
103205** is greater than sqlite3.pWalArg cast to an integer (the value configured by
103206** wal_autocheckpoint()).
103207*/
103208SQLITE_PRIVATE int sqlite3WalDefaultHook(
103209  void *pClientData,     /* Argument */
103210  sqlite3 *db,           /* Connection */
103211  const char *zDb,       /* Database */
103212  int nFrame             /* Size of WAL */
103213){
103214  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
103215    sqlite3BeginBenignMalloc();
103216    sqlite3_wal_checkpoint(db, zDb);
103217    sqlite3EndBenignMalloc();
103218  }
103219  return SQLITE_OK;
103220}
103221#endif /* SQLITE_OMIT_WAL */
103222
103223/*
103224** Configure an sqlite3_wal_hook() callback to automatically checkpoint
103225** a database after committing a transaction if there are nFrame or
103226** more frames in the log file. Passing zero or a negative value as the
103227** nFrame parameter disables automatic checkpoints entirely.
103228**
103229** The callback registered by this function replaces any existing callback
103230** registered using sqlite3_wal_hook(). Likewise, registering a callback
103231** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
103232** configured by this function.
103233*/
103234SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
103235#ifndef SQLITE_OMIT_WAL
103236  if( nFrame>0 ){
103237    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
103238  }else{
103239    sqlite3_wal_hook(db, 0, 0);
103240  }
103241#endif
103242  return SQLITE_OK;
103243}
103244
103245/*
103246** Register a callback to be invoked each time a transaction is written
103247** into the write-ahead-log by this database connection.
103248*/
103249SQLITE_API void *sqlite3_wal_hook(
103250  sqlite3 *db,                    /* Attach the hook to this db handle */
103251  int(*xCallback)(void *, sqlite3*, const char*, int),
103252  void *pArg                      /* First argument passed to xCallback() */
103253){
103254#ifndef SQLITE_OMIT_WAL
103255  void *pRet;
103256  sqlite3_mutex_enter(db->mutex);
103257  pRet = db->pWalArg;
103258  db->xWalCallback = xCallback;
103259  db->pWalArg = pArg;
103260  sqlite3_mutex_leave(db->mutex);
103261  return pRet;
103262#else
103263  return 0;
103264#endif
103265}
103266
103267
103268/*
103269** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
103270** to contains a zero-length string, all attached databases are
103271** checkpointed.
103272*/
103273SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
103274#ifdef SQLITE_OMIT_WAL
103275  return SQLITE_OK;
103276#else
103277  int rc;                         /* Return code */
103278  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
103279
103280  sqlite3_mutex_enter(db->mutex);
103281  if( zDb && zDb[0] ){
103282    iDb = sqlite3FindDbName(db, zDb);
103283  }
103284  if( iDb<0 ){
103285    rc = SQLITE_ERROR;
103286    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
103287  }else{
103288    rc = sqlite3Checkpoint(db, iDb);
103289    sqlite3Error(db, rc, 0);
103290  }
103291  rc = sqlite3ApiExit(db, rc);
103292  sqlite3_mutex_leave(db->mutex);
103293  return rc;
103294#endif
103295}
103296
103297#ifndef SQLITE_OMIT_WAL
103298/*
103299** Run a checkpoint on database iDb. This is a no-op if database iDb is
103300** not currently open in WAL mode.
103301**
103302** If a transaction is open on the database being checkpointed, this
103303** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
103304** an error occurs while running the checkpoint, an SQLite error code is
103305** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
103306**
103307** The mutex on database handle db should be held by the caller. The mutex
103308** associated with the specific b-tree being checkpointed is taken by
103309** this function while the checkpoint is running.
103310**
103311** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
103312** checkpointed. If an error is encountered it is returned immediately -
103313** no attempt is made to checkpoint any remaining databases.
103314*/
103315SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
103316  int rc = SQLITE_OK;             /* Return code */
103317  int i;                          /* Used to iterate through attached dbs */
103318
103319  assert( sqlite3_mutex_held(db->mutex) );
103320
103321  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
103322    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
103323      Btree *pBt = db->aDb[i].pBt;
103324      if( pBt ){
103325        if( sqlite3BtreeIsInReadTrans(pBt) ){
103326          rc = SQLITE_LOCKED;
103327        }else{
103328          sqlite3BtreeEnter(pBt);
103329          rc = sqlite3PagerCheckpoint(sqlite3BtreePager(pBt));
103330          sqlite3BtreeLeave(pBt);
103331        }
103332      }
103333    }
103334  }
103335
103336  return rc;
103337}
103338#endif /* SQLITE_OMIT_WAL */
103339
103340/*
103341** This function returns true if main-memory should be used instead of
103342** a temporary file for transient pager files and statement journals.
103343** The value returned depends on the value of db->temp_store (runtime
103344** parameter) and the compile time value of SQLITE_TEMP_STORE. The
103345** following table describes the relationship between these two values
103346** and this functions return value.
103347**
103348**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
103349**   -----------------     --------------     ------------------------------
103350**   0                     any                file      (return 0)
103351**   1                     1                  file      (return 0)
103352**   1                     2                  memory    (return 1)
103353**   1                     0                  file      (return 0)
103354**   2                     1                  file      (return 0)
103355**   2                     2                  memory    (return 1)
103356**   2                     0                  memory    (return 1)
103357**   3                     any                memory    (return 1)
103358*/
103359SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
103360#if SQLITE_TEMP_STORE==1
103361  return ( db->temp_store==2 );
103362#endif
103363#if SQLITE_TEMP_STORE==2
103364  return ( db->temp_store!=1 );
103365#endif
103366#if SQLITE_TEMP_STORE==3
103367  return 1;
103368#endif
103369#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
103370  return 0;
103371#endif
103372}
103373
103374/*
103375** This routine is called to create a connection to a database BTree
103376** driver.  If zFilename is the name of a file, then that file is
103377** opened and used.  If zFilename is the magic name ":memory:" then
103378** the database is stored in memory (and is thus forgotten as soon as
103379** the connection is closed.)  If zFilename is NULL then the database
103380** is a "virtual" database for transient use only and is deleted as
103381** soon as the connection is closed.
103382**
103383** A virtual database can be either a disk file (that is automatically
103384** deleted when the file is closed) or it an be held entirely in memory.
103385** The sqlite3TempInMemory() function is used to determine which.
103386*/
103387SQLITE_PRIVATE int sqlite3BtreeFactory(
103388  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
103389  const char *zFilename,    /* Name of the file containing the BTree database */
103390  int omitJournal,          /* if TRUE then do not journal this file */
103391  int nCache,               /* How many pages in the page cache */
103392  int vfsFlags,             /* Flags passed through to vfsOpen */
103393  Btree **ppBtree           /* Pointer to new Btree object written here */
103394){
103395  int btFlags = 0;
103396  int rc;
103397
103398  assert( sqlite3_mutex_held(db->mutex) );
103399  assert( ppBtree != 0);
103400  if( omitJournal ){
103401    btFlags |= BTREE_OMIT_JOURNAL;
103402  }
103403  if( db->flags & SQLITE_NoReadlock ){
103404    btFlags |= BTREE_NO_READLOCK;
103405  }
103406#ifndef SQLITE_OMIT_MEMORYDB
103407  if( zFilename==0 && sqlite3TempInMemory(db) ){
103408    zFilename = ":memory:";
103409  }
103410#endif
103411
103412  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
103413    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
103414  }
103415  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
103416
103417  /* If the B-Tree was successfully opened, set the pager-cache size to the
103418  ** default value. Except, if the call to BtreeOpen() returned a handle
103419  ** open on an existing shared pager-cache, do not change the pager-cache
103420  ** size.
103421  */
103422  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
103423    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
103424  }
103425  return rc;
103426}
103427
103428/*
103429** Return UTF-8 encoded English language explanation of the most recent
103430** error.
103431*/
103432SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
103433  const char *z;
103434  if( !db ){
103435    return sqlite3ErrStr(SQLITE_NOMEM);
103436  }
103437  if( !sqlite3SafetyCheckSickOrOk(db) ){
103438    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
103439  }
103440  sqlite3_mutex_enter(db->mutex);
103441  if( db->mallocFailed ){
103442    z = sqlite3ErrStr(SQLITE_NOMEM);
103443  }else{
103444    z = (char*)sqlite3_value_text(db->pErr);
103445    assert( !db->mallocFailed );
103446    if( z==0 ){
103447      z = sqlite3ErrStr(db->errCode);
103448    }
103449  }
103450  sqlite3_mutex_leave(db->mutex);
103451  return z;
103452}
103453
103454#ifndef SQLITE_OMIT_UTF16
103455/*
103456** Return UTF-16 encoded English language explanation of the most recent
103457** error.
103458*/
103459SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
103460  static const u16 outOfMem[] = {
103461    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
103462  };
103463  static const u16 misuse[] = {
103464    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
103465    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
103466    'c', 'a', 'l', 'l', 'e', 'd', ' ',
103467    'o', 'u', 't', ' ',
103468    'o', 'f', ' ',
103469    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
103470  };
103471
103472  const void *z;
103473  if( !db ){
103474    return (void *)outOfMem;
103475  }
103476  if( !sqlite3SafetyCheckSickOrOk(db) ){
103477    return (void *)misuse;
103478  }
103479  sqlite3_mutex_enter(db->mutex);
103480  if( db->mallocFailed ){
103481    z = (void *)outOfMem;
103482  }else{
103483    z = sqlite3_value_text16(db->pErr);
103484    if( z==0 ){
103485      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
103486           SQLITE_UTF8, SQLITE_STATIC);
103487      z = sqlite3_value_text16(db->pErr);
103488    }
103489    /* A malloc() may have failed within the call to sqlite3_value_text16()
103490    ** above. If this is the case, then the db->mallocFailed flag needs to
103491    ** be cleared before returning. Do this directly, instead of via
103492    ** sqlite3ApiExit(), to avoid setting the database handle error message.
103493    */
103494    db->mallocFailed = 0;
103495  }
103496  sqlite3_mutex_leave(db->mutex);
103497  return z;
103498}
103499#endif /* SQLITE_OMIT_UTF16 */
103500
103501/*
103502** Return the most recent error code generated by an SQLite routine. If NULL is
103503** passed to this function, we assume a malloc() failed during sqlite3_open().
103504*/
103505SQLITE_API int sqlite3_errcode(sqlite3 *db){
103506  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103507    return SQLITE_MISUSE_BKPT;
103508  }
103509  if( !db || db->mallocFailed ){
103510    return SQLITE_NOMEM;
103511  }
103512  return db->errCode & db->errMask;
103513}
103514SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
103515  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103516    return SQLITE_MISUSE_BKPT;
103517  }
103518  if( !db || db->mallocFailed ){
103519    return SQLITE_NOMEM;
103520  }
103521  return db->errCode;
103522}
103523
103524/*
103525** Create a new collating function for database "db".  The name is zName
103526** and the encoding is enc.
103527*/
103528static int createCollation(
103529  sqlite3* db,
103530  const char *zName,
103531  u8 enc,
103532  u8 collType,
103533  void* pCtx,
103534  int(*xCompare)(void*,int,const void*,int,const void*),
103535  void(*xDel)(void*)
103536){
103537  CollSeq *pColl;
103538  int enc2;
103539  int nName = sqlite3Strlen30(zName);
103540
103541  assert( sqlite3_mutex_held(db->mutex) );
103542
103543  /* If SQLITE_UTF16 is specified as the encoding type, transform this
103544  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
103545  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
103546  */
103547  enc2 = enc;
103548  testcase( enc2==SQLITE_UTF16 );
103549  testcase( enc2==SQLITE_UTF16_ALIGNED );
103550  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
103551    enc2 = SQLITE_UTF16NATIVE;
103552  }
103553  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
103554    return SQLITE_MISUSE_BKPT;
103555  }
103556
103557  /* Check if this call is removing or replacing an existing collation
103558  ** sequence. If so, and there are active VMs, return busy. If there
103559  ** are no active VMs, invalidate any pre-compiled statements.
103560  */
103561  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
103562  if( pColl && pColl->xCmp ){
103563    if( db->activeVdbeCnt ){
103564      sqlite3Error(db, SQLITE_BUSY,
103565        "unable to delete/modify collation sequence due to active statements");
103566      return SQLITE_BUSY;
103567    }
103568    sqlite3ExpirePreparedStatements(db);
103569
103570    /* If collation sequence pColl was created directly by a call to
103571    ** sqlite3_create_collation, and not generated by synthCollSeq(),
103572    ** then any copies made by synthCollSeq() need to be invalidated.
103573    ** Also, collation destructor - CollSeq.xDel() - function may need
103574    ** to be called.
103575    */
103576    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
103577      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
103578      int j;
103579      for(j=0; j<3; j++){
103580        CollSeq *p = &aColl[j];
103581        if( p->enc==pColl->enc ){
103582          if( p->xDel ){
103583            p->xDel(p->pUser);
103584          }
103585          p->xCmp = 0;
103586        }
103587      }
103588    }
103589  }
103590
103591  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
103592  if( pColl ){
103593    pColl->xCmp = xCompare;
103594    pColl->pUser = pCtx;
103595    pColl->xDel = xDel;
103596    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
103597    pColl->type = collType;
103598  }
103599  sqlite3Error(db, SQLITE_OK, 0);
103600  return SQLITE_OK;
103601}
103602
103603
103604/*
103605** This array defines hard upper bounds on limit values.  The
103606** initializer must be kept in sync with the SQLITE_LIMIT_*
103607** #defines in sqlite3.h.
103608*/
103609static const int aHardLimit[] = {
103610  SQLITE_MAX_LENGTH,
103611  SQLITE_MAX_SQL_LENGTH,
103612  SQLITE_MAX_COLUMN,
103613  SQLITE_MAX_EXPR_DEPTH,
103614  SQLITE_MAX_COMPOUND_SELECT,
103615  SQLITE_MAX_VDBE_OP,
103616  SQLITE_MAX_FUNCTION_ARG,
103617  SQLITE_MAX_ATTACHED,
103618  SQLITE_MAX_LIKE_PATTERN_LENGTH,
103619  SQLITE_MAX_VARIABLE_NUMBER,
103620  SQLITE_MAX_TRIGGER_DEPTH,
103621};
103622
103623/*
103624** Make sure the hard limits are set to reasonable values
103625*/
103626#if SQLITE_MAX_LENGTH<100
103627# error SQLITE_MAX_LENGTH must be at least 100
103628#endif
103629#if SQLITE_MAX_SQL_LENGTH<100
103630# error SQLITE_MAX_SQL_LENGTH must be at least 100
103631#endif
103632#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
103633# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
103634#endif
103635#if SQLITE_MAX_COMPOUND_SELECT<2
103636# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
103637#endif
103638#if SQLITE_MAX_VDBE_OP<40
103639# error SQLITE_MAX_VDBE_OP must be at least 40
103640#endif
103641#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
103642# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
103643#endif
103644#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
103645# error SQLITE_MAX_ATTACHED must be between 0 and 30
103646#endif
103647#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
103648# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
103649#endif
103650#if SQLITE_MAX_COLUMN>32767
103651# error SQLITE_MAX_COLUMN must not exceed 32767
103652#endif
103653#if SQLITE_MAX_TRIGGER_DEPTH<1
103654# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
103655#endif
103656
103657
103658/*
103659** Change the value of a limit.  Report the old value.
103660** If an invalid limit index is supplied, report -1.
103661** Make no changes but still report the old value if the
103662** new limit is negative.
103663**
103664** A new lower limit does not shrink existing constructs.
103665** It merely prevents new constructs that exceed the limit
103666** from forming.
103667*/
103668SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
103669  int oldLimit;
103670  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
103671    return -1;
103672  }
103673  oldLimit = db->aLimit[limitId];
103674  if( newLimit>=0 ){
103675    if( newLimit>aHardLimit[limitId] ){
103676      newLimit = aHardLimit[limitId];
103677    }
103678    db->aLimit[limitId] = newLimit;
103679  }
103680  return oldLimit;
103681}
103682
103683/*
103684** This routine does the work of opening a database on behalf of
103685** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
103686** is UTF-8 encoded.
103687*/
103688static int openDatabase(
103689  const char *zFilename, /* Database filename UTF-8 encoded */
103690  sqlite3 **ppDb,        /* OUT: Returned database handle */
103691  unsigned flags,        /* Operational flags */
103692  const char *zVfs       /* Name of the VFS to use */
103693){
103694  sqlite3 *db;
103695  int rc;
103696  int isThreadsafe;
103697
103698  *ppDb = 0;
103699#ifndef SQLITE_OMIT_AUTOINIT
103700  rc = sqlite3_initialize();
103701  if( rc ) return rc;
103702#endif
103703
103704  if( sqlite3GlobalConfig.bCoreMutex==0 ){
103705    isThreadsafe = 0;
103706  }else if( flags & SQLITE_OPEN_NOMUTEX ){
103707    isThreadsafe = 0;
103708  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
103709    isThreadsafe = 1;
103710  }else{
103711    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
103712  }
103713  if( flags & SQLITE_OPEN_PRIVATECACHE ){
103714    flags &= ~SQLITE_OPEN_SHAREDCACHE;
103715  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
103716    flags |= SQLITE_OPEN_SHAREDCACHE;
103717  }
103718
103719  /* Remove harmful bits from the flags parameter
103720  **
103721  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
103722  ** dealt with in the previous code block.  Besides these, the only
103723  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
103724  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
103725  ** off all other flags.
103726  */
103727  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
103728               SQLITE_OPEN_EXCLUSIVE |
103729               SQLITE_OPEN_MAIN_DB |
103730               SQLITE_OPEN_TEMP_DB |
103731               SQLITE_OPEN_TRANSIENT_DB |
103732               SQLITE_OPEN_MAIN_JOURNAL |
103733               SQLITE_OPEN_TEMP_JOURNAL |
103734               SQLITE_OPEN_SUBJOURNAL |
103735               SQLITE_OPEN_MASTER_JOURNAL |
103736               SQLITE_OPEN_NOMUTEX |
103737               SQLITE_OPEN_FULLMUTEX
103738             );
103739
103740  /* Allocate the sqlite data structure */
103741  db = sqlite3MallocZero( sizeof(sqlite3) );
103742  if( db==0 ) goto opendb_out;
103743  if( isThreadsafe ){
103744    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
103745    if( db->mutex==0 ){
103746      sqlite3_free(db);
103747      db = 0;
103748      goto opendb_out;
103749    }
103750  }
103751  sqlite3_mutex_enter(db->mutex);
103752  db->errMask = 0xff;
103753  db->nDb = 2;
103754  db->magic = SQLITE_MAGIC_BUSY;
103755  db->aDb = db->aDbStatic;
103756
103757  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
103758  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
103759  db->autoCommit = 1;
103760  db->nextAutovac = -1;
103761  db->nextPagesize = 0;
103762  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
103763#if SQLITE_DEFAULT_FILE_FORMAT<4
103764                 | SQLITE_LegacyFileFmt
103765#endif
103766#ifdef SQLITE_ENABLE_LOAD_EXTENSION
103767                 | SQLITE_LoadExtension
103768#endif
103769#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
103770                 | SQLITE_RecTriggers
103771#endif
103772      ;
103773  sqlite3HashInit(&db->aCollSeq);
103774#ifndef SQLITE_OMIT_VIRTUALTABLE
103775  sqlite3HashInit(&db->aModule);
103776#endif
103777
103778  db->pVfs = sqlite3_vfs_find(zVfs);
103779  if( !db->pVfs ){
103780    rc = SQLITE_ERROR;
103781    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
103782    goto opendb_out;
103783  }
103784
103785  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
103786  ** and UTF-16, so add a version for each to avoid any unnecessary
103787  ** conversions. The only error that can occur here is a malloc() failure.
103788  */
103789  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
103790                  binCollFunc, 0);
103791  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
103792                  binCollFunc, 0);
103793  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
103794                  binCollFunc, 0);
103795  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
103796                  binCollFunc, 0);
103797  if( db->mallocFailed ){
103798    goto opendb_out;
103799  }
103800  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
103801  assert( db->pDfltColl!=0 );
103802
103803  /* Also add a UTF-8 case-insensitive collation sequence. */
103804  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
103805                  nocaseCollatingFunc, 0);
103806
103807  /* Open the backend database driver */
103808  db->openFlags = flags;
103809  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
103810                           flags | SQLITE_OPEN_MAIN_DB,
103811                           &db->aDb[0].pBt);
103812  if( rc!=SQLITE_OK ){
103813    if( rc==SQLITE_IOERR_NOMEM ){
103814      rc = SQLITE_NOMEM;
103815    }
103816    sqlite3Error(db, rc, 0);
103817    goto opendb_out;
103818  }
103819  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
103820  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
103821
103822
103823  /* The default safety_level for the main database is 'full'; for the temp
103824  ** database it is 'NONE'. This matches the pager layer defaults.
103825  */
103826  db->aDb[0].zName = "main";
103827  db->aDb[0].safety_level = 3;
103828  db->aDb[1].zName = "temp";
103829  db->aDb[1].safety_level = 1;
103830
103831  db->magic = SQLITE_MAGIC_OPEN;
103832  if( db->mallocFailed ){
103833    goto opendb_out;
103834  }
103835
103836  /* Register all built-in functions, but do not attempt to read the
103837  ** database schema yet. This is delayed until the first time the database
103838  ** is accessed.
103839  */
103840  sqlite3Error(db, SQLITE_OK, 0);
103841  sqlite3RegisterBuiltinFunctions(db);
103842
103843  /* Load automatic extensions - extensions that have been registered
103844  ** using the sqlite3_automatic_extension() API.
103845  */
103846  sqlite3AutoLoadExtensions(db);
103847  rc = sqlite3_errcode(db);
103848  if( rc!=SQLITE_OK ){
103849    goto opendb_out;
103850  }
103851
103852#ifdef SQLITE_ENABLE_FTS1
103853  if( !db->mallocFailed ){
103854    extern int sqlite3Fts1Init(sqlite3*);
103855    rc = sqlite3Fts1Init(db);
103856  }
103857#endif
103858
103859#ifdef SQLITE_ENABLE_FTS2
103860  if( !db->mallocFailed && rc==SQLITE_OK ){
103861    extern int sqlite3Fts2Init(sqlite3*);
103862    rc = sqlite3Fts2Init(db);
103863  }
103864#endif
103865
103866#ifdef SQLITE_ENABLE_FTS3
103867  // Begin Android change
103868  #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
103869    /* Also register as fts1 and fts2, for backwards compatability on
103870    ** systems known to have never seen a pre-fts3 database.
103871    */
103872    if( !db->mallocFailed && rc==SQLITE_OK ){
103873      rc = sqlite3Fts3Init(db, "fts1");
103874    }
103875
103876    if( !db->mallocFailed && rc==SQLITE_OK ){
103877      rc = sqlite3Fts3Init(db, "fts2");
103878    }
103879  #endif
103880
103881    if( !db->mallocFailed && rc==SQLITE_OK ){
103882      rc = sqlite3Fts3Init(db, "fts3");
103883    }
103884  // End Android change
103885#endif
103886
103887#ifdef SQLITE_ENABLE_ICU
103888  if( !db->mallocFailed && rc==SQLITE_OK ){
103889    rc = sqlite3IcuInit(db);
103890  }
103891#endif
103892
103893#ifdef SQLITE_ENABLE_RTREE
103894  if( !db->mallocFailed && rc==SQLITE_OK){
103895    rc = sqlite3RtreeInit(db);
103896  }
103897#endif
103898
103899  sqlite3Error(db, rc, 0);
103900
103901  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
103902  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
103903  ** mode.  Doing nothing at all also makes NORMAL the default.
103904  */
103905#ifdef SQLITE_DEFAULT_LOCKING_MODE
103906  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
103907  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
103908                          SQLITE_DEFAULT_LOCKING_MODE);
103909#endif
103910
103911  /* Enable the lookaside-malloc subsystem */
103912  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
103913                        sqlite3GlobalConfig.nLookaside);
103914
103915  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
103916
103917opendb_out:
103918  if( db ){
103919    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
103920    sqlite3_mutex_leave(db->mutex);
103921  }
103922  rc = sqlite3_errcode(db);
103923  if( rc==SQLITE_NOMEM ){
103924    sqlite3_close(db);
103925    db = 0;
103926  }else if( rc!=SQLITE_OK ){
103927    db->magic = SQLITE_MAGIC_SICK;
103928  }
103929  *ppDb = db;
103930  return sqlite3ApiExit(0, rc);
103931}
103932
103933/*
103934** Open a new database handle.
103935*/
103936SQLITE_API int sqlite3_open(
103937  const char *zFilename,
103938  sqlite3 **ppDb
103939){
103940  return openDatabase(zFilename, ppDb,
103941                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
103942}
103943SQLITE_API int sqlite3_open_v2(
103944  const char *filename,   /* Database filename (UTF-8) */
103945  sqlite3 **ppDb,         /* OUT: SQLite db handle */
103946  int flags,              /* Flags */
103947  const char *zVfs        /* Name of VFS module to use */
103948){
103949  return openDatabase(filename, ppDb, flags, zVfs);
103950}
103951
103952#ifndef SQLITE_OMIT_UTF16
103953/*
103954** Open a new database handle.
103955*/
103956SQLITE_API int sqlite3_open16(
103957  const void *zFilename,
103958  sqlite3 **ppDb
103959){
103960  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
103961  sqlite3_value *pVal;
103962  int rc;
103963
103964  assert( zFilename );
103965  assert( ppDb );
103966  *ppDb = 0;
103967#ifndef SQLITE_OMIT_AUTOINIT
103968  rc = sqlite3_initialize();
103969  if( rc ) return rc;
103970#endif
103971  pVal = sqlite3ValueNew(0);
103972  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
103973  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
103974  if( zFilename8 ){
103975    rc = openDatabase(zFilename8, ppDb,
103976                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
103977    assert( *ppDb || rc==SQLITE_NOMEM );
103978    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
103979      ENC(*ppDb) = SQLITE_UTF16NATIVE;
103980    }
103981  }else{
103982    rc = SQLITE_NOMEM;
103983  }
103984  sqlite3ValueFree(pVal);
103985
103986  return sqlite3ApiExit(0, rc);
103987}
103988#endif /* SQLITE_OMIT_UTF16 */
103989
103990/*
103991** Register a new collation sequence with the database handle db.
103992*/
103993SQLITE_API int sqlite3_create_collation(
103994  sqlite3* db,
103995  const char *zName,
103996  int enc,
103997  void* pCtx,
103998  int(*xCompare)(void*,int,const void*,int,const void*)
103999){
104000  int rc;
104001  sqlite3_mutex_enter(db->mutex);
104002  assert( !db->mallocFailed );
104003  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104004  rc = sqlite3ApiExit(db, rc);
104005  sqlite3_mutex_leave(db->mutex);
104006  return rc;
104007}
104008
104009/*
104010** Register a new collation sequence with the database handle db.
104011*/
104012SQLITE_API int sqlite3_create_collation_v2(
104013  sqlite3* db,
104014  const char *zName,
104015  int enc,
104016  void* pCtx,
104017  int(*xCompare)(void*,int,const void*,int,const void*),
104018  void(*xDel)(void*)
104019){
104020  int rc;
104021  sqlite3_mutex_enter(db->mutex);
104022  assert( !db->mallocFailed );
104023  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
104024  rc = sqlite3ApiExit(db, rc);
104025  sqlite3_mutex_leave(db->mutex);
104026  return rc;
104027}
104028
104029#ifndef SQLITE_OMIT_UTF16
104030/*
104031** Register a new collation sequence with the database handle db.
104032*/
104033SQLITE_API int sqlite3_create_collation16(
104034  sqlite3* db,
104035  const void *zName,
104036  int enc,
104037  void* pCtx,
104038  int(*xCompare)(void*,int,const void*,int,const void*)
104039){
104040  int rc = SQLITE_OK;
104041  char *zName8;
104042  sqlite3_mutex_enter(db->mutex);
104043  assert( !db->mallocFailed );
104044  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
104045  if( zName8 ){
104046    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104047    sqlite3DbFree(db, zName8);
104048  }
104049  rc = sqlite3ApiExit(db, rc);
104050  sqlite3_mutex_leave(db->mutex);
104051  return rc;
104052}
104053#endif /* SQLITE_OMIT_UTF16 */
104054
104055/*
104056** Register a collation sequence factory callback with the database handle
104057** db. Replace any previously installed collation sequence factory.
104058*/
104059SQLITE_API int sqlite3_collation_needed(
104060  sqlite3 *db,
104061  void *pCollNeededArg,
104062  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
104063){
104064  sqlite3_mutex_enter(db->mutex);
104065  db->xCollNeeded = xCollNeeded;
104066  db->xCollNeeded16 = 0;
104067  db->pCollNeededArg = pCollNeededArg;
104068  sqlite3_mutex_leave(db->mutex);
104069  return SQLITE_OK;
104070}
104071
104072#ifndef SQLITE_OMIT_UTF16
104073/*
104074** Register a collation sequence factory callback with the database handle
104075** db. Replace any previously installed collation sequence factory.
104076*/
104077SQLITE_API int sqlite3_collation_needed16(
104078  sqlite3 *db,
104079  void *pCollNeededArg,
104080  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
104081){
104082  sqlite3_mutex_enter(db->mutex);
104083  db->xCollNeeded = 0;
104084  db->xCollNeeded16 = xCollNeeded16;
104085  db->pCollNeededArg = pCollNeededArg;
104086  sqlite3_mutex_leave(db->mutex);
104087  return SQLITE_OK;
104088}
104089#endif /* SQLITE_OMIT_UTF16 */
104090
104091#ifndef SQLITE_OMIT_GLOBALRECOVER
104092#ifndef SQLITE_OMIT_DEPRECATED
104093/*
104094** This function is now an anachronism. It used to be used to recover from a
104095** malloc() failure, but SQLite now does this automatically.
104096*/
104097SQLITE_API int sqlite3_global_recover(void){
104098  return SQLITE_OK;
104099}
104100#endif
104101#endif
104102
104103/*
104104** Test to see whether or not the database connection is in autocommit
104105** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
104106** by default.  Autocommit is disabled by a BEGIN statement and reenabled
104107** by the next COMMIT or ROLLBACK.
104108**
104109******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
104110*/
104111SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
104112  return db->autoCommit;
104113}
104114
104115/*
104116** The following routines are subtitutes for constants SQLITE_CORRUPT,
104117** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
104118** constants.  They server two purposes:
104119**
104120**   1.  Serve as a convenient place to set a breakpoint in a debugger
104121**       to detect when version error conditions occurs.
104122**
104123**   2.  Invoke sqlite3_log() to provide the source code location where
104124**       a low-level error is first detected.
104125*/
104126SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
104127  testcase( sqlite3GlobalConfig.xLog!=0 );
104128  sqlite3_log(SQLITE_CORRUPT,
104129              "database corruption at line %d of [%.10s]",
104130              lineno, 20+sqlite3_sourceid());
104131  return SQLITE_CORRUPT;
104132}
104133SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
104134  testcase( sqlite3GlobalConfig.xLog!=0 );
104135  sqlite3_log(SQLITE_MISUSE,
104136              "misuse at line %d of [%.10s]",
104137              lineno, 20+sqlite3_sourceid());
104138  return SQLITE_MISUSE;
104139}
104140SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
104141  testcase( sqlite3GlobalConfig.xLog!=0 );
104142  sqlite3_log(SQLITE_CANTOPEN,
104143              "cannot open file at line %d of [%.10s]",
104144              lineno, 20+sqlite3_sourceid());
104145  return SQLITE_CANTOPEN;
104146}
104147
104148
104149#ifndef SQLITE_OMIT_DEPRECATED
104150/*
104151** This is a convenience routine that makes sure that all thread-specific
104152** data for this thread has been deallocated.
104153**
104154** SQLite no longer uses thread-specific data so this routine is now a
104155** no-op.  It is retained for historical compatibility.
104156*/
104157SQLITE_API void sqlite3_thread_cleanup(void){
104158}
104159#endif
104160
104161/*
104162** Return meta information about a specific column of a database table.
104163** See comment in sqlite3.h (sqlite.h.in) for details.
104164*/
104165#ifdef SQLITE_ENABLE_COLUMN_METADATA
104166SQLITE_API int sqlite3_table_column_metadata(
104167  sqlite3 *db,                /* Connection handle */
104168  const char *zDbName,        /* Database name or NULL */
104169  const char *zTableName,     /* Table name */
104170  const char *zColumnName,    /* Column name */
104171  char const **pzDataType,    /* OUTPUT: Declared data type */
104172  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
104173  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
104174  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
104175  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
104176){
104177  int rc;
104178  char *zErrMsg = 0;
104179  Table *pTab = 0;
104180  Column *pCol = 0;
104181  int iCol;
104182
104183  char const *zDataType = 0;
104184  char const *zCollSeq = 0;
104185  int notnull = 0;
104186  int primarykey = 0;
104187  int autoinc = 0;
104188
104189  /* Ensure the database schema has been loaded */
104190  sqlite3_mutex_enter(db->mutex);
104191  sqlite3BtreeEnterAll(db);
104192  rc = sqlite3Init(db, &zErrMsg);
104193  if( SQLITE_OK!=rc ){
104194    goto error_out;
104195  }
104196
104197  /* Locate the table in question */
104198  pTab = sqlite3FindTable(db, zTableName, zDbName);
104199  if( !pTab || pTab->pSelect ){
104200    pTab = 0;
104201    goto error_out;
104202  }
104203
104204  /* Find the column for which info is requested */
104205  if( sqlite3IsRowid(zColumnName) ){
104206    iCol = pTab->iPKey;
104207    if( iCol>=0 ){
104208      pCol = &pTab->aCol[iCol];
104209    }
104210  }else{
104211    for(iCol=0; iCol<pTab->nCol; iCol++){
104212      pCol = &pTab->aCol[iCol];
104213      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
104214        break;
104215      }
104216    }
104217    if( iCol==pTab->nCol ){
104218      pTab = 0;
104219      goto error_out;
104220    }
104221  }
104222
104223  /* The following block stores the meta information that will be returned
104224  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
104225  ** and autoinc. At this point there are two possibilities:
104226  **
104227  **     1. The specified column name was rowid", "oid" or "_rowid_"
104228  **        and there is no explicitly declared IPK column.
104229  **
104230  **     2. The table is not a view and the column name identified an
104231  **        explicitly declared column. Copy meta information from *pCol.
104232  */
104233  if( pCol ){
104234    zDataType = pCol->zType;
104235    zCollSeq = pCol->zColl;
104236    notnull = pCol->notNull!=0;
104237    primarykey  = pCol->isPrimKey!=0;
104238    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
104239  }else{
104240    zDataType = "INTEGER";
104241    primarykey = 1;
104242  }
104243  if( !zCollSeq ){
104244    zCollSeq = "BINARY";
104245  }
104246
104247error_out:
104248  sqlite3BtreeLeaveAll(db);
104249
104250  /* Whether the function call succeeded or failed, set the output parameters
104251  ** to whatever their local counterparts contain. If an error did occur,
104252  ** this has the effect of zeroing all output parameters.
104253  */
104254  if( pzDataType ) *pzDataType = zDataType;
104255  if( pzCollSeq ) *pzCollSeq = zCollSeq;
104256  if( pNotNull ) *pNotNull = notnull;
104257  if( pPrimaryKey ) *pPrimaryKey = primarykey;
104258  if( pAutoinc ) *pAutoinc = autoinc;
104259
104260  if( SQLITE_OK==rc && !pTab ){
104261    sqlite3DbFree(db, zErrMsg);
104262    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
104263        zColumnName);
104264    rc = SQLITE_ERROR;
104265  }
104266  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
104267  sqlite3DbFree(db, zErrMsg);
104268  rc = sqlite3ApiExit(db, rc);
104269  sqlite3_mutex_leave(db->mutex);
104270  return rc;
104271}
104272#endif
104273
104274/*
104275** Sleep for a little while.  Return the amount of time slept.
104276*/
104277SQLITE_API int sqlite3_sleep(int ms){
104278  sqlite3_vfs *pVfs;
104279  int rc;
104280  pVfs = sqlite3_vfs_find(0);
104281  if( pVfs==0 ) return 0;
104282
104283  /* This function works in milliseconds, but the underlying OsSleep()
104284  ** API uses microseconds. Hence the 1000's.
104285  */
104286  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
104287  return rc;
104288}
104289
104290/*
104291** Enable or disable the extended result codes.
104292*/
104293SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
104294  sqlite3_mutex_enter(db->mutex);
104295  db->errMask = onoff ? 0xffffffff : 0xff;
104296  sqlite3_mutex_leave(db->mutex);
104297  return SQLITE_OK;
104298}
104299
104300/*
104301** Invoke the xFileControl method on a particular database.
104302*/
104303SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
104304  int rc = SQLITE_ERROR;
104305  int iDb;
104306  sqlite3_mutex_enter(db->mutex);
104307  if( zDbName==0 ){
104308    iDb = 0;
104309  }else{
104310    for(iDb=0; iDb<db->nDb; iDb++){
104311      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
104312    }
104313  }
104314  if( iDb<db->nDb ){
104315    Btree *pBtree = db->aDb[iDb].pBt;
104316    if( pBtree ){
104317      Pager *pPager;
104318      sqlite3_file *fd;
104319      sqlite3BtreeEnter(pBtree);
104320      pPager = sqlite3BtreePager(pBtree);
104321      assert( pPager!=0 );
104322      fd = sqlite3PagerFile(pPager);
104323      assert( fd!=0 );
104324      if( fd->pMethods ){
104325        rc = sqlite3OsFileControl(fd, op, pArg);
104326      }
104327      sqlite3BtreeLeave(pBtree);
104328    }
104329  }
104330  sqlite3_mutex_leave(db->mutex);
104331  return rc;
104332}
104333
104334/*
104335** Interface to the testing logic.
104336*/
104337SQLITE_API int sqlite3_test_control(int op, ...){
104338  int rc = 0;
104339#ifndef SQLITE_OMIT_BUILTIN_TEST
104340  va_list ap;
104341  va_start(ap, op);
104342  switch( op ){
104343
104344    /*
104345    ** Save the current state of the PRNG.
104346    */
104347    case SQLITE_TESTCTRL_PRNG_SAVE: {
104348      sqlite3PrngSaveState();
104349      break;
104350    }
104351
104352    /*
104353    ** Restore the state of the PRNG to the last state saved using
104354    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
104355    ** this verb acts like PRNG_RESET.
104356    */
104357    case SQLITE_TESTCTRL_PRNG_RESTORE: {
104358      sqlite3PrngRestoreState();
104359      break;
104360    }
104361
104362    /*
104363    ** Reset the PRNG back to its uninitialized state.  The next call
104364    ** to sqlite3_randomness() will reseed the PRNG using a single call
104365    ** to the xRandomness method of the default VFS.
104366    */
104367    case SQLITE_TESTCTRL_PRNG_RESET: {
104368      sqlite3PrngResetState();
104369      break;
104370    }
104371
104372    /*
104373    **  sqlite3_test_control(BITVEC_TEST, size, program)
104374    **
104375    ** Run a test against a Bitvec object of size.  The program argument
104376    ** is an array of integers that defines the test.  Return -1 on a
104377    ** memory allocation error, 0 on success, or non-zero for an error.
104378    ** See the sqlite3BitvecBuiltinTest() for additional information.
104379    */
104380    case SQLITE_TESTCTRL_BITVEC_TEST: {
104381      int sz = va_arg(ap, int);
104382      int *aProg = va_arg(ap, int*);
104383      rc = sqlite3BitvecBuiltinTest(sz, aProg);
104384      break;
104385    }
104386
104387    /*
104388    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
104389    **
104390    ** Register hooks to call to indicate which malloc() failures
104391    ** are benign.
104392    */
104393    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
104394      typedef void (*void_function)(void);
104395      void_function xBenignBegin;
104396      void_function xBenignEnd;
104397      xBenignBegin = va_arg(ap, void_function);
104398      xBenignEnd = va_arg(ap, void_function);
104399      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
104400      break;
104401    }
104402
104403    /*
104404    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
104405    **
104406    ** Set the PENDING byte to the value in the argument, if X>0.
104407    ** Make no changes if X==0.  Return the value of the pending byte
104408    ** as it existing before this routine was called.
104409    **
104410    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
104411    ** an incompatible database file format.  Changing the PENDING byte
104412    ** while any database connection is open results in undefined and
104413    ** dileterious behavior.
104414    */
104415    case SQLITE_TESTCTRL_PENDING_BYTE: {
104416      rc = PENDING_BYTE;
104417#ifndef SQLITE_OMIT_WSD
104418      {
104419        unsigned int newVal = va_arg(ap, unsigned int);
104420        if( newVal ) sqlite3PendingByte = newVal;
104421      }
104422#endif
104423      break;
104424    }
104425
104426    /*
104427    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
104428    **
104429    ** This action provides a run-time test to see whether or not
104430    ** assert() was enabled at compile-time.  If X is true and assert()
104431    ** is enabled, then the return value is true.  If X is true and
104432    ** assert() is disabled, then the return value is zero.  If X is
104433    ** false and assert() is enabled, then the assertion fires and the
104434    ** process aborts.  If X is false and assert() is disabled, then the
104435    ** return value is zero.
104436    */
104437    case SQLITE_TESTCTRL_ASSERT: {
104438      volatile int x = 0;
104439      assert( (x = va_arg(ap,int))!=0 );
104440      rc = x;
104441      break;
104442    }
104443
104444
104445    /*
104446    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
104447    **
104448    ** This action provides a run-time test to see how the ALWAYS and
104449    ** NEVER macros were defined at compile-time.
104450    **
104451    ** The return value is ALWAYS(X).
104452    **
104453    ** The recommended test is X==2.  If the return value is 2, that means
104454    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
104455    ** default setting.  If the return value is 1, then ALWAYS() is either
104456    ** hard-coded to true or else it asserts if its argument is false.
104457    ** The first behavior (hard-coded to true) is the case if
104458    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
104459    ** behavior (assert if the argument to ALWAYS() is false) is the case if
104460    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
104461    **
104462    ** The run-time test procedure might look something like this:
104463    **
104464    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
104465    **      // ALWAYS() and NEVER() are no-op pass-through macros
104466    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
104467    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
104468    **    }else{
104469    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
104470    **    }
104471    */
104472    case SQLITE_TESTCTRL_ALWAYS: {
104473      int x = va_arg(ap,int);
104474      rc = ALWAYS(x);
104475      break;
104476    }
104477
104478    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
104479    **
104480    ** Set the nReserve size to N for the main database on the database
104481    ** connection db.
104482    */
104483    case SQLITE_TESTCTRL_RESERVE: {
104484      sqlite3 *db = va_arg(ap, sqlite3*);
104485      int x = va_arg(ap,int);
104486      sqlite3_mutex_enter(db->mutex);
104487      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
104488      sqlite3_mutex_leave(db->mutex);
104489      break;
104490    }
104491
104492    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
104493    **
104494    ** Enable or disable various optimizations for testing purposes.  The
104495    ** argument N is a bitmask of optimizations to be disabled.  For normal
104496    ** operation N should be 0.  The idea is that a test program (like the
104497    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
104498    ** with various optimizations disabled to verify that the same answer
104499    ** is obtained in every case.
104500    */
104501    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
104502      sqlite3 *db = va_arg(ap, sqlite3*);
104503      int x = va_arg(ap,int);
104504      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
104505      break;
104506    }
104507
104508#ifdef SQLITE_N_KEYWORD
104509    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
104510    **
104511    ** If zWord is a keyword recognized by the parser, then return the
104512    ** number of keywords.  Or if zWord is not a keyword, return 0.
104513    **
104514    ** This test feature is only available in the amalgamation since
104515    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
104516    ** is built using separate source files.
104517    */
104518    case SQLITE_TESTCTRL_ISKEYWORD: {
104519      const char *zWord = va_arg(ap, const char*);
104520      int n = sqlite3Strlen30(zWord);
104521      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
104522      break;
104523    }
104524#endif
104525
104526    /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
104527    **
104528    ** Return the size of a pcache header in bytes.
104529    */
104530    case SQLITE_TESTCTRL_PGHDRSZ: {
104531      rc = sizeof(PgHdr);
104532      break;
104533    }
104534
104535  }
104536  va_end(ap);
104537#endif /* SQLITE_OMIT_BUILTIN_TEST */
104538  return rc;
104539}
104540
104541/************** End of main.c ************************************************/
104542/************** Begin file notify.c ******************************************/
104543/*
104544** 2009 March 3
104545**
104546** The author disclaims copyright to this source code.  In place of
104547** a legal notice, here is a blessing:
104548**
104549**    May you do good and not evil.
104550**    May you find forgiveness for yourself and forgive others.
104551**    May you share freely, never taking more than you give.
104552**
104553*************************************************************************
104554**
104555** This file contains the implementation of the sqlite3_unlock_notify()
104556** API method and its associated functionality.
104557*/
104558
104559/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
104560#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
104561
104562/*
104563** Public interfaces:
104564**
104565**   sqlite3ConnectionBlocked()
104566**   sqlite3ConnectionUnlocked()
104567**   sqlite3ConnectionClosed()
104568**   sqlite3_unlock_notify()
104569*/
104570
104571#define assertMutexHeld() \
104572  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
104573
104574/*
104575** Head of a linked list of all sqlite3 objects created by this process
104576** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
104577** is not NULL. This variable may only accessed while the STATIC_MASTER
104578** mutex is held.
104579*/
104580static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
104581
104582#ifndef NDEBUG
104583/*
104584** This function is a complex assert() that verifies the following
104585** properties of the blocked connections list:
104586**
104587**   1) Each entry in the list has a non-NULL value for either
104588**      pUnlockConnection or pBlockingConnection, or both.
104589**
104590**   2) All entries in the list that share a common value for
104591**      xUnlockNotify are grouped together.
104592**
104593**   3) If the argument db is not NULL, then none of the entries in the
104594**      blocked connections list have pUnlockConnection or pBlockingConnection
104595**      set to db. This is used when closing connection db.
104596*/
104597static void checkListProperties(sqlite3 *db){
104598  sqlite3 *p;
104599  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
104600    int seen = 0;
104601    sqlite3 *p2;
104602
104603    /* Verify property (1) */
104604    assert( p->pUnlockConnection || p->pBlockingConnection );
104605
104606    /* Verify property (2) */
104607    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
104608      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
104609      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
104610      assert( db==0 || p->pUnlockConnection!=db );
104611      assert( db==0 || p->pBlockingConnection!=db );
104612    }
104613  }
104614}
104615#else
104616# define checkListProperties(x)
104617#endif
104618
104619/*
104620** Remove connection db from the blocked connections list. If connection
104621** db is not currently a part of the list, this function is a no-op.
104622*/
104623static void removeFromBlockedList(sqlite3 *db){
104624  sqlite3 **pp;
104625  assertMutexHeld();
104626  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
104627    if( *pp==db ){
104628      *pp = (*pp)->pNextBlocked;
104629      break;
104630    }
104631  }
104632}
104633
104634/*
104635** Add connection db to the blocked connections list. It is assumed
104636** that it is not already a part of the list.
104637*/
104638static void addToBlockedList(sqlite3 *db){
104639  sqlite3 **pp;
104640  assertMutexHeld();
104641  for(
104642    pp=&sqlite3BlockedList;
104643    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
104644    pp=&(*pp)->pNextBlocked
104645  );
104646  db->pNextBlocked = *pp;
104647  *pp = db;
104648}
104649
104650/*
104651** Obtain the STATIC_MASTER mutex.
104652*/
104653static void enterMutex(void){
104654  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
104655  checkListProperties(0);
104656}
104657
104658/*
104659** Release the STATIC_MASTER mutex.
104660*/
104661static void leaveMutex(void){
104662  assertMutexHeld();
104663  checkListProperties(0);
104664  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
104665}
104666
104667/*
104668** Register an unlock-notify callback.
104669**
104670** This is called after connection "db" has attempted some operation
104671** but has received an SQLITE_LOCKED error because another connection
104672** (call it pOther) in the same process was busy using the same shared
104673** cache.  pOther is found by looking at db->pBlockingConnection.
104674**
104675** If there is no blocking connection, the callback is invoked immediately,
104676** before this routine returns.
104677**
104678** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
104679** a deadlock.
104680**
104681** Otherwise, make arrangements to invoke xNotify when pOther drops
104682** its locks.
104683**
104684** Each call to this routine overrides any prior callbacks registered
104685** on the same "db".  If xNotify==0 then any prior callbacks are immediately
104686** cancelled.
104687*/
104688SQLITE_API int sqlite3_unlock_notify(
104689  sqlite3 *db,
104690  void (*xNotify)(void **, int),
104691  void *pArg
104692){
104693  int rc = SQLITE_OK;
104694
104695  sqlite3_mutex_enter(db->mutex);
104696  enterMutex();
104697
104698  if( xNotify==0 ){
104699    removeFromBlockedList(db);
104700    db->pBlockingConnection = 0;
104701    db->pUnlockConnection = 0;
104702    db->xUnlockNotify = 0;
104703    db->pUnlockArg = 0;
104704  }else if( 0==db->pBlockingConnection ){
104705    /* The blocking transaction has been concluded. Or there never was a
104706    ** blocking transaction. In either case, invoke the notify callback
104707    ** immediately.
104708    */
104709    xNotify(&pArg, 1);
104710  }else{
104711    sqlite3 *p;
104712
104713    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
104714    if( p ){
104715      rc = SQLITE_LOCKED;              /* Deadlock detected. */
104716    }else{
104717      db->pUnlockConnection = db->pBlockingConnection;
104718      db->xUnlockNotify = xNotify;
104719      db->pUnlockArg = pArg;
104720      removeFromBlockedList(db);
104721      addToBlockedList(db);
104722    }
104723  }
104724
104725  leaveMutex();
104726  assert( !db->mallocFailed );
104727  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
104728  sqlite3_mutex_leave(db->mutex);
104729  return rc;
104730}
104731
104732/*
104733** This function is called while stepping or preparing a statement
104734** associated with connection db. The operation will return SQLITE_LOCKED
104735** to the user because it requires a lock that will not be available
104736** until connection pBlocker concludes its current transaction.
104737*/
104738SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
104739  enterMutex();
104740  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
104741    addToBlockedList(db);
104742  }
104743  db->pBlockingConnection = pBlocker;
104744  leaveMutex();
104745}
104746
104747/*
104748** This function is called when
104749** the transaction opened by database db has just finished. Locks held
104750** by database connection db have been released.
104751**
104752** This function loops through each entry in the blocked connections
104753** list and does the following:
104754**
104755**   1) If the sqlite3.pBlockingConnection member of a list entry is
104756**      set to db, then set pBlockingConnection=0.
104757**
104758**   2) If the sqlite3.pUnlockConnection member of a list entry is
104759**      set to db, then invoke the configured unlock-notify callback and
104760**      set pUnlockConnection=0.
104761**
104762**   3) If the two steps above mean that pBlockingConnection==0 and
104763**      pUnlockConnection==0, remove the entry from the blocked connections
104764**      list.
104765*/
104766SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
104767  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
104768  int nArg = 0;                            /* Number of entries in aArg[] */
104769  sqlite3 **pp;                            /* Iterator variable */
104770  void **aArg;               /* Arguments to the unlock callback */
104771  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
104772  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
104773
104774  aArg = aStatic;
104775  enterMutex();         /* Enter STATIC_MASTER mutex */
104776
104777  /* This loop runs once for each entry in the blocked-connections list. */
104778  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
104779    sqlite3 *p = *pp;
104780
104781    /* Step 1. */
104782    if( p->pBlockingConnection==db ){
104783      p->pBlockingConnection = 0;
104784    }
104785
104786    /* Step 2. */
104787    if( p->pUnlockConnection==db ){
104788      assert( p->xUnlockNotify );
104789      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
104790        xUnlockNotify(aArg, nArg);
104791        nArg = 0;
104792      }
104793
104794      sqlite3BeginBenignMalloc();
104795      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
104796      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
104797      if( (!aDyn && nArg==(int)ArraySize(aStatic))
104798       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
104799      ){
104800        /* The aArg[] array needs to grow. */
104801        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
104802        if( pNew ){
104803          memcpy(pNew, aArg, nArg*sizeof(void *));
104804          sqlite3_free(aDyn);
104805          aDyn = aArg = pNew;
104806        }else{
104807          /* This occurs when the array of context pointers that need to
104808          ** be passed to the unlock-notify callback is larger than the
104809          ** aStatic[] array allocated on the stack and the attempt to
104810          ** allocate a larger array from the heap has failed.
104811          **
104812          ** This is a difficult situation to handle. Returning an error
104813          ** code to the caller is insufficient, as even if an error code
104814          ** is returned the transaction on connection db will still be
104815          ** closed and the unlock-notify callbacks on blocked connections
104816          ** will go unissued. This might cause the application to wait
104817          ** indefinitely for an unlock-notify callback that will never
104818          ** arrive.
104819          **
104820          ** Instead, invoke the unlock-notify callback with the context
104821          ** array already accumulated. We can then clear the array and
104822          ** begin accumulating any further context pointers without
104823          ** requiring any dynamic allocation. This is sub-optimal because
104824          ** it means that instead of one callback with a large array of
104825          ** context pointers the application will receive two or more
104826          ** callbacks with smaller arrays of context pointers, which will
104827          ** reduce the applications ability to prioritize multiple
104828          ** connections. But it is the best that can be done under the
104829          ** circumstances.
104830          */
104831          xUnlockNotify(aArg, nArg);
104832          nArg = 0;
104833        }
104834      }
104835      sqlite3EndBenignMalloc();
104836
104837      aArg[nArg++] = p->pUnlockArg;
104838      xUnlockNotify = p->xUnlockNotify;
104839      p->pUnlockConnection = 0;
104840      p->xUnlockNotify = 0;
104841      p->pUnlockArg = 0;
104842    }
104843
104844    /* Step 3. */
104845    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
104846      /* Remove connection p from the blocked connections list. */
104847      *pp = p->pNextBlocked;
104848      p->pNextBlocked = 0;
104849    }else{
104850      pp = &p->pNextBlocked;
104851    }
104852  }
104853
104854  if( nArg!=0 ){
104855    xUnlockNotify(aArg, nArg);
104856  }
104857  sqlite3_free(aDyn);
104858  leaveMutex();         /* Leave STATIC_MASTER mutex */
104859}
104860
104861/*
104862** This is called when the database connection passed as an argument is
104863** being closed. The connection is removed from the blocked list.
104864*/
104865SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
104866  sqlite3ConnectionUnlocked(db);
104867  enterMutex();
104868  removeFromBlockedList(db);
104869  checkListProperties(db);
104870  leaveMutex();
104871}
104872#endif
104873
104874/************** End of notify.c **********************************************/
104875/************** Begin file fts3.c ********************************************/
104876/*
104877** 2006 Oct 10
104878**
104879** The author disclaims copyright to this source code.  In place of
104880** a legal notice, here is a blessing:
104881**
104882**    May you do good and not evil.
104883**    May you find forgiveness for yourself and forgive others.
104884**    May you share freely, never taking more than you give.
104885**
104886******************************************************************************
104887**
104888** This is an SQLite module implementing full-text search.
104889*/
104890
104891/*
104892** The code in this file is only compiled if:
104893**
104894**     * The FTS3 module is being built as an extension
104895**       (in which case SQLITE_CORE is not defined), or
104896**
104897**     * The FTS3 module is being built into the core of
104898**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
104899*/
104900
104901/* The full-text index is stored in a series of b+tree (-like)
104902** structures called segments which map terms to doclists.  The
104903** structures are like b+trees in layout, but are constructed from the
104904** bottom up in optimal fashion and are not updatable.  Since trees
104905** are built from the bottom up, things will be described from the
104906** bottom up.
104907**
104908**
104909**** Varints ****
104910** The basic unit of encoding is a variable-length integer called a
104911** varint.  We encode variable-length integers in little-endian order
104912** using seven bits * per byte as follows:
104913**
104914** KEY:
104915**         A = 0xxxxxxx    7 bits of data and one flag bit
104916**         B = 1xxxxxxx    7 bits of data and one flag bit
104917**
104918**  7 bits - A
104919** 14 bits - BA
104920** 21 bits - BBA
104921** and so on.
104922**
104923** This is similar in concept to how sqlite encodes "varints" but
104924** the encoding is not the same.  SQLite varints are big-endian
104925** are are limited to 9 bytes in length whereas FTS3 varints are
104926** little-endian and can be up to 10 bytes in length (in theory).
104927**
104928** Example encodings:
104929**
104930**     1:    0x01
104931**   127:    0x7f
104932**   128:    0x81 0x00
104933**
104934**
104935**** Document lists ****
104936** A doclist (document list) holds a docid-sorted list of hits for a
104937** given term.  Doclists hold docids and associated token positions.
104938** A docid is the unique integer identifier for a single document.
104939** A position is the index of a word within the document.  The first
104940** word of the document has a position of 0.
104941**
104942** FTS3 used to optionally store character offsets using a compile-time
104943** option.  But that functionality is no longer supported.
104944**
104945** A doclist is stored like this:
104946**
104947** array {
104948**   varint docid;
104949**   array {                (position list for column 0)
104950**     varint position;     (2 more than the delta from previous position)
104951**   }
104952**   array {
104953**     varint POS_COLUMN;   (marks start of position list for new column)
104954**     varint column;       (index of new column)
104955**     array {
104956**       varint position;   (2 more than the delta from previous position)
104957**     }
104958**   }
104959**   varint POS_END;        (marks end of positions for this document.
104960** }
104961**
104962** Here, array { X } means zero or more occurrences of X, adjacent in
104963** memory.  A "position" is an index of a token in the token stream
104964** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
104965** in the same logical place as the position element, and act as sentinals
104966** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
104967** The positions numbers are not stored literally but rather as two more
104968** than the difference from the prior position, or the just the position plus
104969** 2 for the first position.  Example:
104970**
104971**   label:       A B C D E  F  G H   I  J K
104972**   value:     123 5 9 1 1 14 35 0 234 72 0
104973**
104974** The 123 value is the first docid.  For column zero in this document
104975** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
104976** at D signals the start of a new column; the 1 at E indicates that the
104977** new column is column number 1.  There are two positions at 12 and 45
104978** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
104979** 234 at I is the next docid.  It has one position 72 (72-2) and then
104980** terminates with the 0 at K.
104981**
104982** A "position-list" is the list of positions for multiple columns for
104983** a single docid.  A "column-list" is the set of positions for a single
104984** column.  Hence, a position-list consists of one or more column-lists,
104985** a document record consists of a docid followed by a position-list and
104986** a doclist consists of one or more document records.
104987**
104988** A bare doclist omits the position information, becoming an
104989** array of varint-encoded docids.
104990**
104991**** Segment leaf nodes ****
104992** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
104993** nodes are written using LeafWriter, and read using LeafReader (to
104994** iterate through a single leaf node's data) and LeavesReader (to
104995** iterate through a segment's entire leaf layer).  Leaf nodes have
104996** the format:
104997**
104998** varint iHeight;             (height from leaf level, always 0)
104999** varint nTerm;               (length of first term)
105000** char pTerm[nTerm];          (content of first term)
105001** varint nDoclist;            (length of term's associated doclist)
105002** char pDoclist[nDoclist];    (content of doclist)
105003** array {
105004**                             (further terms are delta-encoded)
105005**   varint nPrefix;           (length of prefix shared with previous term)
105006**   varint nSuffix;           (length of unshared suffix)
105007**   char pTermSuffix[nSuffix];(unshared suffix of next term)
105008**   varint nDoclist;          (length of term's associated doclist)
105009**   char pDoclist[nDoclist];  (content of doclist)
105010** }
105011**
105012** Here, array { X } means zero or more occurrences of X, adjacent in
105013** memory.
105014**
105015** Leaf nodes are broken into blocks which are stored contiguously in
105016** the %_segments table in sorted order.  This means that when the end
105017** of a node is reached, the next term is in the node with the next
105018** greater node id.
105019**
105020** New data is spilled to a new leaf node when the current node
105021** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
105022** larger than STANDALONE_MIN (default 1024) is placed in a standalone
105023** node (a leaf node with a single term and doclist).  The goal of
105024** these settings is to pack together groups of small doclists while
105025** making it efficient to directly access large doclists.  The
105026** assumption is that large doclists represent terms which are more
105027** likely to be query targets.
105028**
105029** TODO(shess) It may be useful for blocking decisions to be more
105030** dynamic.  For instance, it may make more sense to have a 2.5k leaf
105031** node rather than splitting into 2k and .5k nodes.  My intuition is
105032** that this might extend through 2x or 4x the pagesize.
105033**
105034**
105035**** Segment interior nodes ****
105036** Segment interior nodes store blockids for subtree nodes and terms
105037** to describe what data is stored by the each subtree.  Interior
105038** nodes are written using InteriorWriter, and read using
105039** InteriorReader.  InteriorWriters are created as needed when
105040** SegmentWriter creates new leaf nodes, or when an interior node
105041** itself grows too big and must be split.  The format of interior
105042** nodes:
105043**
105044** varint iHeight;           (height from leaf level, always >0)
105045** varint iBlockid;          (block id of node's leftmost subtree)
105046** optional {
105047**   varint nTerm;           (length of first term)
105048**   char pTerm[nTerm];      (content of first term)
105049**   array {
105050**                                (further terms are delta-encoded)
105051**     varint nPrefix;            (length of shared prefix with previous term)
105052**     varint nSuffix;            (length of unshared suffix)
105053**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
105054**   }
105055** }
105056**
105057** Here, optional { X } means an optional element, while array { X }
105058** means zero or more occurrences of X, adjacent in memory.
105059**
105060** An interior node encodes n terms separating n+1 subtrees.  The
105061** subtree blocks are contiguous, so only the first subtree's blockid
105062** is encoded.  The subtree at iBlockid will contain all terms less
105063** than the first term encoded (or all terms if no term is encoded).
105064** Otherwise, for terms greater than or equal to pTerm[i] but less
105065** than pTerm[i+1], the subtree for that term will be rooted at
105066** iBlockid+i.  Interior nodes only store enough term data to
105067** distinguish adjacent children (if the rightmost term of the left
105068** child is "something", and the leftmost term of the right child is
105069** "wicked", only "w" is stored).
105070**
105071** New data is spilled to a new interior node at the same height when
105072** the current node exceeds INTERIOR_MAX bytes (default 2048).
105073** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
105074** interior nodes and making the tree too skinny.  The interior nodes
105075** at a given height are naturally tracked by interior nodes at
105076** height+1, and so on.
105077**
105078**
105079**** Segment directory ****
105080** The segment directory in table %_segdir stores meta-information for
105081** merging and deleting segments, and also the root node of the
105082** segment's tree.
105083**
105084** The root node is the top node of the segment's tree after encoding
105085** the entire segment, restricted to ROOT_MAX bytes (default 1024).
105086** This could be either a leaf node or an interior node.  If the top
105087** node requires more than ROOT_MAX bytes, it is flushed to %_segments
105088** and a new root interior node is generated (which should always fit
105089** within ROOT_MAX because it only needs space for 2 varints, the
105090** height and the blockid of the previous root).
105091**
105092** The meta-information in the segment directory is:
105093**   level               - segment level (see below)
105094**   idx                 - index within level
105095**                       - (level,idx uniquely identify a segment)
105096**   start_block         - first leaf node
105097**   leaves_end_block    - last leaf node
105098**   end_block           - last block (including interior nodes)
105099**   root                - contents of root node
105100**
105101** If the root node is a leaf node, then start_block,
105102** leaves_end_block, and end_block are all 0.
105103**
105104**
105105**** Segment merging ****
105106** To amortize update costs, segments are grouped into levels and
105107** merged in batches.  Each increase in level represents exponentially
105108** more documents.
105109**
105110** New documents (actually, document updates) are tokenized and
105111** written individually (using LeafWriter) to a level 0 segment, with
105112** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
105113** level 0 segments are merged into a single level 1 segment.  Level 1
105114** is populated like level 0, and eventually MERGE_COUNT level 1
105115** segments are merged to a single level 2 segment (representing
105116** MERGE_COUNT^2 updates), and so on.
105117**
105118** A segment merge traverses all segments at a given level in
105119** parallel, performing a straightforward sorted merge.  Since segment
105120** leaf nodes are written in to the %_segments table in order, this
105121** merge traverses the underlying sqlite disk structures efficiently.
105122** After the merge, all segment blocks from the merged level are
105123** deleted.
105124**
105125** MERGE_COUNT controls how often we merge segments.  16 seems to be
105126** somewhat of a sweet spot for insertion performance.  32 and 64 show
105127** very similar performance numbers to 16 on insertion, though they're
105128** a tiny bit slower (perhaps due to more overhead in merge-time
105129** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
105130** 16, 2 about 66% slower than 16.
105131**
105132** At query time, high MERGE_COUNT increases the number of segments
105133** which need to be scanned and merged.  For instance, with 100k docs
105134** inserted:
105135**
105136**    MERGE_COUNT   segments
105137**       16           25
105138**        8           12
105139**        4           10
105140**        2            6
105141**
105142** This appears to have only a moderate impact on queries for very
105143** frequent terms (which are somewhat dominated by segment merge
105144** costs), and infrequent and non-existent terms still seem to be fast
105145** even with many segments.
105146**
105147** TODO(shess) That said, it would be nice to have a better query-side
105148** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
105149** optimizations to things like doclist merging will swing the sweet
105150** spot around.
105151**
105152**
105153**
105154**** Handling of deletions and updates ****
105155** Since we're using a segmented structure, with no docid-oriented
105156** index into the term index, we clearly cannot simply update the term
105157** index when a document is deleted or updated.  For deletions, we
105158** write an empty doclist (varint(docid) varint(POS_END)), for updates
105159** we simply write the new doclist.  Segment merges overwrite older
105160** data for a particular docid with newer data, so deletes or updates
105161** will eventually overtake the earlier data and knock it out.  The
105162** query logic likewise merges doclists so that newer data knocks out
105163** older data.
105164**
105165** TODO(shess) Provide a VACUUM type operation to clear out all
105166** deletions and duplications.  This would basically be a forced merge
105167** into a single segment.
105168*/
105169
105170#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105171
105172#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
105173# define SQLITE_CORE 1
105174#endif
105175
105176/************** Include fts3Int.h in the middle of fts3.c ********************/
105177/************** Begin file fts3Int.h *****************************************/
105178/*
105179** 2009 Nov 12
105180**
105181** The author disclaims copyright to this source code.  In place of
105182** a legal notice, here is a blessing:
105183**
105184**    May you do good and not evil.
105185**    May you find forgiveness for yourself and forgive others.
105186**    May you share freely, never taking more than you give.
105187**
105188******************************************************************************
105189**
105190*/
105191
105192#ifndef _FTSINT_H
105193#define _FTSINT_H
105194
105195#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
105196# define NDEBUG 1
105197#endif
105198
105199/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
105200/************** Begin file fts3_tokenizer.h **********************************/
105201/*
105202** 2006 July 10
105203**
105204** The author disclaims copyright to this source code.
105205**
105206*************************************************************************
105207** Defines the interface to tokenizers used by fulltext-search.  There
105208** are three basic components:
105209**
105210** sqlite3_tokenizer_module is a singleton defining the tokenizer
105211** interface functions.  This is essentially the class structure for
105212** tokenizers.
105213**
105214** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
105215** including customization information defined at creation time.
105216**
105217** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
105218** tokens from a particular input.
105219*/
105220#ifndef _FTS3_TOKENIZER_H_
105221#define _FTS3_TOKENIZER_H_
105222
105223/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
105224** If tokenizers are to be allowed to call sqlite3_*() functions, then
105225** we will need a way to register the API consistently.
105226*/
105227
105228/*
105229** Structures used by the tokenizer interface. When a new tokenizer
105230** implementation is registered, the caller provides a pointer to
105231** an sqlite3_tokenizer_module containing pointers to the callback
105232** functions that make up an implementation.
105233**
105234** When an fts3 table is created, it passes any arguments passed to
105235** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
105236** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
105237** implementation. The xCreate() function in turn returns an
105238** sqlite3_tokenizer structure representing the specific tokenizer to
105239** be used for the fts3 table (customized by the tokenizer clause arguments).
105240**
105241** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
105242** method is called. It returns an sqlite3_tokenizer_cursor object
105243** that may be used to tokenize a specific input buffer based on
105244** the tokenization rules supplied by a specific sqlite3_tokenizer
105245** object.
105246*/
105247typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
105248typedef struct sqlite3_tokenizer sqlite3_tokenizer;
105249typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
105250
105251struct sqlite3_tokenizer_module {
105252
105253  /*
105254  ** Structure version. Should always be set to 0.
105255  */
105256  int iVersion;
105257
105258  /*
105259  ** Create a new tokenizer. The values in the argv[] array are the
105260  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
105261  ** TABLE statement that created the fts3 table. For example, if
105262  ** the following SQL is executed:
105263  **
105264  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
105265  **
105266  ** then argc is set to 2, and the argv[] array contains pointers
105267  ** to the strings "arg1" and "arg2".
105268  **
105269  ** This method should return either SQLITE_OK (0), or an SQLite error
105270  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
105271  ** to point at the newly created tokenizer structure. The generic
105272  ** sqlite3_tokenizer.pModule variable should not be initialised by
105273  ** this callback. The caller will do so.
105274  */
105275  int (*xCreate)(
105276    int argc,                           /* Size of argv array */
105277    const char *const*argv,             /* Tokenizer argument strings */
105278    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
105279  );
105280
105281  /*
105282  ** Destroy an existing tokenizer. The fts3 module calls this method
105283  ** exactly once for each successful call to xCreate().
105284  */
105285  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
105286
105287  /*
105288  ** Create a tokenizer cursor to tokenize an input buffer. The caller
105289  ** is responsible for ensuring that the input buffer remains valid
105290  ** until the cursor is closed (using the xClose() method).
105291  */
105292  int (*xOpen)(
105293    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
105294    const char *pInput, int nBytes,      /* Input buffer */
105295    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
105296  );
105297
105298  /*
105299  ** Destroy an existing tokenizer cursor. The fts3 module calls this
105300  ** method exactly once for each successful call to xOpen().
105301  */
105302  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
105303
105304  /*
105305  ** Retrieve the next token from the tokenizer cursor pCursor. This
105306  ** method should either return SQLITE_OK and set the values of the
105307  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
105308  ** the end of the buffer has been reached, or an SQLite error code.
105309  **
105310  ** *ppToken should be set to point at a buffer containing the
105311  ** normalized version of the token (i.e. after any case-folding and/or
105312  ** stemming has been performed). *pnBytes should be set to the length
105313  ** of this buffer in bytes. The input text that generated the token is
105314  ** identified by the byte offsets returned in *piStartOffset and
105315  ** *piEndOffset. *piStartOffset should be set to the index of the first
105316  ** byte of the token in the input buffer. *piEndOffset should be set
105317  ** to the index of the first byte just past the end of the token in
105318  ** the input buffer.
105319  **
105320  ** The buffer *ppToken is set to point at is managed by the tokenizer
105321  ** implementation. It is only required to be valid until the next call
105322  ** to xNext() or xClose().
105323  */
105324  /* TODO(shess) current implementation requires pInput to be
105325  ** nul-terminated.  This should either be fixed, or pInput/nBytes
105326  ** should be converted to zInput.
105327  */
105328  int (*xNext)(
105329    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
105330    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
105331    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
105332    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
105333    int *piPosition      /* OUT: Number of tokens returned before this one */
105334  );
105335};
105336
105337struct sqlite3_tokenizer {
105338  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
105339  /* Tokenizer implementations will typically add additional fields */
105340};
105341
105342struct sqlite3_tokenizer_cursor {
105343  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
105344  /* Tokenizer implementations will typically add additional fields */
105345};
105346
105347int fts3_global_term_cnt(int iTerm, int iCol);
105348int fts3_term_cnt(int iTerm, int iCol);
105349
105350
105351#endif /* _FTS3_TOKENIZER_H_ */
105352
105353/************** End of fts3_tokenizer.h **************************************/
105354/************** Continuing where we left off in fts3Int.h ********************/
105355/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
105356/************** Begin file fts3_hash.h ***************************************/
105357/*
105358** 2001 September 22
105359**
105360** The author disclaims copyright to this source code.  In place of
105361** a legal notice, here is a blessing:
105362**
105363**    May you do good and not evil.
105364**    May you find forgiveness for yourself and forgive others.
105365**    May you share freely, never taking more than you give.
105366**
105367*************************************************************************
105368** This is the header file for the generic hash-table implemenation
105369** used in SQLite.  We've modified it slightly to serve as a standalone
105370** hash table implementation for the full-text indexing module.
105371**
105372*/
105373#ifndef _FTS3_HASH_H_
105374#define _FTS3_HASH_H_
105375
105376/* Forward declarations of structures. */
105377typedef struct Fts3Hash Fts3Hash;
105378typedef struct Fts3HashElem Fts3HashElem;
105379
105380/* A complete hash table is an instance of the following structure.
105381** The internals of this structure are intended to be opaque -- client
105382** code should not attempt to access or modify the fields of this structure
105383** directly.  Change this structure only by using the routines below.
105384** However, many of the "procedures" and "functions" for modifying and
105385** accessing this structure are really macros, so we can't really make
105386** this structure opaque.
105387*/
105388struct Fts3Hash {
105389  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
105390  char copyKey;           /* True if copy of key made on insert */
105391  int count;              /* Number of entries in this table */
105392  Fts3HashElem *first;    /* The first element of the array */
105393  int htsize;             /* Number of buckets in the hash table */
105394  struct _fts3ht {        /* the hash table */
105395    int count;               /* Number of entries with this hash */
105396    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
105397  } *ht;
105398};
105399
105400/* Each element in the hash table is an instance of the following
105401** structure.  All elements are stored on a single doubly-linked list.
105402**
105403** Again, this structure is intended to be opaque, but it can't really
105404** be opaque because it is used by macros.
105405*/
105406struct Fts3HashElem {
105407  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
105408  void *data;                /* Data associated with this element */
105409  void *pKey; int nKey;      /* Key associated with this element */
105410};
105411
105412/*
105413** There are 2 different modes of operation for a hash table:
105414**
105415**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
105416**                           (including the null-terminator, if any).  Case
105417**                           is respected in comparisons.
105418**
105419**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
105420**                           memcmp() is used to compare keys.
105421**
105422** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
105423*/
105424#define FTS3_HASH_STRING    1
105425#define FTS3_HASH_BINARY    2
105426
105427/*
105428** Access routines.  To delete, insert a NULL pointer.
105429*/
105430SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
105431SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
105432SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
105433SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
105434SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
105435
105436/*
105437** Shorthand for the functions above
105438*/
105439#define fts3HashInit     sqlite3Fts3HashInit
105440#define fts3HashInsert   sqlite3Fts3HashInsert
105441#define fts3HashFind     sqlite3Fts3HashFind
105442#define fts3HashClear    sqlite3Fts3HashClear
105443#define fts3HashFindElem sqlite3Fts3HashFindElem
105444
105445/*
105446** Macros for looping over all elements of a hash table.  The idiom is
105447** like this:
105448**
105449**   Fts3Hash h;
105450**   Fts3HashElem *p;
105451**   ...
105452**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
105453**     SomeStructure *pData = fts3HashData(p);
105454**     // do something with pData
105455**   }
105456*/
105457#define fts3HashFirst(H)  ((H)->first)
105458#define fts3HashNext(E)   ((E)->next)
105459#define fts3HashData(E)   ((E)->data)
105460#define fts3HashKey(E)    ((E)->pKey)
105461#define fts3HashKeysize(E) ((E)->nKey)
105462
105463/*
105464** Number of entries in a hash table
105465*/
105466#define fts3HashCount(H)  ((H)->count)
105467
105468#endif /* _FTS3_HASH_H_ */
105469
105470/************** End of fts3_hash.h *******************************************/
105471/************** Continuing where we left off in fts3Int.h ********************/
105472
105473/*
105474** This constant controls how often segments are merged. Once there are
105475** FTS3_MERGE_COUNT segments of level N, they are merged into a single
105476** segment of level N+1.
105477*/
105478#define FTS3_MERGE_COUNT 16
105479
105480/*
105481** This is the maximum amount of data (in bytes) to store in the
105482** Fts3Table.pendingTerms hash table. Normally, the hash table is
105483** populated as documents are inserted/updated/deleted in a transaction
105484** and used to create a new segment when the transaction is committed.
105485** However if this limit is reached midway through a transaction, a new
105486** segment is created and the hash table cleared immediately.
105487*/
105488#define FTS3_MAX_PENDING_DATA (1*1024*1024)
105489
105490/*
105491** Macro to return the number of elements in an array. SQLite has a
105492** similar macro called ArraySize(). Use a different name to avoid
105493** a collision when building an amalgamation with built-in FTS3.
105494*/
105495#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
105496
105497/*
105498** Maximum length of a varint encoded integer. The varint format is different
105499** from that used by SQLite, so the maximum length is 10, not 9.
105500*/
105501#define FTS3_VARINT_MAX 10
105502
105503/*
105504** The testcase() macro is only used by the amalgamation.  If undefined,
105505** make it a no-op.
105506*/
105507#ifndef testcase
105508# define testcase(X)
105509#endif
105510
105511/*
105512** Terminator values for position-lists and column-lists.
105513*/
105514#define POS_COLUMN  (1)     /* Column-list terminator */
105515#define POS_END     (0)     /* Position-list terminator */
105516
105517/*
105518** This section provides definitions to allow the
105519** FTS3 extension to be compiled outside of the
105520** amalgamation.
105521*/
105522#ifndef SQLITE_AMALGAMATION
105523/*
105524** Macros indicating that conditional expressions are always true or
105525** false.
105526*/
105527# define ALWAYS(x) (x)
105528# define NEVER(X)  (x)
105529/*
105530** Internal types used by SQLite.
105531*/
105532typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
105533typedef short int i16;            /* 2-byte (or larger) signed integer */
105534typedef unsigned int u32;         /* 4-byte unsigned integer */
105535typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
105536/*
105537** Macro used to suppress compiler warnings for unused parameters.
105538*/
105539#define UNUSED_PARAMETER(x) (void)(x)
105540#endif
105541
105542typedef struct Fts3Table Fts3Table;
105543typedef struct Fts3Cursor Fts3Cursor;
105544typedef struct Fts3Expr Fts3Expr;
105545typedef struct Fts3Phrase Fts3Phrase;
105546typedef struct Fts3SegReader Fts3SegReader;
105547typedef struct Fts3SegFilter Fts3SegFilter;
105548
105549/*
105550** A connection to a fulltext index is an instance of the following
105551** structure. The xCreate and xConnect methods create an instance
105552** of this structure and xDestroy and xDisconnect free that instance.
105553** All other methods receive a pointer to the structure as one of their
105554** arguments.
105555*/
105556struct Fts3Table {
105557  sqlite3_vtab base;              /* Base class used by SQLite core */
105558  sqlite3 *db;                    /* The database connection */
105559  const char *zDb;                /* logical database name */
105560  const char *zName;              /* virtual table name */
105561  int nColumn;                    /* number of named columns in virtual table */
105562  char **azColumn;                /* column names.  malloced */
105563  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
105564
105565  /* Precompiled statements used by the implementation. Each of these
105566  ** statements is run and reset within a single virtual table API call.
105567  */
105568  sqlite3_stmt *aStmt[25];
105569
105570  /* Pointer to string containing the SQL:
105571  **
105572  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
105573  **    ORDER BY blockid"
105574  */
105575  char *zSelectLeaves;
105576  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
105577  int nLeavesTotal;               /* Total number of prepared leaves stmts */
105578  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
105579  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
105580
105581  int nNodeSize;                  /* Soft limit for node size */
105582  u8 bHasContent;                 /* True if %_content table exists */
105583  u8 bHasDocsize;                 /* True if %_docsize table exists */
105584
105585  /* The following hash table is used to buffer pending index updates during
105586  ** transactions. Variable nPendingData estimates the memory size of the
105587  ** pending data, including hash table overhead, but not malloc overhead.
105588  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
105589  ** automatically. Variable iPrevDocid is the docid of the most recently
105590  ** inserted record.
105591  */
105592  int nMaxPendingData;
105593  int nPendingData;
105594  sqlite_int64 iPrevDocid;
105595  Fts3Hash pendingTerms;
105596};
105597
105598/*
105599** When the core wants to read from the virtual table, it creates a
105600** virtual table cursor (an instance of the following structure) using
105601** the xOpen method. Cursors are destroyed using the xClose method.
105602*/
105603struct Fts3Cursor {
105604  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
105605  i16 eSearch;                    /* Search strategy (see below) */
105606  u8 isEof;                       /* True if at End Of Results */
105607  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
105608  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
105609  Fts3Expr *pExpr;                /* Parsed MATCH query string */
105610  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
105611  char *pNextId;                  /* Pointer into the body of aDoclist */
105612  char *aDoclist;                 /* List of docids for full-text queries */
105613  int nDoclist;                   /* Size of buffer at aDoclist */
105614  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
105615  u32 *aMatchinfo;                /* Information about most recent match */
105616};
105617
105618/*
105619** The Fts3Cursor.eSearch member is always set to one of the following.
105620** Actualy, Fts3Cursor.eSearch can be greater than or equal to
105621** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
105622** of the column to be searched.  For example, in
105623**
105624**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
105625**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
105626**
105627** Because the LHS of the MATCH operator is 2nd column "b",
105628** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
105629** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
105630** indicating that all columns should be searched,
105631** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
105632*/
105633#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
105634#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
105635#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
105636
105637/*
105638** A "phrase" is a sequence of one or more tokens that must match in
105639** sequence.  A single token is the base case and the most common case.
105640** For a sequence of tokens contained in "...", nToken will be the number
105641** of tokens in the string.
105642*/
105643struct Fts3Phrase {
105644  int nToken;                /* Number of tokens in the phrase */
105645  int iColumn;               /* Index of column this phrase must match */
105646  int isNot;                 /* Phrase prefixed by unary not (-) operator */
105647  struct PhraseToken {
105648    char *z;                 /* Text of the token */
105649    int n;                   /* Number of bytes in buffer pointed to by z */
105650    int isPrefix;            /* True if token ends in with a "*" character */
105651  } aToken[1];               /* One entry for each token in the phrase */
105652};
105653
105654/*
105655** A tree of these objects forms the RHS of a MATCH operator.
105656**
105657** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
105658** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
105659** containing the results of the NEAR or phrase query in FTS3 doclist
105660** format. As usual, the initial "Length" field found in doclists stored
105661** on disk is omitted from this buffer.
105662**
105663** Variable pCurrent always points to the start of a docid field within
105664** aDoclist. Since the doclist is usually scanned in docid order, this can
105665** be used to accelerate seeking to the required docid within the doclist.
105666*/
105667struct Fts3Expr {
105668  int eType;                 /* One of the FTSQUERY_XXX values defined below */
105669  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
105670  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
105671  Fts3Expr *pLeft;           /* Left operand */
105672  Fts3Expr *pRight;          /* Right operand */
105673  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
105674
105675  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
105676  char *aDoclist;            /* Buffer containing doclist */
105677  int nDoclist;              /* Size of aDoclist in bytes */
105678
105679  sqlite3_int64 iCurrent;
105680  char *pCurrent;
105681};
105682
105683/*
105684** Candidate values for Fts3Query.eType. Note that the order of the first
105685** four values is in order of precedence when parsing expressions. For
105686** example, the following:
105687**
105688**   "a OR b AND c NOT d NEAR e"
105689**
105690** is equivalent to:
105691**
105692**   "a OR (b AND (c NOT (d NEAR e)))"
105693*/
105694#define FTSQUERY_NEAR   1
105695#define FTSQUERY_NOT    2
105696#define FTSQUERY_AND    3
105697#define FTSQUERY_OR     4
105698#define FTSQUERY_PHRASE 5
105699
105700
105701/* fts3_init.c */
105702SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
105703SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
105704                        sqlite3_vtab **, char **);
105705
105706/* fts3_write.c */
105707SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
105708SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
105709SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
105710SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
105711SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
105712  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
105713SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
105714SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
105715SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105716  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
105717  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
105718);
105719SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
105720SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
105721SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
105722SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
105723
105724/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
105725#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
105726#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
105727#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
105728#define FTS3_SEGMENT_PREFIX        0x00000008
105729
105730/* Type passed as 4th argument to SegmentReaderIterate() */
105731struct Fts3SegFilter {
105732  const char *zTerm;
105733  int nTerm;
105734  int iCol;
105735  int flags;
105736};
105737
105738/* fts3.c */
105739SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
105740SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
105741SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
105742SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
105743SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
105744
105745SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
105746SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
105747SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
105748
105749/* fts3_tokenizer.c */
105750SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
105751SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
105752SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
105753  const char *, sqlite3_tokenizer **, const char **, char **
105754);
105755
105756/* fts3_snippet.c */
105757SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
105758SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
105759  const char *, const char *, int, int
105760);
105761SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
105762
105763/* fts3_expr.c */
105764SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
105765  char **, int, int, const char *, int, Fts3Expr **
105766);
105767SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
105768#ifdef SQLITE_TEST
105769SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
105770#endif
105771
105772#endif /* _FTSINT_H */
105773
105774/************** End of fts3Int.h *********************************************/
105775/************** Continuing where we left off in fts3.c ***********************/
105776
105777
105778#ifndef SQLITE_CORE
105779  SQLITE_EXTENSION_INIT1
105780#endif
105781
105782/*
105783** Write a 64-bit variable-length integer to memory starting at p[0].
105784** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
105785** The number of bytes written is returned.
105786*/
105787SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
105788  unsigned char *q = (unsigned char *) p;
105789  sqlite_uint64 vu = v;
105790  do{
105791    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
105792    vu >>= 7;
105793  }while( vu!=0 );
105794  q[-1] &= 0x7f;  /* turn off high bit in final byte */
105795  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
105796  return (int) (q - (unsigned char *)p);
105797}
105798
105799/*
105800** Read a 64-bit variable-length integer from memory starting at p[0].
105801** Return the number of bytes read, or 0 on error.
105802** The value is stored in *v.
105803*/
105804SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
105805  const unsigned char *q = (const unsigned char *) p;
105806  sqlite_uint64 x = 0, y = 1;
105807  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
105808    x += y * (*q++ & 0x7f);
105809    y <<= 7;
105810  }
105811  x += y * (*q++);
105812  *v = (sqlite_int64) x;
105813  return (int) (q - (unsigned char *)p);
105814}
105815
105816/*
105817** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
105818** 32-bit integer before it is returned.
105819*/
105820SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
105821 sqlite_int64 i;
105822 int ret = sqlite3Fts3GetVarint(p, &i);
105823 *pi = (int) i;
105824 return ret;
105825}
105826
105827/*
105828** Return the number of bytes required to encode v as a varint
105829*/
105830SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
105831  int i = 0;
105832  do{
105833    i++;
105834    v >>= 7;
105835  }while( v!=0 );
105836  return i;
105837}
105838
105839/*
105840** Convert an SQL-style quoted string into a normal string by removing
105841** the quote characters.  The conversion is done in-place.  If the
105842** input does not begin with a quote character, then this routine
105843** is a no-op.
105844**
105845** Examples:
105846**
105847**     "abc"   becomes   abc
105848**     'xyz'   becomes   xyz
105849**     [pqr]   becomes   pqr
105850**     `mno`   becomes   mno
105851**
105852*/
105853SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
105854  char quote;                     /* Quote character (if any ) */
105855
105856  quote = z[0];
105857  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
105858    int iIn = 1;                  /* Index of next byte to read from input */
105859    int iOut = 0;                 /* Index of next byte to write to output */
105860
105861    /* If the first byte was a '[', then the close-quote character is a ']' */
105862    if( quote=='[' ) quote = ']';
105863
105864    while( ALWAYS(z[iIn]) ){
105865      if( z[iIn]==quote ){
105866        if( z[iIn+1]!=quote ) break;
105867        z[iOut++] = quote;
105868        iIn += 2;
105869      }else{
105870        z[iOut++] = z[iIn++];
105871      }
105872    }
105873    z[iOut] = '\0';
105874  }
105875}
105876
105877/*
105878** Read a single varint from the doclist at *pp and advance *pp to point
105879** to the first byte past the end of the varint.  Add the value of the varint
105880** to *pVal.
105881*/
105882static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
105883  sqlite3_int64 iVal;
105884  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
105885  *pVal += iVal;
105886}
105887
105888/*
105889** As long as *pp has not reached its end (pEnd), then do the same
105890** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
105891** But if we have reached the end of the varint, just set *pp=0 and
105892** leave *pVal unchanged.
105893*/
105894static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
105895  if( *pp>=pEnd ){
105896    *pp = 0;
105897  }else{
105898    fts3GetDeltaVarint(pp, pVal);
105899  }
105900}
105901
105902/*
105903** The xDisconnect() virtual table method.
105904*/
105905static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
105906  Fts3Table *p = (Fts3Table *)pVtab;
105907  int i;
105908
105909  assert( p->nPendingData==0 );
105910
105911  /* Free any prepared statements held */
105912  for(i=0; i<SizeofArray(p->aStmt); i++){
105913    sqlite3_finalize(p->aStmt[i]);
105914  }
105915  for(i=0; i<p->nLeavesStmt; i++){
105916    sqlite3_finalize(p->aLeavesStmt[i]);
105917  }
105918  sqlite3_free(p->zSelectLeaves);
105919  sqlite3_free(p->aLeavesStmt);
105920
105921  /* Invoke the tokenizer destructor to free the tokenizer. */
105922  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
105923
105924  sqlite3_free(p);
105925  return SQLITE_OK;
105926}
105927
105928/*
105929** Construct one or more SQL statements from the format string given
105930** and then evaluate those statements.  The success code is writting
105931** into *pRc.
105932**
105933** If *pRc is initially non-zero then this routine is a no-op.
105934*/
105935static void fts3DbExec(
105936  int *pRc,              /* Success code */
105937  sqlite3 *db,           /* Database in which to run SQL */
105938  const char *zFormat,   /* Format string for SQL */
105939  ...                    /* Arguments to the format string */
105940){
105941  va_list ap;
105942  char *zSql;
105943  if( *pRc ) return;
105944  va_start(ap, zFormat);
105945  zSql = sqlite3_vmprintf(zFormat, ap);
105946  va_end(ap);
105947  if( zSql==0 ){
105948    *pRc = SQLITE_NOMEM;
105949  }else{
105950    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
105951    sqlite3_free(zSql);
105952  }
105953}
105954
105955/*
105956** The xDestroy() virtual table method.
105957*/
105958static int fts3DestroyMethod(sqlite3_vtab *pVtab){
105959  int rc = SQLITE_OK;              /* Return code */
105960  Fts3Table *p = (Fts3Table *)pVtab;
105961  sqlite3 *db = p->db;
105962
105963  /* Drop the shadow tables */
105964  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
105965  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
105966  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
105967  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
105968  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
105969
105970  /* If everything has worked, invoke fts3DisconnectMethod() to free the
105971  ** memory associated with the Fts3Table structure and return SQLITE_OK.
105972  ** Otherwise, return an SQLite error code.
105973  */
105974  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
105975}
105976
105977
105978/*
105979** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
105980** passed as the first argument. This is done as part of the xConnect()
105981** and xCreate() methods.
105982*/
105983static int fts3DeclareVtab(Fts3Table *p){
105984  int i;                          /* Iterator variable */
105985  int rc;                         /* Return code */
105986  char *zSql;                     /* SQL statement passed to declare_vtab() */
105987  char *zCols;                    /* List of user defined columns */
105988
105989  /* Create a list of user columns for the virtual table */
105990  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
105991  for(i=1; zCols && i<p->nColumn; i++){
105992    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
105993  }
105994
105995  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
105996  zSql = sqlite3_mprintf(
105997      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
105998  );
105999
106000  if( !zCols || !zSql ){
106001    rc = SQLITE_NOMEM;
106002  }else{
106003    rc = sqlite3_declare_vtab(p->db, zSql);
106004  }
106005
106006  sqlite3_free(zSql);
106007  sqlite3_free(zCols);
106008  return rc;
106009}
106010
106011/*
106012** Create the backing store tables (%_content, %_segments and %_segdir)
106013** required by the FTS3 table passed as the only argument. This is done
106014** as part of the vtab xCreate() method.
106015**
106016** If the p->bHasDocsize boolean is true (indicating that this is an
106017** FTS4 table, not an FTS3 table) then also create the %_docsize and
106018** %_stat tables required by FTS4.
106019*/
106020static int fts3CreateTables(Fts3Table *p){
106021  int rc = SQLITE_OK;             /* Return code */
106022  int i;                          /* Iterator variable */
106023  char *zContentCols;             /* Columns of %_content table */
106024  sqlite3 *db = p->db;            /* The database connection */
106025
106026  /* Create a list of user columns for the content table */
106027  if( p->bHasContent ){
106028    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
106029    for(i=0; zContentCols && i<p->nColumn; i++){
106030      char *z = p->azColumn[i];
106031      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
106032    }
106033    if( zContentCols==0 ) rc = SQLITE_NOMEM;
106034
106035    /* Create the content table */
106036    fts3DbExec(&rc, db,
106037       "CREATE TABLE %Q.'%q_content'(%s)",
106038       p->zDb, p->zName, zContentCols
106039    );
106040    sqlite3_free(zContentCols);
106041  }
106042  /* Create other tables */
106043  fts3DbExec(&rc, db,
106044      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
106045      p->zDb, p->zName
106046  );
106047  fts3DbExec(&rc, db,
106048      "CREATE TABLE %Q.'%q_segdir'("
106049        "level INTEGER,"
106050        "idx INTEGER,"
106051        "start_block INTEGER,"
106052        "leaves_end_block INTEGER,"
106053        "end_block INTEGER,"
106054        "root BLOB,"
106055        "PRIMARY KEY(level, idx)"
106056      ");",
106057      p->zDb, p->zName
106058  );
106059  if( p->bHasDocsize ){
106060    fts3DbExec(&rc, db,
106061        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
106062        p->zDb, p->zName
106063    );
106064    fts3DbExec(&rc, db,
106065        "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
106066        p->zDb, p->zName
106067    );
106068  }
106069  return rc;
106070}
106071
106072/*
106073** An sqlite3_exec() callback for fts3TableExists.
106074*/
106075static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
106076  *(int*)pArg = 1;
106077  return 1;
106078}
106079
106080/*
106081** Determine if a table currently exists in the database.
106082*/
106083static void fts3TableExists(
106084  int *pRc,             /* Success code */
106085  sqlite3 *db,          /* The database connection to test */
106086  const char *zDb,      /* ATTACHed database within the connection */
106087  const char *zName,    /* Name of the FTS3 table */
106088  const char *zSuffix,  /* Shadow table extension */
106089  u8 *pResult           /* Write results here */
106090){
106091  int rc = SQLITE_OK;
106092  int res = 0;
106093  char *zSql;
106094  if( *pRc ) return;
106095  zSql = sqlite3_mprintf(
106096    "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
106097    zDb, zName, zSuffix
106098  );
106099  rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
106100  sqlite3_free(zSql);
106101  *pResult = res & 0xff;
106102  if( rc!=SQLITE_ABORT ) *pRc = rc;
106103}
106104
106105/*
106106** This function is the implementation of both the xConnect and xCreate
106107** methods of the FTS3 virtual table.
106108**
106109** The argv[] array contains the following:
106110**
106111**   argv[0]   -> module name  ("fts3" or "fts4")
106112**   argv[1]   -> database name
106113**   argv[2]   -> table name
106114**   argv[...] -> "column name" and other module argument fields.
106115*/
106116static int fts3InitVtab(
106117  int isCreate,                   /* True for xCreate, false for xConnect */
106118  sqlite3 *db,                    /* The SQLite database connection */
106119  void *pAux,                     /* Hash table containing tokenizers */
106120  int argc,                       /* Number of elements in argv array */
106121  const char * const *argv,       /* xCreate/xConnect argument array */
106122  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
106123  char **pzErr                    /* Write any error message here */
106124){
106125  Fts3Hash *pHash = (Fts3Hash *)pAux;
106126  Fts3Table *p;                   /* Pointer to allocated vtab */
106127  int rc;                         /* Return code */
106128  int i;                          /* Iterator variable */
106129  int nByte;                      /* Size of allocation used for *p */
106130  int iCol;                       /* Column index */
106131  int nString = 0;                /* Bytes required to hold all column names */
106132  int nCol = 0;                   /* Number of columns in the FTS table */
106133  char *zCsr;                     /* Space for holding column names */
106134  int nDb;                        /* Bytes required to hold database name */
106135  int nName;                      /* Bytes required to hold table name */
106136
106137  const char *zTokenizer = 0;               /* Name of tokenizer to use */
106138  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
106139
106140  nDb = (int)strlen(argv[1]) + 1;
106141  nName = (int)strlen(argv[2]) + 1;
106142  for(i=3; i<argc; i++){
106143    char const *z = argv[i];
106144    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
106145    if( rc!=SQLITE_OK ){
106146      return rc;
106147    }
106148    if( z!=zTokenizer ){
106149      nString += (int)(strlen(z) + 1);
106150    }
106151  }
106152  nCol = argc - 3 - (zTokenizer!=0);
106153  if( zTokenizer==0 ){
106154    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
106155    if( rc!=SQLITE_OK ){
106156      return rc;
106157    }
106158    assert( pTokenizer );
106159  }
106160
106161  if( nCol==0 ){
106162    nCol = 1;
106163  }
106164
106165  /* Allocate and populate the Fts3Table structure. */
106166  nByte = sizeof(Fts3Table) +              /* Fts3Table */
106167          nCol * sizeof(char *) +              /* azColumn */
106168          nName +                              /* zName */
106169          nDb +                                /* zDb */
106170          nString;                             /* Space for azColumn strings */
106171  p = (Fts3Table*)sqlite3_malloc(nByte);
106172  if( p==0 ){
106173    rc = SQLITE_NOMEM;
106174    goto fts3_init_out;
106175  }
106176  memset(p, 0, nByte);
106177
106178  p->db = db;
106179  p->nColumn = nCol;
106180  p->nPendingData = 0;
106181  p->azColumn = (char **)&p[1];
106182  p->pTokenizer = pTokenizer;
106183  p->nNodeSize = 1000;
106184  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
106185  zCsr = (char *)&p->azColumn[nCol];
106186
106187  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
106188
106189  /* Fill in the zName and zDb fields of the vtab structure. */
106190  p->zName = zCsr;
106191  memcpy(zCsr, argv[2], nName);
106192  zCsr += nName;
106193  p->zDb = zCsr;
106194  memcpy(zCsr, argv[1], nDb);
106195  zCsr += nDb;
106196
106197  /* Fill in the azColumn array */
106198  iCol = 0;
106199  for(i=3; i<argc; i++){
106200    if( argv[i]!=zTokenizer ){
106201      char *z;
106202      int n;
106203      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
106204      memcpy(zCsr, z, n);
106205      zCsr[n] = '\0';
106206      sqlite3Fts3Dequote(zCsr);
106207      p->azColumn[iCol++] = zCsr;
106208      zCsr += n+1;
106209      assert( zCsr <= &((char *)p)[nByte] );
106210    }
106211  }
106212  if( iCol==0 ){
106213    assert( nCol==1 );
106214    p->azColumn[0] = "content";
106215  }
106216
106217  /* If this is an xCreate call, create the underlying tables in the
106218  ** database. TODO: For xConnect(), it could verify that said tables exist.
106219  */
106220  if( isCreate ){
106221    p->bHasContent = 1;
106222    p->bHasDocsize = argv[0][3]=='4';
106223    rc = fts3CreateTables(p);
106224  }else{
106225    rc = SQLITE_OK;
106226    fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
106227    fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
106228  }
106229  if( rc!=SQLITE_OK ) goto fts3_init_out;
106230
106231  rc = fts3DeclareVtab(p);
106232  if( rc!=SQLITE_OK ) goto fts3_init_out;
106233
106234  *ppVTab = &p->base;
106235
106236fts3_init_out:
106237  assert( p || (pTokenizer && rc!=SQLITE_OK) );
106238  if( rc!=SQLITE_OK ){
106239    if( p ){
106240      fts3DisconnectMethod((sqlite3_vtab *)p);
106241    }else{
106242      pTokenizer->pModule->xDestroy(pTokenizer);
106243    }
106244  }
106245  return rc;
106246}
106247
106248/*
106249** The xConnect() and xCreate() methods for the virtual table. All the
106250** work is done in function fts3InitVtab().
106251*/
106252static int fts3ConnectMethod(
106253  sqlite3 *db,                    /* Database connection */
106254  void *pAux,                     /* Pointer to tokenizer hash table */
106255  int argc,                       /* Number of elements in argv array */
106256  const char * const *argv,       /* xCreate/xConnect argument array */
106257  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106258  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106259){
106260  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
106261}
106262static int fts3CreateMethod(
106263  sqlite3 *db,                    /* Database connection */
106264  void *pAux,                     /* Pointer to tokenizer hash table */
106265  int argc,                       /* Number of elements in argv array */
106266  const char * const *argv,       /* xCreate/xConnect argument array */
106267  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106268  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106269){
106270  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
106271}
106272
106273/*
106274** Implementation of the xBestIndex method for FTS3 tables. There
106275** are three possible strategies, in order of preference:
106276**
106277**   1. Direct lookup by rowid or docid.
106278**   2. Full-text search using a MATCH operator on a non-docid column.
106279**   3. Linear scan of %_content table.
106280*/
106281static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
106282  Fts3Table *p = (Fts3Table *)pVTab;
106283  int i;                          /* Iterator variable */
106284  int iCons = -1;                 /* Index of constraint to use */
106285
106286  /* By default use a full table scan. This is an expensive option,
106287  ** so search through the constraints to see if a more efficient
106288  ** strategy is possible.
106289  */
106290  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
106291  pInfo->estimatedCost = 500000;
106292  for(i=0; i<pInfo->nConstraint; i++){
106293    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
106294    if( pCons->usable==0 ) continue;
106295
106296    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
106297    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
106298     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
106299    ){
106300      pInfo->idxNum = FTS3_DOCID_SEARCH;
106301      pInfo->estimatedCost = 1.0;
106302      iCons = i;
106303    }
106304
106305    /* A MATCH constraint. Use a full-text search.
106306    **
106307    ** If there is more than one MATCH constraint available, use the first
106308    ** one encountered. If there is both a MATCH constraint and a direct
106309    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
106310    ** though the rowid/docid lookup is faster than a MATCH query, selecting
106311    ** it would lead to an "unable to use function MATCH in the requested
106312    ** context" error.
106313    */
106314    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
106315     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
106316    ){
106317      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
106318      pInfo->estimatedCost = 2.0;
106319      iCons = i;
106320      break;
106321    }
106322  }
106323
106324  if( iCons>=0 ){
106325    pInfo->aConstraintUsage[iCons].argvIndex = 1;
106326    pInfo->aConstraintUsage[iCons].omit = 1;
106327  }
106328  return SQLITE_OK;
106329}
106330
106331/*
106332** Implementation of xOpen method.
106333*/
106334static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
106335  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
106336
106337  UNUSED_PARAMETER(pVTab);
106338
106339  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
106340  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
106341  ** if the allocation fails, return SQLITE_NOMEM.
106342  */
106343  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
106344  if( !pCsr ){
106345    return SQLITE_NOMEM;
106346  }
106347  memset(pCsr, 0, sizeof(Fts3Cursor));
106348  return SQLITE_OK;
106349}
106350
106351/*
106352** Close the cursor.  For additional information see the documentation
106353** on the xClose method of the virtual table interface.
106354*/
106355static int fulltextClose(sqlite3_vtab_cursor *pCursor){
106356  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106357  sqlite3_finalize(pCsr->pStmt);
106358  sqlite3Fts3ExprFree(pCsr->pExpr);
106359  sqlite3_free(pCsr->aDoclist);
106360  sqlite3_free(pCsr->aMatchinfo);
106361  sqlite3_free(pCsr);
106362  return SQLITE_OK;
106363}
106364
106365/*
106366** Position the pCsr->pStmt statement so that it is on the row
106367** of the %_content table that contains the last match.  Return
106368** SQLITE_OK on success.
106369*/
106370static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
106371  if( pCsr->isRequireSeek ){
106372    pCsr->isRequireSeek = 0;
106373    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
106374    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
106375      return SQLITE_OK;
106376    }else{
106377      int rc = sqlite3_reset(pCsr->pStmt);
106378      if( rc==SQLITE_OK ){
106379        /* If no row was found and no error has occured, then the %_content
106380        ** table is missing a row that is present in the full-text index.
106381        ** The data structures are corrupt.
106382        */
106383        rc = SQLITE_CORRUPT;
106384      }
106385      pCsr->isEof = 1;
106386      if( pContext ){
106387        sqlite3_result_error_code(pContext, rc);
106388      }
106389      return rc;
106390    }
106391  }else{
106392    return SQLITE_OK;
106393  }
106394}
106395
106396/*
106397** Advance the cursor to the next row in the %_content table that
106398** matches the search criteria.  For a MATCH search, this will be
106399** the next row that matches.  For a full-table scan, this will be
106400** simply the next row in the %_content table.  For a docid lookup,
106401** this routine simply sets the EOF flag.
106402**
106403** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
106404** even if we reach end-of-file.  The fts3EofMethod() will be called
106405** subsequently to determine whether or not an EOF was hit.
106406*/
106407static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
106408  int rc = SQLITE_OK;             /* Return code */
106409  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106410
106411  if( pCsr->aDoclist==0 ){
106412    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
106413      pCsr->isEof = 1;
106414      rc = sqlite3_reset(pCsr->pStmt);
106415    }
106416  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
106417    pCsr->isEof = 1;
106418  }else{
106419    sqlite3_reset(pCsr->pStmt);
106420    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
106421    pCsr->isRequireSeek = 1;
106422    pCsr->isMatchinfoNeeded = 1;
106423  }
106424  return rc;
106425}
106426
106427
106428/*
106429** The buffer pointed to by argument zNode (size nNode bytes) contains the
106430** root node of a b-tree segment. The segment is guaranteed to be at least
106431** one level high (i.e. the root node is not also a leaf). If successful,
106432** this function locates the leaf node of the segment that may contain the
106433** term specified by arguments zTerm and nTerm and writes its block number
106434** to *piLeaf.
106435**
106436** It is possible that the returned leaf node does not contain the specified
106437** term. However, if the segment does contain said term, it is stored on
106438** the identified leaf node. Because this function only inspects interior
106439** segment nodes (and never loads leaf nodes into memory), it is not possible
106440** to be sure.
106441**
106442** If an error occurs, an error code other than SQLITE_OK is returned.
106443*/
106444static int fts3SelectLeaf(
106445  Fts3Table *p,                   /* Virtual table handle */
106446  const char *zTerm,              /* Term to select leaves for */
106447  int nTerm,                      /* Size of term zTerm in bytes */
106448  const char *zNode,              /* Buffer containing segment interior node */
106449  int nNode,                      /* Size of buffer at zNode */
106450  sqlite3_int64 *piLeaf           /* Selected leaf node */
106451){
106452  int rc = SQLITE_OK;             /* Return code */
106453  const char *zCsr = zNode;       /* Cursor to iterate through node */
106454  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
106455  char *zBuffer = 0;              /* Buffer to load terms into */
106456  int nAlloc = 0;                 /* Size of allocated buffer */
106457
106458  while( 1 ){
106459    int isFirstTerm = 1;          /* True when processing first term on page */
106460    int iHeight;                  /* Height of this node in tree */
106461    sqlite3_int64 iChild;         /* Block id of child node to descend to */
106462    int nBlock;                   /* Size of child node in bytes */
106463
106464    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
106465    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
106466
106467    while( zCsr<zEnd ){
106468      int cmp;                    /* memcmp() result */
106469      int nSuffix;                /* Size of term suffix */
106470      int nPrefix = 0;            /* Size of term prefix */
106471      int nBuffer;                /* Total term size */
106472
106473      /* Load the next term on the node into zBuffer */
106474      if( !isFirstTerm ){
106475        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
106476      }
106477      isFirstTerm = 0;
106478      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
106479      if( nPrefix+nSuffix>nAlloc ){
106480        char *zNew;
106481        nAlloc = (nPrefix+nSuffix) * 2;
106482        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
106483        if( !zNew ){
106484          sqlite3_free(zBuffer);
106485          return SQLITE_NOMEM;
106486        }
106487        zBuffer = zNew;
106488      }
106489      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
106490      nBuffer = nPrefix + nSuffix;
106491      zCsr += nSuffix;
106492
106493      /* Compare the term we are searching for with the term just loaded from
106494      ** the interior node. If the specified term is greater than or equal
106495      ** to the term from the interior node, then all terms on the sub-tree
106496      ** headed by node iChild are smaller than zTerm. No need to search
106497      ** iChild.
106498      **
106499      ** If the interior node term is larger than the specified term, then
106500      ** the tree headed by iChild may contain the specified term.
106501      */
106502      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
106503      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
106504      iChild++;
106505    };
106506
106507    /* If (iHeight==1), the children of this interior node are leaves. The
106508    ** specified term may be present on leaf node iChild.
106509    */
106510    if( iHeight==1 ){
106511      *piLeaf = iChild;
106512      break;
106513    }
106514
106515    /* Descend to interior node iChild. */
106516    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
106517    if( rc!=SQLITE_OK ) break;
106518    zEnd = &zCsr[nBlock];
106519  }
106520  sqlite3_free(zBuffer);
106521  return rc;
106522}
106523
106524/*
106525** This function is used to create delta-encoded serialized lists of FTS3
106526** varints. Each call to this function appends a single varint to a list.
106527*/
106528static void fts3PutDeltaVarint(
106529  char **pp,                      /* IN/OUT: Output pointer */
106530  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
106531  sqlite3_int64 iVal              /* Write this value to the list */
106532){
106533  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
106534  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
106535  *piPrev = iVal;
106536}
106537
106538/*
106539** When this function is called, *ppPoslist is assumed to point to the
106540** start of a position-list. After it returns, *ppPoslist points to the
106541** first byte after the position-list.
106542**
106543** A position list is list of positions (delta encoded) and columns for
106544** a single document record of a doclist.  So, in other words, this
106545** routine advances *ppPoslist so that it points to the next docid in
106546** the doclist, or to the first byte past the end of the doclist.
106547**
106548** If pp is not NULL, then the contents of the position list are copied
106549** to *pp. *pp is set to point to the first byte past the last byte copied
106550** before this function returns.
106551*/
106552static void fts3PoslistCopy(char **pp, char **ppPoslist){
106553  char *pEnd = *ppPoslist;
106554  char c = 0;
106555
106556  /* The end of a position list is marked by a zero encoded as an FTS3
106557  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
106558  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
106559  ** of some other, multi-byte, value.
106560  **
106561  ** The following while-loop moves pEnd to point to the first byte that is not
106562  ** immediately preceded by a byte with the 0x80 bit set. Then increments
106563  ** pEnd once more so that it points to the byte immediately following the
106564  ** last byte in the position-list.
106565  */
106566  while( *pEnd | c ){
106567    c = *pEnd++ & 0x80;
106568    testcase( c!=0 && (*pEnd)==0 );
106569  }
106570  pEnd++;  /* Advance past the POS_END terminator byte */
106571
106572  if( pp ){
106573    int n = (int)(pEnd - *ppPoslist);
106574    char *p = *pp;
106575    memcpy(p, *ppPoslist, n);
106576    p += n;
106577    *pp = p;
106578  }
106579  *ppPoslist = pEnd;
106580}
106581
106582/*
106583** When this function is called, *ppPoslist is assumed to point to the
106584** start of a column-list. After it returns, *ppPoslist points to the
106585** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
106586**
106587** A column-list is list of delta-encoded positions for a single column
106588** within a single document within a doclist.
106589**
106590** The column-list is terminated either by a POS_COLUMN varint (1) or
106591** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
106592** the POS_COLUMN or POS_END that terminates the column-list.
106593**
106594** If pp is not NULL, then the contents of the column-list are copied
106595** to *pp. *pp is set to point to the first byte past the last byte copied
106596** before this function returns.  The POS_COLUMN or POS_END terminator
106597** is not copied into *pp.
106598*/
106599static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
106600  char *pEnd = *ppPoslist;
106601  char c = 0;
106602
106603  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
106604  ** not part of a multi-byte varint.
106605  */
106606  while( 0xFE & (*pEnd | c) ){
106607    c = *pEnd++ & 0x80;
106608    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
106609  }
106610  if( pp ){
106611    int n = (int)(pEnd - *ppPoslist);
106612    char *p = *pp;
106613    memcpy(p, *ppPoslist, n);
106614    p += n;
106615    *pp = p;
106616  }
106617  *ppPoslist = pEnd;
106618}
106619
106620/*
106621** Value used to signify the end of an position-list. This is safe because
106622** it is not possible to have a document with 2^31 terms.
106623*/
106624#define POSITION_LIST_END 0x7fffffff
106625
106626/*
106627** This function is used to help parse position-lists. When this function is
106628** called, *pp may point to the start of the next varint in the position-list
106629** being parsed, or it may point to 1 byte past the end of the position-list
106630** (in which case **pp will be a terminator bytes POS_END (0) or
106631** (1)).
106632**
106633** If *pp points past the end of the current position-list, set *pi to
106634** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
106635** increment the current value of *pi by the value read, and set *pp to
106636** point to the next value before returning.
106637**
106638** Before calling this routine *pi must be initialized to the value of
106639** the previous position, or zero if we are reading the first position
106640** in the position-list.  Because positions are delta-encoded, the value
106641** of the previous position is needed in order to compute the value of
106642** the next position.
106643*/
106644static void fts3ReadNextPos(
106645  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
106646  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
106647){
106648  if( (**pp)&0xFE ){
106649    fts3GetDeltaVarint(pp, pi);
106650    *pi -= 2;
106651  }else{
106652    *pi = POSITION_LIST_END;
106653  }
106654}
106655
106656/*
106657** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
106658** the value of iCol encoded as a varint to *pp.   This will start a new
106659** column list.
106660**
106661** Set *pp to point to the byte just after the last byte written before
106662** returning (do not modify it if iCol==0). Return the total number of bytes
106663** written (0 if iCol==0).
106664*/
106665static int fts3PutColNumber(char **pp, int iCol){
106666  int n = 0;                      /* Number of bytes written */
106667  if( iCol ){
106668    char *p = *pp;                /* Output pointer */
106669    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
106670    *p = 0x01;
106671    *pp = &p[n];
106672  }
106673  return n;
106674}
106675
106676/*
106677** Compute the union of two position lists.  The output written
106678** into *pp contains all positions of both *pp1 and *pp2 in sorted
106679** order and with any duplicates removed.  All pointers are
106680** updated appropriately.   The caller is responsible for insuring
106681** that there is enough space in *pp to hold the complete output.
106682*/
106683static void fts3PoslistMerge(
106684  char **pp,                      /* Output buffer */
106685  char **pp1,                     /* Left input list */
106686  char **pp2                      /* Right input list */
106687){
106688  char *p = *pp;
106689  char *p1 = *pp1;
106690  char *p2 = *pp2;
106691
106692  while( *p1 || *p2 ){
106693    int iCol1;         /* The current column index in pp1 */
106694    int iCol2;         /* The current column index in pp2 */
106695
106696    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
106697    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
106698    else iCol1 = 0;
106699
106700    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
106701    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
106702    else iCol2 = 0;
106703
106704    if( iCol1==iCol2 ){
106705      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
106706      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
106707      sqlite3_int64 iPrev = 0;
106708      int n = fts3PutColNumber(&p, iCol1);
106709      p1 += n;
106710      p2 += n;
106711
106712      /* At this point, both p1 and p2 point to the start of column-lists
106713      ** for the same column (the column with index iCol1 and iCol2).
106714      ** A column-list is a list of non-negative delta-encoded varints, each
106715      ** incremented by 2 before being stored. Each list is terminated by a
106716      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
106717      ** and writes the results to buffer p. p is left pointing to the byte
106718      ** after the list written. No terminator (POS_END or POS_COLUMN) is
106719      ** written to the output.
106720      */
106721      fts3GetDeltaVarint(&p1, &i1);
106722      fts3GetDeltaVarint(&p2, &i2);
106723      do {
106724        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
106725        iPrev -= 2;
106726        if( i1==i2 ){
106727          fts3ReadNextPos(&p1, &i1);
106728          fts3ReadNextPos(&p2, &i2);
106729        }else if( i1<i2 ){
106730          fts3ReadNextPos(&p1, &i1);
106731        }else{
106732          fts3ReadNextPos(&p2, &i2);
106733        }
106734      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
106735    }else if( iCol1<iCol2 ){
106736      p1 += fts3PutColNumber(&p, iCol1);
106737      fts3ColumnlistCopy(&p, &p1);
106738    }else{
106739      p2 += fts3PutColNumber(&p, iCol2);
106740      fts3ColumnlistCopy(&p, &p2);
106741    }
106742  }
106743
106744  *p++ = POS_END;
106745  *pp = p;
106746  *pp1 = p1 + 1;
106747  *pp2 = p2 + 1;
106748}
106749
106750/*
106751** nToken==1 searches for adjacent positions.
106752*/
106753static int fts3PoslistPhraseMerge(
106754  char **pp,                      /* Output buffer */
106755  int nToken,                     /* Maximum difference in token positions */
106756  int isSaveLeft,                 /* Save the left position */
106757  char **pp1,                     /* Left input list */
106758  char **pp2                      /* Right input list */
106759){
106760  char *p = (pp ? *pp : 0);
106761  char *p1 = *pp1;
106762  char *p2 = *pp2;
106763
106764  int iCol1 = 0;
106765  int iCol2 = 0;
106766  assert( *p1!=0 && *p2!=0 );
106767  if( *p1==POS_COLUMN ){
106768    p1++;
106769    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
106770  }
106771  if( *p2==POS_COLUMN ){
106772    p2++;
106773    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
106774  }
106775
106776  while( 1 ){
106777    if( iCol1==iCol2 ){
106778      char *pSave = p;
106779      sqlite3_int64 iPrev = 0;
106780      sqlite3_int64 iPos1 = 0;
106781      sqlite3_int64 iPos2 = 0;
106782
106783      if( pp && iCol1 ){
106784        *p++ = POS_COLUMN;
106785        p += sqlite3Fts3PutVarint(p, iCol1);
106786      }
106787
106788      assert( *p1!=POS_END && *p1!=POS_COLUMN );
106789      assert( *p2!=POS_END && *p2!=POS_COLUMN );
106790      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
106791      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
106792
106793      while( 1 ){
106794        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
106795          sqlite3_int64 iSave;
106796          if( !pp ){
106797            fts3PoslistCopy(0, &p2);
106798            fts3PoslistCopy(0, &p1);
106799            *pp1 = p1;
106800            *pp2 = p2;
106801            return 1;
106802          }
106803          iSave = isSaveLeft ? iPos1 : iPos2;
106804          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
106805          pSave = 0;
106806        }
106807        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
106808          if( (*p2&0xFE)==0 ) break;
106809          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
106810        }else{
106811          if( (*p1&0xFE)==0 ) break;
106812          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
106813        }
106814      }
106815
106816      if( pSave ){
106817        assert( pp && p );
106818        p = pSave;
106819      }
106820
106821      fts3ColumnlistCopy(0, &p1);
106822      fts3ColumnlistCopy(0, &p2);
106823      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
106824      if( 0==*p1 || 0==*p2 ) break;
106825
106826      p1++;
106827      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
106828      p2++;
106829      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
106830    }
106831
106832    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
106833    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
106834    ** end of the position list, or the 0x01 that precedes the next
106835    ** column-number in the position list.
106836    */
106837    else if( iCol1<iCol2 ){
106838      fts3ColumnlistCopy(0, &p1);
106839      if( 0==*p1 ) break;
106840      p1++;
106841      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
106842    }else{
106843      fts3ColumnlistCopy(0, &p2);
106844      if( 0==*p2 ) break;
106845      p2++;
106846      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
106847    }
106848  }
106849
106850  fts3PoslistCopy(0, &p2);
106851  fts3PoslistCopy(0, &p1);
106852  *pp1 = p1;
106853  *pp2 = p2;
106854  if( !pp || *pp==p ){
106855    return 0;
106856  }
106857  *p++ = 0x00;
106858  *pp = p;
106859  return 1;
106860}
106861
106862/*
106863** Merge two position-lists as required by the NEAR operator.
106864*/
106865static int fts3PoslistNearMerge(
106866  char **pp,                      /* Output buffer */
106867  char *aTmp,                     /* Temporary buffer space */
106868  int nRight,                     /* Maximum difference in token positions */
106869  int nLeft,                      /* Maximum difference in token positions */
106870  char **pp1,                     /* IN/OUT: Left input list */
106871  char **pp2                      /* IN/OUT: Right input list */
106872){
106873  char *p1 = *pp1;
106874  char *p2 = *pp2;
106875
106876  if( !pp ){
106877    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
106878    *pp1 = p1;
106879    *pp2 = p2;
106880    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
106881  }else{
106882    char *pTmp1 = aTmp;
106883    char *pTmp2;
106884    char *aTmp2;
106885    int res = 1;
106886
106887    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
106888    aTmp2 = pTmp2 = pTmp1;
106889    *pp1 = p1;
106890    *pp2 = p2;
106891    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
106892    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
106893      fts3PoslistMerge(pp, &aTmp, &aTmp2);
106894    }else if( pTmp1!=aTmp ){
106895      fts3PoslistCopy(pp, &aTmp);
106896    }else if( pTmp2!=aTmp2 ){
106897      fts3PoslistCopy(pp, &aTmp2);
106898    }else{
106899      res = 0;
106900    }
106901
106902    return res;
106903  }
106904}
106905
106906/*
106907** Values that may be used as the first parameter to fts3DoclistMerge().
106908*/
106909#define MERGE_NOT        2        /* D + D -> D */
106910#define MERGE_AND        3        /* D + D -> D */
106911#define MERGE_OR         4        /* D + D -> D */
106912#define MERGE_POS_OR     5        /* P + P -> P */
106913#define MERGE_PHRASE     6        /* P + P -> D */
106914#define MERGE_POS_PHRASE 7        /* P + P -> P */
106915#define MERGE_NEAR       8        /* P + P -> D */
106916#define MERGE_POS_NEAR   9        /* P + P -> P */
106917
106918/*
106919** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
106920** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
106921** which is guaranteed to be large enough to hold the results. The number
106922** of bytes written to aBuffer is stored in *pnBuffer before returning.
106923**
106924** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
106925** occurs while allocating a temporary buffer as part of the merge operation,
106926** SQLITE_NOMEM is returned.
106927*/
106928static int fts3DoclistMerge(
106929  int mergetype,                  /* One of the MERGE_XXX constants */
106930  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
106931  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
106932  char *aBuffer,                  /* Pre-allocated output buffer */
106933  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
106934  char *a1,                       /* Buffer containing first doclist */
106935  int n1,                         /* Size of buffer a1 */
106936  char *a2,                       /* Buffer containing second doclist */
106937  int n2                          /* Size of buffer a2 */
106938){
106939  sqlite3_int64 i1 = 0;
106940  sqlite3_int64 i2 = 0;
106941  sqlite3_int64 iPrev = 0;
106942
106943  char *p = aBuffer;
106944  char *p1 = a1;
106945  char *p2 = a2;
106946  char *pEnd1 = &a1[n1];
106947  char *pEnd2 = &a2[n2];
106948
106949  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
106950       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
106951       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
106952       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
106953  );
106954
106955  if( !aBuffer ){
106956    *pnBuffer = 0;
106957    return SQLITE_NOMEM;
106958  }
106959
106960  /* Read the first docid from each doclist */
106961  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
106962  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
106963
106964  switch( mergetype ){
106965    case MERGE_OR:
106966    case MERGE_POS_OR:
106967      while( p1 || p2 ){
106968        if( p2 && p1 && i1==i2 ){
106969          fts3PutDeltaVarint(&p, &iPrev, i1);
106970          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
106971          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
106972          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
106973        }else if( !p2 || (p1 && i1<i2) ){
106974          fts3PutDeltaVarint(&p, &iPrev, i1);
106975          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
106976          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
106977        }else{
106978          fts3PutDeltaVarint(&p, &iPrev, i2);
106979          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
106980          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
106981        }
106982      }
106983      break;
106984
106985    case MERGE_AND:
106986      while( p1 && p2 ){
106987        if( i1==i2 ){
106988          fts3PutDeltaVarint(&p, &iPrev, i1);
106989          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
106990          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
106991        }else if( i1<i2 ){
106992          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
106993        }else{
106994          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
106995        }
106996      }
106997      break;
106998
106999    case MERGE_NOT:
107000      while( p1 ){
107001        if( p2 && i1==i2 ){
107002          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107003          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107004        }else if( !p2 || i1<i2 ){
107005          fts3PutDeltaVarint(&p, &iPrev, i1);
107006          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107007        }else{
107008          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107009        }
107010      }
107011      break;
107012
107013    case MERGE_POS_PHRASE:
107014    case MERGE_PHRASE: {
107015      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
107016      while( p1 && p2 ){
107017        if( i1==i2 ){
107018          char *pSave = p;
107019          sqlite3_int64 iPrevSave = iPrev;
107020          fts3PutDeltaVarint(&p, &iPrev, i1);
107021          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
107022            p = pSave;
107023            iPrev = iPrevSave;
107024          }
107025          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107026          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107027        }else if( i1<i2 ){
107028          fts3PoslistCopy(0, &p1);
107029          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107030        }else{
107031          fts3PoslistCopy(0, &p2);
107032          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107033        }
107034      }
107035      break;
107036    }
107037
107038    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
107039      char *aTmp = 0;
107040      char **ppPos = 0;
107041
107042      if( mergetype==MERGE_POS_NEAR ){
107043        ppPos = &p;
107044        aTmp = sqlite3_malloc(2*(n1+n2+1));
107045        if( !aTmp ){
107046          return SQLITE_NOMEM;
107047        }
107048      }
107049
107050      while( p1 && p2 ){
107051        if( i1==i2 ){
107052          char *pSave = p;
107053          sqlite3_int64 iPrevSave = iPrev;
107054          fts3PutDeltaVarint(&p, &iPrev, i1);
107055
107056          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
107057            iPrev = iPrevSave;
107058            p = pSave;
107059          }
107060
107061          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107062          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107063        }else if( i1<i2 ){
107064          fts3PoslistCopy(0, &p1);
107065          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107066        }else{
107067          fts3PoslistCopy(0, &p2);
107068          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107069        }
107070      }
107071      sqlite3_free(aTmp);
107072      break;
107073    }
107074  }
107075
107076  *pnBuffer = (int)(p-aBuffer);
107077  return SQLITE_OK;
107078}
107079
107080/*
107081** A pointer to an instance of this structure is used as the context
107082** argument to sqlite3Fts3SegReaderIterate()
107083*/
107084typedef struct TermSelect TermSelect;
107085struct TermSelect {
107086  int isReqPos;
107087  char *aOutput;                  /* Malloc'd output buffer */
107088  int nOutput;                    /* Size of output in bytes */
107089};
107090
107091/*
107092** This function is used as the sqlite3Fts3SegReaderIterate() callback when
107093** querying the full-text index for a doclist associated with a term or
107094** term-prefix.
107095*/
107096static int fts3TermSelectCb(
107097  Fts3Table *p,                   /* Virtual table object */
107098  void *pContext,                 /* Pointer to TermSelect structure */
107099  char *zTerm,
107100  int nTerm,
107101  char *aDoclist,
107102  int nDoclist
107103){
107104  TermSelect *pTS = (TermSelect *)pContext;
107105  int nNew = pTS->nOutput + nDoclist;
107106  char *aNew = sqlite3_malloc(nNew);
107107
107108  UNUSED_PARAMETER(p);
107109  UNUSED_PARAMETER(zTerm);
107110  UNUSED_PARAMETER(nTerm);
107111
107112  if( !aNew ){
107113    return SQLITE_NOMEM;
107114  }
107115
107116  if( pTS->nOutput==0 ){
107117    /* If this is the first term selected, copy the doclist to the output
107118    ** buffer using memcpy(). TODO: Add a way to transfer control of the
107119    ** aDoclist buffer from the caller so as to avoid the memcpy().
107120    */
107121    memcpy(aNew, aDoclist, nDoclist);
107122  }else{
107123    /* The output buffer is not empty. Merge doclist aDoclist with the
107124    ** existing output. This can only happen with prefix-searches (as
107125    ** searches for exact terms return exactly one doclist).
107126    */
107127    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
107128    fts3DoclistMerge(mergetype, 0, 0,
107129        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
107130    );
107131  }
107132
107133  sqlite3_free(pTS->aOutput);
107134  pTS->aOutput = aNew;
107135  pTS->nOutput = nNew;
107136
107137  return SQLITE_OK;
107138}
107139
107140/*
107141** This function retreives the doclist for the specified term (or term
107142** prefix) from the database.
107143**
107144** The returned doclist may be in one of two formats, depending on the
107145** value of parameter isReqPos. If isReqPos is zero, then the doclist is
107146** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
107147** is non-zero, then the returned list is in the same format as is stored
107148** in the database without the found length specifier at the start of on-disk
107149** doclists.
107150*/
107151static int fts3TermSelect(
107152  Fts3Table *p,                   /* Virtual table handle */
107153  int iColumn,                    /* Column to query (or -ve for all columns) */
107154  const char *zTerm,              /* Term to query for */
107155  int nTerm,                      /* Size of zTerm in bytes */
107156  int isPrefix,                   /* True for a prefix search */
107157  int isReqPos,                   /* True to include position lists in output */
107158  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
107159  char **ppOut                    /* OUT: Malloced result buffer */
107160){
107161  int i;
107162  TermSelect tsc;
107163  Fts3SegFilter filter;           /* Segment term filter configuration */
107164  Fts3SegReader **apSegment;      /* Array of segments to read data from */
107165  int nSegment = 0;               /* Size of apSegment array */
107166  int nAlloc = 16;                /* Allocated size of segment array */
107167  int rc;                         /* Return code */
107168  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
107169  int iAge = 0;                   /* Used to assign ages to segments */
107170
107171  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
107172  if( !apSegment ) return SQLITE_NOMEM;
107173  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
107174  if( rc!=SQLITE_OK ) goto finished;
107175  if( apSegment[0] ){
107176    nSegment = 1;
107177  }
107178
107179  /* Loop through the entire %_segdir table. For each segment, create a
107180  ** Fts3SegReader to iterate through the subset of the segment leaves
107181  ** that may contain a term that matches zTerm/nTerm. For non-prefix
107182  ** searches, this is always a single leaf. For prefix searches, this
107183  ** may be a contiguous block of leaves.
107184  **
107185  ** The code in this loop does not actually load any leaves into memory
107186  ** (unless the root node happens to be a leaf). It simply examines the
107187  ** b-tree structure to determine which leaves need to be inspected.
107188  */
107189  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
107190  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
107191    Fts3SegReader *pNew = 0;
107192    int nRoot = sqlite3_column_bytes(pStmt, 4);
107193    char const *zRoot = sqlite3_column_blob(pStmt, 4);
107194    if( sqlite3_column_int64(pStmt, 1)==0 ){
107195      /* The entire segment is stored on the root node (which must be a
107196      ** leaf). Do not bother inspecting any data in this case, just
107197      ** create a Fts3SegReader to scan the single leaf.
107198      */
107199      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
107200    }else{
107201      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
107202      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
107203      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
107204      if( rc==SQLITE_OK ){
107205        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
107206        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
107207      }
107208
107209      /* The following call to ReadBlock() serves to reset the SQL statement
107210      ** used to retrieve blocks of data from the %_segments table. If it is
107211      ** not reset here, then it may remain classified as an active statement
107212      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
107213      ** failing.
107214      */
107215      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
107216      if( rc==SQLITE_OK ){
107217        rc = rc2;
107218      }
107219    }
107220    iAge++;
107221
107222    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
107223    assert( pNew!=0 || rc!=SQLITE_OK );
107224    if( pNew ){
107225      if( nSegment==nAlloc ){
107226        Fts3SegReader **pArray;
107227        nAlloc += 16;
107228        pArray = (Fts3SegReader **)sqlite3_realloc(
107229            apSegment, nAlloc*sizeof(Fts3SegReader *)
107230        );
107231        if( !pArray ){
107232          sqlite3Fts3SegReaderFree(p, pNew);
107233          rc = SQLITE_NOMEM;
107234          goto finished;
107235        }
107236        apSegment = pArray;
107237      }
107238      apSegment[nSegment++] = pNew;
107239    }
107240  }
107241  if( rc!=SQLITE_DONE ){
107242    assert( rc!=SQLITE_OK );
107243    goto finished;
107244  }
107245
107246  memset(&tsc, 0, sizeof(TermSelect));
107247  tsc.isReqPos = isReqPos;
107248
107249  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
107250        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
107251        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
107252        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
107253  filter.iCol = iColumn;
107254  filter.zTerm = zTerm;
107255  filter.nTerm = nTerm;
107256
107257  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
107258      fts3TermSelectCb, (void *)&tsc
107259  );
107260
107261  if( rc==SQLITE_OK ){
107262    *ppOut = tsc.aOutput;
107263    *pnOut = tsc.nOutput;
107264  }else{
107265    sqlite3_free(tsc.aOutput);
107266  }
107267
107268finished:
107269  sqlite3_reset(pStmt);
107270  for(i=0; i<nSegment; i++){
107271    sqlite3Fts3SegReaderFree(p, apSegment[i]);
107272  }
107273  sqlite3_free(apSegment);
107274  return rc;
107275}
107276
107277
107278/*
107279** Return a DocList corresponding to the phrase *pPhrase.
107280*/
107281static int fts3PhraseSelect(
107282  Fts3Table *p,                   /* Virtual table handle */
107283  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
107284  int isReqPos,                   /* True if output should contain positions */
107285  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107286  int *pnOut                      /* OUT: Size of buffer at *paOut */
107287){
107288  char *pOut = 0;
107289  int nOut = 0;
107290  int rc = SQLITE_OK;
107291  int ii;
107292  int iCol = pPhrase->iColumn;
107293  int isTermPos = (pPhrase->nToken>1 || isReqPos);
107294
107295  for(ii=0; ii<pPhrase->nToken; ii++){
107296    struct PhraseToken *pTok = &pPhrase->aToken[ii];
107297    char *z = pTok->z;            /* Next token of the phrase */
107298    int n = pTok->n;              /* Size of z in bytes */
107299    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
107300    char *pList;                  /* Pointer to token doclist */
107301    int nList;                    /* Size of buffer at pList */
107302
107303    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
107304    if( rc!=SQLITE_OK ) break;
107305
107306    if( ii==0 ){
107307      pOut = pList;
107308      nOut = nList;
107309    }else{
107310      /* Merge the new term list and the current output. If this is the
107311      ** last term in the phrase, and positions are not required in the
107312      ** output of this function, the positions can be dropped as part
107313      ** of this merge. Either way, the result of this merge will be
107314      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
107315      ** so that it is safe to use pList as the output as well as an input
107316      ** in this case.
107317      */
107318      int mergetype = MERGE_POS_PHRASE;
107319      if( ii==pPhrase->nToken-1 && !isReqPos ){
107320        mergetype = MERGE_PHRASE;
107321      }
107322      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
107323      sqlite3_free(pOut);
107324      pOut = pList;
107325    }
107326    assert( nOut==0 || pOut!=0 );
107327  }
107328
107329  if( rc==SQLITE_OK ){
107330    *paOut = pOut;
107331    *pnOut = nOut;
107332  }else{
107333    sqlite3_free(pOut);
107334  }
107335  return rc;
107336}
107337
107338static int fts3NearMerge(
107339  int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
107340  int nNear,                      /* Parameter to NEAR operator */
107341  int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
107342  char *aLeft,                    /* Doclist for LHS (incl. positions) */
107343  int nLeft,                      /* Size of LHS doclist in bytes */
107344  int nTokenRight,                /* As nTokenLeft */
107345  char *aRight,                   /* As aLeft */
107346  int nRight,                     /* As nRight */
107347  char **paOut,                   /* OUT: Results of merge (malloced) */
107348  int *pnOut                      /* OUT: Sized of output buffer */
107349){
107350  char *aOut;
107351  int rc;
107352
107353  assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
107354
107355  aOut = sqlite3_malloc(nLeft+nRight+1);
107356  if( aOut==0 ){
107357    rc = SQLITE_NOMEM;
107358  }else{
107359    rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
107360      aOut, pnOut, aLeft, nLeft, aRight, nRight
107361    );
107362    if( rc!=SQLITE_OK ){
107363      sqlite3_free(aOut);
107364      aOut = 0;
107365    }
107366  }
107367
107368  *paOut = aOut;
107369  return rc;
107370}
107371
107372SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
107373  int rc;
107374  if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
107375    sqlite3_free(pLeft->aDoclist);
107376    sqlite3_free(pRight->aDoclist);
107377    pRight->aDoclist = 0;
107378    pLeft->aDoclist = 0;
107379    rc = SQLITE_OK;
107380  }else{
107381    char *aOut;
107382    int nOut;
107383
107384    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
107385        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107386        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107387        &aOut, &nOut
107388    );
107389    if( rc!=SQLITE_OK ) return rc;
107390    sqlite3_free(pRight->aDoclist);
107391    pRight->aDoclist = aOut;
107392    pRight->nDoclist = nOut;
107393
107394    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
107395        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107396        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107397        &aOut, &nOut
107398    );
107399    sqlite3_free(pLeft->aDoclist);
107400    pLeft->aDoclist = aOut;
107401    pLeft->nDoclist = nOut;
107402  }
107403  return rc;
107404}
107405
107406/*
107407** Evaluate the full-text expression pExpr against fts3 table pTab. Store
107408** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
107409** the space needed to store the output.  The caller is responsible for
107410** freeing the space when it has finished.
107411*/
107412static int evalFts3Expr(
107413  Fts3Table *p,                   /* Virtual table handle */
107414  Fts3Expr *pExpr,                /* Parsed fts3 expression */
107415  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107416  int *pnOut,                     /* OUT: Size of buffer at *paOut */
107417  int isReqPos                    /* Require positions in output buffer */
107418){
107419  int rc = SQLITE_OK;             /* Return code */
107420
107421  /* Zero the output parameters. */
107422  *paOut = 0;
107423  *pnOut = 0;
107424
107425  if( pExpr ){
107426    assert( pExpr->eType==FTSQUERY_PHRASE
107427         || pExpr->eType==FTSQUERY_NEAR
107428         || isReqPos==0
107429    );
107430    if( pExpr->eType==FTSQUERY_PHRASE ){
107431      rc = fts3PhraseSelect(p, pExpr->pPhrase,
107432          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
107433          paOut, pnOut
107434      );
107435    }else{
107436      char *aLeft;
107437      char *aRight;
107438      int nLeft;
107439      int nRight;
107440
107441      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
107442       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
107443      ){
107444        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
107445            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
107446        );
107447        switch( pExpr->eType ){
107448          case FTSQUERY_NEAR: {
107449            Fts3Expr *pLeft;
107450            Fts3Expr *pRight;
107451            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
107452
107453            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
107454              mergetype = MERGE_POS_NEAR;
107455            }
107456            pLeft = pExpr->pLeft;
107457            while( pLeft->eType==FTSQUERY_NEAR ){
107458              pLeft=pLeft->pRight;
107459            }
107460            pRight = pExpr->pRight;
107461            assert( pRight->eType==FTSQUERY_PHRASE );
107462            assert( pLeft->eType==FTSQUERY_PHRASE );
107463
107464            rc = fts3NearMerge(mergetype, pExpr->nNear,
107465                pLeft->pPhrase->nToken, aLeft, nLeft,
107466                pRight->pPhrase->nToken, aRight, nRight,
107467                paOut, pnOut
107468            );
107469            sqlite3_free(aLeft);
107470            break;
107471          }
107472
107473          case FTSQUERY_OR: {
107474            /* Allocate a buffer for the output. The maximum size is the
107475            ** sum of the sizes of the two input buffers. The +1 term is
107476            ** so that a buffer of zero bytes is never allocated - this can
107477            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
107478            */
107479            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
107480            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
107481                aLeft, nLeft, aRight, nRight
107482            );
107483            *paOut = aBuffer;
107484            sqlite3_free(aLeft);
107485            break;
107486          }
107487
107488          default: {
107489            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
107490            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
107491                aLeft, nLeft, aRight, nRight
107492            );
107493            *paOut = aLeft;
107494            break;
107495          }
107496        }
107497      }
107498      sqlite3_free(aRight);
107499    }
107500  }
107501
107502  return rc;
107503}
107504
107505/*
107506** This is the xFilter interface for the virtual table.  See
107507** the virtual table xFilter method documentation for additional
107508** information.
107509**
107510** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
107511** the %_content table.
107512**
107513** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
107514** in the %_content table.
107515**
107516** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
107517** column on the left-hand side of the MATCH operator is column
107518** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
107519** side of the MATCH operator.
107520*/
107521/* TODO(shess) Upgrade the cursor initialization and destruction to
107522** account for fts3FilterMethod() being called multiple times on the
107523** same cursor. The current solution is very fragile. Apply fix to
107524** fts3 as appropriate.
107525*/
107526static int fts3FilterMethod(
107527  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
107528  int idxNum,                     /* Strategy index */
107529  const char *idxStr,             /* Unused */
107530  int nVal,                       /* Number of elements in apVal */
107531  sqlite3_value **apVal           /* Arguments for the indexing scheme */
107532){
107533  const char *azSql[] = {
107534    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
107535    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
107536  };
107537  int rc;                         /* Return code */
107538  char *zSql;                     /* SQL statement used to access %_content */
107539  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
107540  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107541
107542  UNUSED_PARAMETER(idxStr);
107543  UNUSED_PARAMETER(nVal);
107544
107545  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
107546  assert( nVal==0 || nVal==1 );
107547  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
107548
107549  /* In case the cursor has been used before, clear it now. */
107550  sqlite3_finalize(pCsr->pStmt);
107551  sqlite3_free(pCsr->aDoclist);
107552  sqlite3Fts3ExprFree(pCsr->pExpr);
107553  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
107554
107555  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
107556  ** statement loops through all rows of the %_content table. For a
107557  ** full-text query or docid lookup, the statement retrieves a single
107558  ** row by docid.
107559  */
107560  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
107561  if( !zSql ){
107562    rc = SQLITE_NOMEM;
107563  }else{
107564    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
107565    sqlite3_free(zSql);
107566  }
107567  if( rc!=SQLITE_OK ) return rc;
107568  pCsr->eSearch = (i16)idxNum;
107569
107570  if( idxNum==FTS3_DOCID_SEARCH ){
107571    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
107572  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
107573    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
107574    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
107575
107576    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
107577      return SQLITE_NOMEM;
107578    }
107579
107580    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
107581        iCol, zQuery, -1, &pCsr->pExpr
107582    );
107583    if( rc!=SQLITE_OK ){
107584      if( rc==SQLITE_ERROR ){
107585        p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
107586                                          zQuery);
107587      }
107588      return rc;
107589    }
107590
107591    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
107592    pCsr->pNextId = pCsr->aDoclist;
107593    pCsr->iPrevId = 0;
107594  }
107595
107596  if( rc!=SQLITE_OK ) return rc;
107597  return fts3NextMethod(pCursor);
107598}
107599
107600/*
107601** This is the xEof method of the virtual table. SQLite calls this
107602** routine to find out if it has reached the end of a result set.
107603*/
107604static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
107605  return ((Fts3Cursor *)pCursor)->isEof;
107606}
107607
107608/*
107609** This is the xRowid method. The SQLite core calls this routine to
107610** retrieve the rowid for the current row of the result set. fts3
107611** exposes %_content.docid as the rowid for the virtual table. The
107612** rowid should be written to *pRowid.
107613*/
107614static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
107615  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
107616  if( pCsr->aDoclist ){
107617    *pRowid = pCsr->iPrevId;
107618  }else{
107619    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
107620  }
107621  return SQLITE_OK;
107622}
107623
107624/*
107625** This is the xColumn method, called by SQLite to request a value from
107626** the row that the supplied cursor currently points to.
107627*/
107628static int fts3ColumnMethod(
107629  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
107630  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
107631  int iCol                        /* Index of column to read value from */
107632){
107633  int rc;                         /* Return Code */
107634  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
107635  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
107636
107637  /* The column value supplied by SQLite must be in range. */
107638  assert( iCol>=0 && iCol<=p->nColumn+1 );
107639
107640  if( iCol==p->nColumn+1 ){
107641    /* This call is a request for the "docid" column. Since "docid" is an
107642    ** alias for "rowid", use the xRowid() method to obtain the value.
107643    */
107644    sqlite3_int64 iRowid;
107645    rc = fts3RowidMethod(pCursor, &iRowid);
107646    sqlite3_result_int64(pContext, iRowid);
107647  }else if( iCol==p->nColumn ){
107648    /* The extra column whose name is the same as the table.
107649    ** Return a blob which is a pointer to the cursor.
107650    */
107651    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
107652    rc = SQLITE_OK;
107653  }else{
107654    rc = fts3CursorSeek(0, pCsr);
107655    if( rc==SQLITE_OK ){
107656      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
107657    }
107658  }
107659  return rc;
107660}
107661
107662/*
107663** This function is the implementation of the xUpdate callback used by
107664** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
107665** inserted, updated or deleted.
107666*/
107667static int fts3UpdateMethod(
107668  sqlite3_vtab *pVtab,            /* Virtual table handle */
107669  int nArg,                       /* Size of argument array */
107670  sqlite3_value **apVal,          /* Array of arguments */
107671  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
107672){
107673  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
107674}
107675
107676/*
107677** Implementation of xSync() method. Flush the contents of the pending-terms
107678** hash-table to the database.
107679*/
107680static int fts3SyncMethod(sqlite3_vtab *pVtab){
107681  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
107682}
107683
107684/*
107685** Implementation of xBegin() method. This is a no-op.
107686*/
107687static int fts3BeginMethod(sqlite3_vtab *pVtab){
107688  UNUSED_PARAMETER(pVtab);
107689  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
107690  return SQLITE_OK;
107691}
107692
107693/*
107694** Implementation of xCommit() method. This is a no-op. The contents of
107695** the pending-terms hash-table have already been flushed into the database
107696** by fts3SyncMethod().
107697*/
107698static int fts3CommitMethod(sqlite3_vtab *pVtab){
107699  UNUSED_PARAMETER(pVtab);
107700  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
107701  return SQLITE_OK;
107702}
107703
107704/*
107705** Implementation of xRollback(). Discard the contents of the pending-terms
107706** hash-table. Any changes made to the database are reverted by SQLite.
107707*/
107708static int fts3RollbackMethod(sqlite3_vtab *pVtab){
107709  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
107710  return SQLITE_OK;
107711}
107712
107713/*
107714** Load the doclist associated with expression pExpr to pExpr->aDoclist.
107715** The loaded doclist contains positions as well as the document ids.
107716** This is used by the matchinfo(), snippet() and offsets() auxillary
107717** functions.
107718*/
107719SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
107720  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
107721}
107722
107723/*
107724** After ExprLoadDoclist() (see above) has been called, this function is
107725** used to iterate/search through the position lists that make up the doclist
107726** stored in pExpr->aDoclist.
107727*/
107728SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
107729  Fts3Expr *pExpr,                /* Access this expressions doclist */
107730  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
107731  int iCol                        /* Column of requested pos-list */
107732){
107733  assert( pExpr->isLoaded );
107734  if( pExpr->aDoclist ){
107735    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107736    char *pCsr = pExpr->pCurrent;
107737
107738    assert( pCsr );
107739    while( pCsr<pEnd ){
107740      if( pExpr->iCurrent<iDocid ){
107741        fts3PoslistCopy(0, &pCsr);
107742        if( pCsr<pEnd ){
107743          fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
107744        }
107745        pExpr->pCurrent = pCsr;
107746      }else{
107747        if( pExpr->iCurrent==iDocid ){
107748          int iThis = 0;
107749          if( iCol<0 ){
107750            /* If iCol is negative, return a pointer to the start of the
107751            ** position-list (instead of a pointer to the start of a list
107752            ** of offsets associated with a specific column).
107753            */
107754            return pCsr;
107755          }
107756          while( iThis<iCol ){
107757            fts3ColumnlistCopy(0, &pCsr);
107758            if( *pCsr==0x00 ) return 0;
107759            pCsr++;
107760            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
107761          }
107762          if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
107763        }
107764        return 0;
107765      }
107766    }
107767  }
107768
107769  return 0;
107770}
107771
107772/*
107773** Helper function used by the implementation of the overloaded snippet(),
107774** offsets() and optimize() SQL functions.
107775**
107776** If the value passed as the third argument is a blob of size
107777** sizeof(Fts3Cursor*), then the blob contents are copied to the
107778** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
107779** message is written to context pContext and SQLITE_ERROR returned. The
107780** string passed via zFunc is used as part of the error message.
107781*/
107782static int fts3FunctionArg(
107783  sqlite3_context *pContext,      /* SQL function call context */
107784  const char *zFunc,              /* Function name */
107785  sqlite3_value *pVal,            /* argv[0] passed to function */
107786  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
107787){
107788  Fts3Cursor *pRet;
107789  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
107790   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
107791  ){
107792    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
107793    sqlite3_result_error(pContext, zErr, -1);
107794    sqlite3_free(zErr);
107795    return SQLITE_ERROR;
107796  }
107797  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
107798  *ppCsr = pRet;
107799  return SQLITE_OK;
107800}
107801
107802/*
107803** Implementation of the snippet() function for FTS3
107804*/
107805static void fts3SnippetFunc(
107806  sqlite3_context *pContext,      /* SQLite function call context */
107807  int nVal,                       /* Size of apVal[] array */
107808  sqlite3_value **apVal           /* Array of arguments */
107809){
107810  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
107811  const char *zStart = "<b>";
107812  const char *zEnd = "</b>";
107813  const char *zEllipsis = "<b>...</b>";
107814  int iCol = -1;
107815  int nToken = 15;                /* Default number of tokens in snippet */
107816
107817  /* There must be at least one argument passed to this function (otherwise
107818  ** the non-overloaded version would have been called instead of this one).
107819  */
107820  assert( nVal>=1 );
107821
107822  if( nVal>6 ){
107823    sqlite3_result_error(pContext,
107824        "wrong number of arguments to function snippet()", -1);
107825    return;
107826  }
107827  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
107828
107829  switch( nVal ){
107830    case 6: nToken = sqlite3_value_int(apVal[5]);
107831    case 5: iCol = sqlite3_value_int(apVal[4]);
107832    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
107833    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
107834    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
107835  }
107836  if( !zEllipsis || !zEnd || !zStart ){
107837    sqlite3_result_error_nomem(pContext);
107838  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
107839    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
107840  }
107841}
107842
107843/*
107844** Implementation of the offsets() function for FTS3
107845*/
107846static void fts3OffsetsFunc(
107847  sqlite3_context *pContext,      /* SQLite function call context */
107848  int nVal,                       /* Size of argument array */
107849  sqlite3_value **apVal           /* Array of arguments */
107850){
107851  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
107852
107853  UNUSED_PARAMETER(nVal);
107854
107855  assert( nVal==1 );
107856  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
107857  assert( pCsr );
107858  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
107859    sqlite3Fts3Offsets(pContext, pCsr);
107860  }
107861}
107862
107863/*
107864** Implementation of the special optimize() function for FTS3. This
107865** function merges all segments in the database to a single segment.
107866** Example usage is:
107867**
107868**   SELECT optimize(t) FROM t LIMIT 1;
107869**
107870** where 't' is the name of an FTS3 table.
107871*/
107872static void fts3OptimizeFunc(
107873  sqlite3_context *pContext,      /* SQLite function call context */
107874  int nVal,                       /* Size of argument array */
107875  sqlite3_value **apVal           /* Array of arguments */
107876){
107877  int rc;                         /* Return code */
107878  Fts3Table *p;                   /* Virtual table handle */
107879  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
107880
107881  UNUSED_PARAMETER(nVal);
107882
107883  assert( nVal==1 );
107884  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
107885  p = (Fts3Table *)pCursor->base.pVtab;
107886  assert( p );
107887
107888  rc = sqlite3Fts3Optimize(p);
107889
107890  switch( rc ){
107891    case SQLITE_OK:
107892      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
107893      break;
107894    case SQLITE_DONE:
107895      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
107896      break;
107897    default:
107898      sqlite3_result_error_code(pContext, rc);
107899      break;
107900  }
107901}
107902
107903/*
107904** Implementation of the matchinfo() function for FTS3
107905*/
107906static void fts3MatchinfoFunc(
107907  sqlite3_context *pContext,      /* SQLite function call context */
107908  int nVal,                       /* Size of argument array */
107909  sqlite3_value **apVal           /* Array of arguments */
107910){
107911  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
107912
107913  if( nVal!=1 ){
107914    sqlite3_result_error(pContext,
107915        "wrong number of arguments to function matchinfo()", -1);
107916    return;
107917  }
107918
107919  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
107920    sqlite3Fts3Matchinfo(pContext, pCsr);
107921  }
107922}
107923
107924/*
107925** This routine implements the xFindFunction method for the FTS3
107926** virtual table.
107927*/
107928static int fts3FindFunctionMethod(
107929  sqlite3_vtab *pVtab,            /* Virtual table handle */
107930  int nArg,                       /* Number of SQL function arguments */
107931  const char *zName,              /* Name of SQL function */
107932  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
107933  void **ppArg                    /* Unused */
107934){
107935  struct Overloaded {
107936    const char *zName;
107937    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
107938  } aOverload[] = {
107939    { "snippet", fts3SnippetFunc },
107940    { "offsets", fts3OffsetsFunc },
107941    { "optimize", fts3OptimizeFunc },
107942    { "matchinfo", fts3MatchinfoFunc },
107943  };
107944  int i;                          /* Iterator variable */
107945
107946  UNUSED_PARAMETER(pVtab);
107947  UNUSED_PARAMETER(nArg);
107948  UNUSED_PARAMETER(ppArg);
107949
107950  for(i=0; i<SizeofArray(aOverload); i++){
107951    if( strcmp(zName, aOverload[i].zName)==0 ){
107952      *pxFunc = aOverload[i].xFunc;
107953      return 1;
107954    }
107955  }
107956
107957  /* No function of the specified name was found. Return 0. */
107958  return 0;
107959}
107960
107961/*
107962** Implementation of FTS3 xRename method. Rename an fts3 table.
107963*/
107964static int fts3RenameMethod(
107965  sqlite3_vtab *pVtab,            /* Virtual table handle */
107966  const char *zName               /* New name of table */
107967){
107968  Fts3Table *p = (Fts3Table *)pVtab;
107969  sqlite3 *db;                    /* Database connection */
107970  int rc;                         /* Return Code */
107971
107972  db = p->db;
107973  rc = SQLITE_OK;
107974  fts3DbExec(&rc, db,
107975    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
107976    p->zDb, p->zName, zName
107977  );
107978  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
107979  if( p->bHasDocsize ){
107980    fts3DbExec(&rc, db,
107981      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
107982      p->zDb, p->zName, zName
107983    );
107984    fts3DbExec(&rc, db,
107985      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
107986      p->zDb, p->zName, zName
107987    );
107988  }
107989  fts3DbExec(&rc, db,
107990    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
107991    p->zDb, p->zName, zName
107992  );
107993  fts3DbExec(&rc, db,
107994    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
107995    p->zDb, p->zName, zName
107996  );
107997  return rc;
107998}
107999
108000static const sqlite3_module fts3Module = {
108001  /* iVersion      */ 0,
108002  /* xCreate       */ fts3CreateMethod,
108003  /* xConnect      */ fts3ConnectMethod,
108004  /* xBestIndex    */ fts3BestIndexMethod,
108005  /* xDisconnect   */ fts3DisconnectMethod,
108006  /* xDestroy      */ fts3DestroyMethod,
108007  /* xOpen         */ fts3OpenMethod,
108008  /* xClose        */ fulltextClose,
108009  /* xFilter       */ fts3FilterMethod,
108010  /* xNext         */ fts3NextMethod,
108011  /* xEof          */ fts3EofMethod,
108012  /* xColumn       */ fts3ColumnMethod,
108013  /* xRowid        */ fts3RowidMethod,
108014  /* xUpdate       */ fts3UpdateMethod,
108015  /* xBegin        */ fts3BeginMethod,
108016  /* xSync         */ fts3SyncMethod,
108017  /* xCommit       */ fts3CommitMethod,
108018  /* xRollback     */ fts3RollbackMethod,
108019  /* xFindFunction */ fts3FindFunctionMethod,
108020  /* xRename */       fts3RenameMethod,
108021};
108022
108023/*
108024** This function is registered as the module destructor (called when an
108025** FTS3 enabled database connection is closed). It frees the memory
108026** allocated for the tokenizer hash table.
108027*/
108028static void hashDestroy(void *p){
108029  Fts3Hash *pHash = (Fts3Hash *)p;
108030  sqlite3Fts3HashClear(pHash);
108031  sqlite3_free(pHash);
108032}
108033
108034/*
108035** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
108036** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
108037** two forward declarations are for functions declared in these files
108038** used to retrieve the respective implementations.
108039**
108040** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
108041** to by the argument to point a the "simple" tokenizer implementation.
108042** Function ...PorterTokenizerModule() sets *pModule to point to the
108043** porter tokenizer/stemmer implementation.
108044*/
108045SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108046SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108047SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108048
108049/*
108050** Initialise the fts3 extension. If this extension is built as part
108051** of the sqlite library, then this function is called directly by
108052** SQLite. If fts3 is built as a dynamically loadable extension, this
108053** function is called by the sqlite3_extension_init() entry point.
108054*/
108055SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){ // Android Change
108056  int rc = SQLITE_OK;
108057  Fts3Hash *pHash = 0;
108058  const sqlite3_tokenizer_module *pSimple = 0;
108059  const sqlite3_tokenizer_module *pPorter = 0;
108060
108061#ifdef SQLITE_ENABLE_ICU
108062  const sqlite3_tokenizer_module *pIcu = 0;
108063  sqlite3Fts3IcuTokenizerModule(&pIcu);
108064#endif
108065
108066  sqlite3Fts3SimpleTokenizerModule(&pSimple);
108067  sqlite3Fts3PorterTokenizerModule(&pPorter);
108068
108069  /* Allocate and initialise the hash-table used to store tokenizers. */
108070  pHash = sqlite3_malloc(sizeof(Fts3Hash));
108071  if( !pHash ){
108072    rc = SQLITE_NOMEM;
108073  }else{
108074    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
108075  }
108076
108077  /* Load the built-in tokenizers into the hash table */
108078  if( rc==SQLITE_OK ){
108079    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
108080     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
108081#ifdef SQLITE_ENABLE_ICU
108082     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
108083#endif
108084    ){
108085      rc = SQLITE_NOMEM;
108086    }
108087  }
108088
108089#ifdef SQLITE_TEST
108090  if( rc==SQLITE_OK ){
108091    rc = sqlite3Fts3ExprInitTestInterface(db);
108092  }
108093#endif
108094
108095  /* Create the virtual table wrapper around the hash-table and overload
108096  ** the two scalar functions. If this is successful, register the
108097  ** module with sqlite.
108098  */
108099  if( SQLITE_OK==rc
108100   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
108101   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
108102   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
108103   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
108104   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
108105  ){
108106    rc = sqlite3_create_module_v2(
108107        // Begin Android change
108108        // Also register as fts1 and fts2
108109        db, registerAs, &fts3Module, (void *)pHash, hashDestroy
108110        // End Android change
108111    );
108112    if( rc==SQLITE_OK ){
108113      rc = sqlite3_create_module_v2(
108114          db, "fts4", &fts3Module, (void *)pHash, 0
108115      );
108116    }
108117    return rc;
108118  }
108119
108120  /* An error has occurred. Delete the hash table and return the error code. */
108121  assert( rc!=SQLITE_OK );
108122  if( pHash ){
108123    sqlite3Fts3HashClear(pHash);
108124    sqlite3_free(pHash);
108125  }
108126  return rc;
108127}
108128
108129#if !SQLITE_CORE
108130SQLITE_API int sqlite3_extension_init(
108131  sqlite3 *db,
108132  char **pzErrMsg,
108133  const sqlite3_api_routines *pApi
108134){
108135  SQLITE_EXTENSION_INIT2(pApi)
108136  return sqlite3Fts3Init(db);
108137}
108138#endif
108139
108140#endif
108141
108142/************** End of fts3.c ************************************************/
108143/************** Begin file fts3_expr.c ***************************************/
108144/*
108145** 2008 Nov 28
108146**
108147** The author disclaims copyright to this source code.  In place of
108148** a legal notice, here is a blessing:
108149**
108150**    May you do good and not evil.
108151**    May you find forgiveness for yourself and forgive others.
108152**    May you share freely, never taking more than you give.
108153**
108154******************************************************************************
108155**
108156** This module contains code that implements a parser for fts3 query strings
108157** (the right-hand argument to the MATCH operator). Because the supported
108158** syntax is relatively simple, the whole tokenizer/parser system is
108159** hand-coded.
108160*/
108161#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
108162
108163/*
108164** By default, this module parses the legacy syntax that has been
108165** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
108166** is defined, then it uses the new syntax. The differences between
108167** the new and the old syntaxes are:
108168**
108169**  a) The new syntax supports parenthesis. The old does not.
108170**
108171**  b) The new syntax supports the AND and NOT operators. The old does not.
108172**
108173**  c) The old syntax supports the "-" token qualifier. This is not
108174**     supported by the new syntax (it is replaced by the NOT operator).
108175**
108176**  d) When using the old syntax, the OR operator has a greater precedence
108177**     than an implicit AND. When using the new, both implicity and explicit
108178**     AND operators have a higher precedence than OR.
108179**
108180** If compiled with SQLITE_TEST defined, then this module exports the
108181** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
108182** to zero causes the module to use the old syntax. If it is set to
108183** non-zero the new syntax is activated. This is so both syntaxes can
108184** be tested using a single build of testfixture.
108185**
108186** The following describes the syntax supported by the fts3 MATCH
108187** operator in a similar format to that used by the lemon parser
108188** generator. This module does not use actually lemon, it uses a
108189** custom parser.
108190**
108191**   query ::= andexpr (OR andexpr)*.
108192**
108193**   andexpr ::= notexpr (AND? notexpr)*.
108194**
108195**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
108196**   notexpr ::= LP query RP.
108197**
108198**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
108199**
108200**   distance_opt ::= .
108201**   distance_opt ::= / INTEGER.
108202**
108203**   phrase ::= TOKEN.
108204**   phrase ::= COLUMN:TOKEN.
108205**   phrase ::= "TOKEN TOKEN TOKEN...".
108206*/
108207
108208#ifdef SQLITE_TEST
108209SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
108210#else
108211# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
108212#  define sqlite3_fts3_enable_parentheses 1
108213# else
108214#  define sqlite3_fts3_enable_parentheses 0
108215# endif
108216#endif
108217
108218/*
108219** Default span for NEAR operators.
108220*/
108221#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
108222
108223
108224typedef struct ParseContext ParseContext;
108225struct ParseContext {
108226  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
108227  const char **azCol;                 /* Array of column names for fts3 table */
108228  int nCol;                           /* Number of entries in azCol[] */
108229  int iDefaultCol;                    /* Default column to query */
108230  sqlite3_context *pCtx;              /* Write error message here */
108231  int nNest;                          /* Number of nested brackets */
108232};
108233
108234/*
108235** This function is equivalent to the standard isspace() function.
108236**
108237** The standard isspace() can be awkward to use safely, because although it
108238** is defined to accept an argument of type int, its behaviour when passed
108239** an integer that falls outside of the range of the unsigned char type
108240** is undefined (and sometimes, "undefined" means segfault). This wrapper
108241** is defined to accept an argument of type char, and always returns 0 for
108242** any values that fall outside of the range of the unsigned char type (i.e.
108243** negative values).
108244*/
108245static int fts3isspace(char c){
108246  return (c&0x80)==0 ? isspace(c) : 0;
108247}
108248
108249/*
108250** Extract the next token from buffer z (length n) using the tokenizer
108251** and other information (column names etc.) in pParse. Create an Fts3Expr
108252** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
108253** single token and set *ppExpr to point to it. If the end of the buffer is
108254** reached before a token is found, set *ppExpr to zero. It is the
108255** responsibility of the caller to eventually deallocate the allocated
108256** Fts3Expr structure (if any) by passing it to sqlite3_free().
108257**
108258** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
108259** fails.
108260*/
108261static int getNextToken(
108262  ParseContext *pParse,                   /* fts3 query parse context */
108263  int iCol,                               /* Value for Fts3Phrase.iColumn */
108264  const char *z, int n,                   /* Input string */
108265  Fts3Expr **ppExpr,                      /* OUT: expression */
108266  int *pnConsumed                         /* OUT: Number of bytes consumed */
108267){
108268  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108269  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108270  int rc;
108271  sqlite3_tokenizer_cursor *pCursor;
108272  Fts3Expr *pRet = 0;
108273  int nConsumed = 0;
108274
108275  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
108276  if( rc==SQLITE_OK ){
108277    const char *zToken;
108278    int nToken, iStart, iEnd, iPosition;
108279    int nByte;                               /* total space to allocate */
108280
108281    pCursor->pTokenizer = pTokenizer;
108282    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
108283
108284    if( rc==SQLITE_OK ){
108285      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
108286      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
108287      if( !pRet ){
108288        rc = SQLITE_NOMEM;
108289      }else{
108290        memset(pRet, 0, nByte);
108291        pRet->eType = FTSQUERY_PHRASE;
108292        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
108293        pRet->pPhrase->nToken = 1;
108294        pRet->pPhrase->iColumn = iCol;
108295        pRet->pPhrase->aToken[0].n = nToken;
108296        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
108297        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
108298
108299        if( iEnd<n && z[iEnd]=='*' ){
108300          pRet->pPhrase->aToken[0].isPrefix = 1;
108301          iEnd++;
108302        }
108303        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
108304          pRet->pPhrase->isNot = 1;
108305        }
108306      }
108307      nConsumed = iEnd;
108308    }
108309
108310    pModule->xClose(pCursor);
108311  }
108312
108313  *pnConsumed = nConsumed;
108314  *ppExpr = pRet;
108315  return rc;
108316}
108317
108318
108319/*
108320** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
108321** then free the old allocation.
108322*/
108323static void *fts3ReallocOrFree(void *pOrig, int nNew){
108324  void *pRet = sqlite3_realloc(pOrig, nNew);
108325  if( !pRet ){
108326    sqlite3_free(pOrig);
108327  }
108328  return pRet;
108329}
108330
108331/*
108332** Buffer zInput, length nInput, contains the contents of a quoted string
108333** that appeared as part of an fts3 query expression. Neither quote character
108334** is included in the buffer. This function attempts to tokenize the entire
108335** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
108336** containing the results.
108337**
108338** If successful, SQLITE_OK is returned and *ppExpr set to point at the
108339** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
108340** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
108341** to 0.
108342*/
108343static int getNextString(
108344  ParseContext *pParse,                   /* fts3 query parse context */
108345  const char *zInput, int nInput,         /* Input string */
108346  Fts3Expr **ppExpr                       /* OUT: expression */
108347){
108348  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108349  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108350  int rc;
108351  Fts3Expr *p = 0;
108352  sqlite3_tokenizer_cursor *pCursor = 0;
108353  char *zTemp = 0;
108354  int nTemp = 0;
108355
108356  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
108357  if( rc==SQLITE_OK ){
108358    int ii;
108359    pCursor->pTokenizer = pTokenizer;
108360    for(ii=0; rc==SQLITE_OK; ii++){
108361      const char *zToken;
108362      int nToken, iBegin, iEnd, iPos;
108363      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
108364      if( rc==SQLITE_OK ){
108365        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108366        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
108367        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
108368        if( !p || !zTemp ){
108369          goto no_mem;
108370        }
108371        if( ii==0 ){
108372          memset(p, 0, nByte);
108373          p->pPhrase = (Fts3Phrase *)&p[1];
108374        }
108375        p->pPhrase = (Fts3Phrase *)&p[1];
108376        p->pPhrase->nToken = ii+1;
108377        p->pPhrase->aToken[ii].n = nToken;
108378        memcpy(&zTemp[nTemp], zToken, nToken);
108379        nTemp += nToken;
108380        if( iEnd<nInput && zInput[iEnd]=='*' ){
108381          p->pPhrase->aToken[ii].isPrefix = 1;
108382        }else{
108383          p->pPhrase->aToken[ii].isPrefix = 0;
108384        }
108385      }
108386    }
108387
108388    pModule->xClose(pCursor);
108389    pCursor = 0;
108390  }
108391
108392  if( rc==SQLITE_DONE ){
108393    int jj;
108394    char *zNew = NULL;
108395    int nNew = 0;
108396    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108397    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
108398    p = fts3ReallocOrFree(p, nByte + nTemp);
108399    if( !p ){
108400      goto no_mem;
108401    }
108402    if( zTemp ){
108403      zNew = &(((char *)p)[nByte]);
108404      memcpy(zNew, zTemp, nTemp);
108405    }else{
108406      memset(p, 0, nByte+nTemp);
108407    }
108408    p->pPhrase = (Fts3Phrase *)&p[1];
108409    for(jj=0; jj<p->pPhrase->nToken; jj++){
108410      p->pPhrase->aToken[jj].z = &zNew[nNew];
108411      nNew += p->pPhrase->aToken[jj].n;
108412    }
108413    sqlite3_free(zTemp);
108414    p->eType = FTSQUERY_PHRASE;
108415    p->pPhrase->iColumn = pParse->iDefaultCol;
108416    rc = SQLITE_OK;
108417  }
108418
108419  *ppExpr = p;
108420  return rc;
108421no_mem:
108422
108423  if( pCursor ){
108424    pModule->xClose(pCursor);
108425  }
108426  sqlite3_free(zTemp);
108427  sqlite3_free(p);
108428  *ppExpr = 0;
108429  return SQLITE_NOMEM;
108430}
108431
108432/*
108433** Function getNextNode(), which is called by fts3ExprParse(), may itself
108434** call fts3ExprParse(). So this forward declaration is required.
108435*/
108436static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
108437
108438/*
108439** The output variable *ppExpr is populated with an allocated Fts3Expr
108440** structure, or set to 0 if the end of the input buffer is reached.
108441**
108442** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
108443** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
108444** If SQLITE_ERROR is returned, pContext is populated with an error message.
108445*/
108446static int getNextNode(
108447  ParseContext *pParse,                   /* fts3 query parse context */
108448  const char *z, int n,                   /* Input string */
108449  Fts3Expr **ppExpr,                      /* OUT: expression */
108450  int *pnConsumed                         /* OUT: Number of bytes consumed */
108451){
108452  static const struct Fts3Keyword {
108453    char *z;                              /* Keyword text */
108454    unsigned char n;                      /* Length of the keyword */
108455    unsigned char parenOnly;              /* Only valid in paren mode */
108456    unsigned char eType;                  /* Keyword code */
108457  } aKeyword[] = {
108458    { "OR" ,  2, 0, FTSQUERY_OR   },
108459    { "AND",  3, 1, FTSQUERY_AND  },
108460    { "NOT",  3, 1, FTSQUERY_NOT  },
108461    { "NEAR", 4, 0, FTSQUERY_NEAR }
108462  };
108463  int ii;
108464  int iCol;
108465  int iColLen;
108466  int rc;
108467  Fts3Expr *pRet = 0;
108468
108469  const char *zInput = z;
108470  int nInput = n;
108471
108472  /* Skip over any whitespace before checking for a keyword, an open or
108473  ** close bracket, or a quoted string.
108474  */
108475  while( nInput>0 && fts3isspace(*zInput) ){
108476    nInput--;
108477    zInput++;
108478  }
108479  if( nInput==0 ){
108480    return SQLITE_DONE;
108481  }
108482
108483  /* See if we are dealing with a keyword. */
108484  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
108485    const struct Fts3Keyword *pKey = &aKeyword[ii];
108486
108487    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
108488      continue;
108489    }
108490
108491    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
108492      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
108493      int nKey = pKey->n;
108494      char cNext;
108495
108496      /* If this is a "NEAR" keyword, check for an explicit nearness. */
108497      if( pKey->eType==FTSQUERY_NEAR ){
108498        assert( nKey==4 );
108499        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
108500          nNear = 0;
108501          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
108502            nNear = nNear * 10 + (zInput[nKey] - '0');
108503          }
108504        }
108505      }
108506
108507      /* At this point this is probably a keyword. But for that to be true,
108508      ** the next byte must contain either whitespace, an open or close
108509      ** parenthesis, a quote character, or EOF.
108510      */
108511      cNext = zInput[nKey];
108512      if( fts3isspace(cNext)
108513       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
108514      ){
108515        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
108516        if( !pRet ){
108517          return SQLITE_NOMEM;
108518        }
108519        memset(pRet, 0, sizeof(Fts3Expr));
108520        pRet->eType = pKey->eType;
108521        pRet->nNear = nNear;
108522        *ppExpr = pRet;
108523        *pnConsumed = (int)((zInput - z) + nKey);
108524        return SQLITE_OK;
108525      }
108526
108527      /* Turns out that wasn't a keyword after all. This happens if the
108528      ** user has supplied a token such as "ORacle". Continue.
108529      */
108530    }
108531  }
108532
108533  /* Check for an open bracket. */
108534  if( sqlite3_fts3_enable_parentheses ){
108535    if( *zInput=='(' ){
108536      int nConsumed;
108537      int rc;
108538      pParse->nNest++;
108539      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
108540      if( rc==SQLITE_OK && !*ppExpr ){
108541        rc = SQLITE_DONE;
108542      }
108543      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
108544      return rc;
108545    }
108546
108547    /* Check for a close bracket. */
108548    if( *zInput==')' ){
108549      pParse->nNest--;
108550      *pnConsumed = (int)((zInput - z) + 1);
108551      return SQLITE_DONE;
108552    }
108553  }
108554
108555  /* See if we are dealing with a quoted phrase. If this is the case, then
108556  ** search for the closing quote and pass the whole string to getNextString()
108557  ** for processing. This is easy to do, as fts3 has no syntax for escaping
108558  ** a quote character embedded in a string.
108559  */
108560  if( *zInput=='"' ){
108561    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
108562    *pnConsumed = (int)((zInput - z) + ii + 1);
108563    if( ii==nInput ){
108564      return SQLITE_ERROR;
108565    }
108566    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
108567  }
108568
108569
108570  /* If control flows to this point, this must be a regular token, or
108571  ** the end of the input. Read a regular token using the sqlite3_tokenizer
108572  ** interface. Before doing so, figure out if there is an explicit
108573  ** column specifier for the token.
108574  **
108575  ** TODO: Strangely, it is not possible to associate a column specifier
108576  ** with a quoted phrase, only with a single token. Not sure if this was
108577  ** an implementation artifact or an intentional decision when fts3 was
108578  ** first implemented. Whichever it was, this module duplicates the
108579  ** limitation.
108580  */
108581  iCol = pParse->iDefaultCol;
108582  iColLen = 0;
108583  for(ii=0; ii<pParse->nCol; ii++){
108584    const char *zStr = pParse->azCol[ii];
108585    int nStr = (int)strlen(zStr);
108586    if( nInput>nStr && zInput[nStr]==':'
108587     && sqlite3_strnicmp(zStr, zInput, nStr)==0
108588    ){
108589      iCol = ii;
108590      iColLen = (int)((zInput - z) + nStr + 1);
108591      break;
108592    }
108593  }
108594  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
108595  *pnConsumed += iColLen;
108596  return rc;
108597}
108598
108599/*
108600** The argument is an Fts3Expr structure for a binary operator (any type
108601** except an FTSQUERY_PHRASE). Return an integer value representing the
108602** precedence of the operator. Lower values have a higher precedence (i.e.
108603** group more tightly). For example, in the C language, the == operator
108604** groups more tightly than ||, and would therefore have a higher precedence.
108605**
108606** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
108607** is defined), the order of the operators in precedence from highest to
108608** lowest is:
108609**
108610**   NEAR
108611**   NOT
108612**   AND (including implicit ANDs)
108613**   OR
108614**
108615** Note that when using the old query syntax, the OR operator has a higher
108616** precedence than the AND operator.
108617*/
108618static int opPrecedence(Fts3Expr *p){
108619  assert( p->eType!=FTSQUERY_PHRASE );
108620  if( sqlite3_fts3_enable_parentheses ){
108621    return p->eType;
108622  }else if( p->eType==FTSQUERY_NEAR ){
108623    return 1;
108624  }else if( p->eType==FTSQUERY_OR ){
108625    return 2;
108626  }
108627  assert( p->eType==FTSQUERY_AND );
108628  return 3;
108629}
108630
108631/*
108632** Argument ppHead contains a pointer to the current head of a query
108633** expression tree being parsed. pPrev is the expression node most recently
108634** inserted into the tree. This function adds pNew, which is always a binary
108635** operator node, into the expression tree based on the relative precedence
108636** of pNew and the existing nodes of the tree. This may result in the head
108637** of the tree changing, in which case *ppHead is set to the new root node.
108638*/
108639static void insertBinaryOperator(
108640  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
108641  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
108642  Fts3Expr *pNew           /* New binary node to insert into expression tree */
108643){
108644  Fts3Expr *pSplit = pPrev;
108645  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
108646    pSplit = pSplit->pParent;
108647  }
108648
108649  if( pSplit->pParent ){
108650    assert( pSplit->pParent->pRight==pSplit );
108651    pSplit->pParent->pRight = pNew;
108652    pNew->pParent = pSplit->pParent;
108653  }else{
108654    *ppHead = pNew;
108655  }
108656  pNew->pLeft = pSplit;
108657  pSplit->pParent = pNew;
108658}
108659
108660/*
108661** Parse the fts3 query expression found in buffer z, length n. This function
108662** returns either when the end of the buffer is reached or an unmatched
108663** closing bracket - ')' - is encountered.
108664**
108665** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
108666** parsed form of the expression and *pnConsumed is set to the number of
108667** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
108668** (out of memory error) or SQLITE_ERROR (parse error) is returned.
108669*/
108670static int fts3ExprParse(
108671  ParseContext *pParse,                   /* fts3 query parse context */
108672  const char *z, int n,                   /* Text of MATCH query */
108673  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
108674  int *pnConsumed                         /* OUT: Number of bytes consumed */
108675){
108676  Fts3Expr *pRet = 0;
108677  Fts3Expr *pPrev = 0;
108678  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
108679  int nIn = n;
108680  const char *zIn = z;
108681  int rc = SQLITE_OK;
108682  int isRequirePhrase = 1;
108683
108684  while( rc==SQLITE_OK ){
108685    Fts3Expr *p = 0;
108686    int nByte = 0;
108687    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
108688    if( rc==SQLITE_OK ){
108689      int isPhrase;
108690
108691      if( !sqlite3_fts3_enable_parentheses
108692       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
108693      ){
108694        /* Create an implicit NOT operator. */
108695        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
108696        if( !pNot ){
108697          sqlite3Fts3ExprFree(p);
108698          rc = SQLITE_NOMEM;
108699          goto exprparse_out;
108700        }
108701        memset(pNot, 0, sizeof(Fts3Expr));
108702        pNot->eType = FTSQUERY_NOT;
108703        pNot->pRight = p;
108704        if( pNotBranch ){
108705          pNot->pLeft = pNotBranch;
108706        }
108707        pNotBranch = pNot;
108708        p = pPrev;
108709      }else{
108710        int eType = p->eType;
108711        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
108712        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
108713
108714        /* The isRequirePhrase variable is set to true if a phrase or
108715        ** an expression contained in parenthesis is required. If a
108716        ** binary operator (AND, OR, NOT or NEAR) is encounted when
108717        ** isRequirePhrase is set, this is a syntax error.
108718        */
108719        if( !isPhrase && isRequirePhrase ){
108720          sqlite3Fts3ExprFree(p);
108721          rc = SQLITE_ERROR;
108722          goto exprparse_out;
108723        }
108724
108725        if( isPhrase && !isRequirePhrase ){
108726          /* Insert an implicit AND operator. */
108727          Fts3Expr *pAnd;
108728          assert( pRet && pPrev );
108729          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
108730          if( !pAnd ){
108731            sqlite3Fts3ExprFree(p);
108732            rc = SQLITE_NOMEM;
108733            goto exprparse_out;
108734          }
108735          memset(pAnd, 0, sizeof(Fts3Expr));
108736          pAnd->eType = FTSQUERY_AND;
108737          insertBinaryOperator(&pRet, pPrev, pAnd);
108738          pPrev = pAnd;
108739        }
108740
108741        /* This test catches attempts to make either operand of a NEAR
108742        ** operator something other than a phrase. For example, either of
108743        ** the following:
108744        **
108745        **    (bracketed expression) NEAR phrase
108746        **    phrase NEAR (bracketed expression)
108747        **
108748        ** Return an error in either case.
108749        */
108750        if( pPrev && (
108751            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
108752         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
108753        )){
108754          sqlite3Fts3ExprFree(p);
108755          rc = SQLITE_ERROR;
108756          goto exprparse_out;
108757        }
108758
108759        if( isPhrase ){
108760          if( pRet ){
108761            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
108762            pPrev->pRight = p;
108763            p->pParent = pPrev;
108764          }else{
108765            pRet = p;
108766          }
108767        }else{
108768          insertBinaryOperator(&pRet, pPrev, p);
108769        }
108770        isRequirePhrase = !isPhrase;
108771      }
108772      assert( nByte>0 );
108773    }
108774    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
108775    nIn -= nByte;
108776    zIn += nByte;
108777    pPrev = p;
108778  }
108779
108780  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
108781    rc = SQLITE_ERROR;
108782  }
108783
108784  if( rc==SQLITE_DONE ){
108785    rc = SQLITE_OK;
108786    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
108787      if( !pRet ){
108788        rc = SQLITE_ERROR;
108789      }else{
108790        Fts3Expr *pIter = pNotBranch;
108791        while( pIter->pLeft ){
108792          pIter = pIter->pLeft;
108793        }
108794        pIter->pLeft = pRet;
108795        pRet = pNotBranch;
108796      }
108797    }
108798  }
108799  *pnConsumed = n - nIn;
108800
108801exprparse_out:
108802  if( rc!=SQLITE_OK ){
108803    sqlite3Fts3ExprFree(pRet);
108804    sqlite3Fts3ExprFree(pNotBranch);
108805    pRet = 0;
108806  }
108807  *ppExpr = pRet;
108808  return rc;
108809}
108810
108811/*
108812** Parameters z and n contain a pointer to and length of a buffer containing
108813** an fts3 query expression, respectively. This function attempts to parse the
108814** query expression and create a tree of Fts3Expr structures representing the
108815** parsed expression. If successful, *ppExpr is set to point to the head
108816** of the parsed expression tree and SQLITE_OK is returned. If an error
108817** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
108818** error) is returned and *ppExpr is set to 0.
108819**
108820** If parameter n is a negative number, then z is assumed to point to a
108821** nul-terminated string and the length is determined using strlen().
108822**
108823** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
108824** use to normalize query tokens while parsing the expression. The azCol[]
108825** array, which is assumed to contain nCol entries, should contain the names
108826** of each column in the target fts3 table, in order from left to right.
108827** Column names must be nul-terminated strings.
108828**
108829** The iDefaultCol parameter should be passed the index of the table column
108830** that appears on the left-hand-side of the MATCH operator (the default
108831** column to match against for tokens for which a column name is not explicitly
108832** specified as part of the query string), or -1 if tokens may by default
108833** match any table column.
108834*/
108835SQLITE_PRIVATE int sqlite3Fts3ExprParse(
108836  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
108837  char **azCol,                       /* Array of column names for fts3 table */
108838  int nCol,                           /* Number of entries in azCol[] */
108839  int iDefaultCol,                    /* Default column to query */
108840  const char *z, int n,               /* Text of MATCH query */
108841  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
108842){
108843  int nParsed;
108844  int rc;
108845  ParseContext sParse;
108846  sParse.pTokenizer = pTokenizer;
108847  sParse.azCol = (const char **)azCol;
108848  sParse.nCol = nCol;
108849  sParse.iDefaultCol = iDefaultCol;
108850  sParse.nNest = 0;
108851  if( z==0 ){
108852    *ppExpr = 0;
108853    return SQLITE_OK;
108854  }
108855  if( n<0 ){
108856    n = (int)strlen(z);
108857  }
108858  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
108859
108860  /* Check for mismatched parenthesis */
108861  if( rc==SQLITE_OK && sParse.nNest ){
108862    rc = SQLITE_ERROR;
108863    sqlite3Fts3ExprFree(*ppExpr);
108864    *ppExpr = 0;
108865  }
108866
108867  return rc;
108868}
108869
108870/*
108871** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
108872*/
108873SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
108874  if( p ){
108875    sqlite3Fts3ExprFree(p->pLeft);
108876    sqlite3Fts3ExprFree(p->pRight);
108877    sqlite3_free(p->aDoclist);
108878    sqlite3_free(p);
108879  }
108880}
108881
108882/****************************************************************************
108883*****************************************************************************
108884** Everything after this point is just test code.
108885*/
108886
108887#ifdef SQLITE_TEST
108888
108889
108890/*
108891** Function to query the hash-table of tokenizers (see README.tokenizers).
108892*/
108893static int queryTestTokenizer(
108894  sqlite3 *db,
108895  const char *zName,
108896  const sqlite3_tokenizer_module **pp
108897){
108898  int rc;
108899  sqlite3_stmt *pStmt;
108900  const char zSql[] = "SELECT fts3_tokenizer(?)";
108901
108902  *pp = 0;
108903  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
108904  if( rc!=SQLITE_OK ){
108905    return rc;
108906  }
108907
108908  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
108909  if( SQLITE_ROW==sqlite3_step(pStmt) ){
108910    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
108911      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
108912    }
108913  }
108914
108915  return sqlite3_finalize(pStmt);
108916}
108917
108918/*
108919** This function is part of the test interface for the query parser. It
108920** writes a text representation of the query expression pExpr into the
108921** buffer pointed to by argument zBuf. It is assumed that zBuf is large
108922** enough to store the required text representation.
108923*/
108924static void exprToString(Fts3Expr *pExpr, char *zBuf){
108925  switch( pExpr->eType ){
108926    case FTSQUERY_PHRASE: {
108927      Fts3Phrase *pPhrase = pExpr->pPhrase;
108928      int i;
108929      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
108930      for(i=0; i<pPhrase->nToken; i++){
108931        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
108932        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
108933      }
108934      return;
108935    }
108936
108937    case FTSQUERY_NEAR:
108938      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
108939      break;
108940    case FTSQUERY_NOT:
108941      zBuf += sprintf(zBuf, "NOT ");
108942      break;
108943    case FTSQUERY_AND:
108944      zBuf += sprintf(zBuf, "AND ");
108945      break;
108946    case FTSQUERY_OR:
108947      zBuf += sprintf(zBuf, "OR ");
108948      break;
108949  }
108950
108951  zBuf += sprintf(zBuf, "{");
108952  exprToString(pExpr->pLeft, zBuf);
108953  zBuf += strlen(zBuf);
108954  zBuf += sprintf(zBuf, "} ");
108955
108956  zBuf += sprintf(zBuf, "{");
108957  exprToString(pExpr->pRight, zBuf);
108958  zBuf += strlen(zBuf);
108959  zBuf += sprintf(zBuf, "}");
108960}
108961
108962/*
108963** This is the implementation of a scalar SQL function used to test the
108964** expression parser. It should be called as follows:
108965**
108966**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
108967**
108968** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
108969** to parse the query expression (see README.tokenizers). The second argument
108970** is the query expression to parse. Each subsequent argument is the name
108971** of a column of the fts3 table that the query expression may refer to.
108972** For example:
108973**
108974**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
108975*/
108976static void fts3ExprTest(
108977  sqlite3_context *context,
108978  int argc,
108979  sqlite3_value **argv
108980){
108981  sqlite3_tokenizer_module const *pModule = 0;
108982  sqlite3_tokenizer *pTokenizer = 0;
108983  int rc;
108984  char **azCol = 0;
108985  const char *zExpr;
108986  int nExpr;
108987  int nCol;
108988  int ii;
108989  Fts3Expr *pExpr;
108990  sqlite3 *db = sqlite3_context_db_handle(context);
108991
108992  if( argc<3 ){
108993    sqlite3_result_error(context,
108994        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
108995    );
108996    return;
108997  }
108998
108999  rc = queryTestTokenizer(db,
109000                          (const char *)sqlite3_value_text(argv[0]), &pModule);
109001  if( rc==SQLITE_NOMEM ){
109002    sqlite3_result_error_nomem(context);
109003    goto exprtest_out;
109004  }else if( !pModule ){
109005    sqlite3_result_error(context, "No such tokenizer module", -1);
109006    goto exprtest_out;
109007  }
109008
109009  rc = pModule->xCreate(0, 0, &pTokenizer);
109010  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
109011  if( rc==SQLITE_NOMEM ){
109012    sqlite3_result_error_nomem(context);
109013    goto exprtest_out;
109014  }
109015  pTokenizer->pModule = pModule;
109016
109017  zExpr = (const char *)sqlite3_value_text(argv[1]);
109018  nExpr = sqlite3_value_bytes(argv[1]);
109019  nCol = argc-2;
109020  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
109021  if( !azCol ){
109022    sqlite3_result_error_nomem(context);
109023    goto exprtest_out;
109024  }
109025  for(ii=0; ii<nCol; ii++){
109026    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
109027  }
109028
109029  rc = sqlite3Fts3ExprParse(
109030      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
109031  );
109032  if( rc==SQLITE_NOMEM ){
109033    sqlite3_result_error_nomem(context);
109034    goto exprtest_out;
109035  }else if( rc==SQLITE_OK ){
109036    char zBuf[4096];
109037    exprToString(pExpr, zBuf);
109038    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
109039    sqlite3Fts3ExprFree(pExpr);
109040  }else{
109041    sqlite3_result_error(context, "Error parsing expression", -1);
109042  }
109043
109044exprtest_out:
109045  if( pModule && pTokenizer ){
109046    rc = pModule->xDestroy(pTokenizer);
109047  }
109048  sqlite3_free(azCol);
109049}
109050
109051/*
109052** Register the query expression parser test function fts3_exprtest()
109053** with database connection db.
109054*/
109055SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
109056  return sqlite3_create_function(
109057      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
109058  );
109059}
109060
109061#endif
109062#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109063
109064/************** End of fts3_expr.c *******************************************/
109065/************** Begin file fts3_hash.c ***************************************/
109066/*
109067** 2001 September 22
109068**
109069** The author disclaims copyright to this source code.  In place of
109070** a legal notice, here is a blessing:
109071**
109072**    May you do good and not evil.
109073**    May you find forgiveness for yourself and forgive others.
109074**    May you share freely, never taking more than you give.
109075**
109076*************************************************************************
109077** This is the implementation of generic hash-tables used in SQLite.
109078** We've modified it slightly to serve as a standalone hash table
109079** implementation for the full-text indexing module.
109080*/
109081
109082/*
109083** The code in this file is only compiled if:
109084**
109085**     * The FTS3 module is being built as an extension
109086**       (in which case SQLITE_CORE is not defined), or
109087**
109088**     * The FTS3 module is being built into the core of
109089**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109090*/
109091#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109092
109093
109094
109095/*
109096** Malloc and Free functions
109097*/
109098static void *fts3HashMalloc(int n){
109099  void *p = sqlite3_malloc(n);
109100  if( p ){
109101    memset(p, 0, n);
109102  }
109103  return p;
109104}
109105static void fts3HashFree(void *p){
109106  sqlite3_free(p);
109107}
109108
109109/* Turn bulk memory into a hash table object by initializing the
109110** fields of the Hash structure.
109111**
109112** "pNew" is a pointer to the hash table that is to be initialized.
109113** keyClass is one of the constants
109114** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
109115** determines what kind of key the hash table will use.  "copyKey" is
109116** true if the hash table should make its own private copy of keys and
109117** false if it should just use the supplied pointer.
109118*/
109119SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
109120  assert( pNew!=0 );
109121  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
109122  pNew->keyClass = keyClass;
109123  pNew->copyKey = copyKey;
109124  pNew->first = 0;
109125  pNew->count = 0;
109126  pNew->htsize = 0;
109127  pNew->ht = 0;
109128}
109129
109130/* Remove all entries from a hash table.  Reclaim all memory.
109131** Call this routine to delete a hash table or to reset a hash table
109132** to the empty state.
109133*/
109134SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
109135  Fts3HashElem *elem;         /* For looping over all elements of the table */
109136
109137  assert( pH!=0 );
109138  elem = pH->first;
109139  pH->first = 0;
109140  fts3HashFree(pH->ht);
109141  pH->ht = 0;
109142  pH->htsize = 0;
109143  while( elem ){
109144    Fts3HashElem *next_elem = elem->next;
109145    if( pH->copyKey && elem->pKey ){
109146      fts3HashFree(elem->pKey);
109147    }
109148    fts3HashFree(elem);
109149    elem = next_elem;
109150  }
109151  pH->count = 0;
109152}
109153
109154/*
109155** Hash and comparison functions when the mode is FTS3_HASH_STRING
109156*/
109157static int fts3StrHash(const void *pKey, int nKey){
109158  const char *z = (const char *)pKey;
109159  int h = 0;
109160  if( nKey<=0 ) nKey = (int) strlen(z);
109161  while( nKey > 0  ){
109162    h = (h<<3) ^ h ^ *z++;
109163    nKey--;
109164  }
109165  return h & 0x7fffffff;
109166}
109167static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109168  if( n1!=n2 ) return 1;
109169  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
109170}
109171
109172/*
109173** Hash and comparison functions when the mode is FTS3_HASH_BINARY
109174*/
109175static int fts3BinHash(const void *pKey, int nKey){
109176  int h = 0;
109177  const char *z = (const char *)pKey;
109178  while( nKey-- > 0 ){
109179    h = (h<<3) ^ h ^ *(z++);
109180  }
109181  return h & 0x7fffffff;
109182}
109183static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109184  if( n1!=n2 ) return 1;
109185  return memcmp(pKey1,pKey2,n1);
109186}
109187
109188/*
109189** Return a pointer to the appropriate hash function given the key class.
109190**
109191** The C syntax in this function definition may be unfamilar to some
109192** programmers, so we provide the following additional explanation:
109193**
109194** The name of the function is "ftsHashFunction".  The function takes a
109195** single parameter "keyClass".  The return value of ftsHashFunction()
109196** is a pointer to another function.  Specifically, the return value
109197** of ftsHashFunction() is a pointer to a function that takes two parameters
109198** with types "const void*" and "int" and returns an "int".
109199*/
109200static int (*ftsHashFunction(int keyClass))(const void*,int){
109201  if( keyClass==FTS3_HASH_STRING ){
109202    return &fts3StrHash;
109203  }else{
109204    assert( keyClass==FTS3_HASH_BINARY );
109205    return &fts3BinHash;
109206  }
109207}
109208
109209/*
109210** Return a pointer to the appropriate hash function given the key class.
109211**
109212** For help in interpreted the obscure C code in the function definition,
109213** see the header comment on the previous function.
109214*/
109215static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
109216  if( keyClass==FTS3_HASH_STRING ){
109217    return &fts3StrCompare;
109218  }else{
109219    assert( keyClass==FTS3_HASH_BINARY );
109220    return &fts3BinCompare;
109221  }
109222}
109223
109224/* Link an element into the hash table
109225*/
109226static void fts3HashInsertElement(
109227  Fts3Hash *pH,            /* The complete hash table */
109228  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
109229  Fts3HashElem *pNew       /* The element to be inserted */
109230){
109231  Fts3HashElem *pHead;     /* First element already in pEntry */
109232  pHead = pEntry->chain;
109233  if( pHead ){
109234    pNew->next = pHead;
109235    pNew->prev = pHead->prev;
109236    if( pHead->prev ){ pHead->prev->next = pNew; }
109237    else             { pH->first = pNew; }
109238    pHead->prev = pNew;
109239  }else{
109240    pNew->next = pH->first;
109241    if( pH->first ){ pH->first->prev = pNew; }
109242    pNew->prev = 0;
109243    pH->first = pNew;
109244  }
109245  pEntry->count++;
109246  pEntry->chain = pNew;
109247}
109248
109249
109250/* Resize the hash table so that it cantains "new_size" buckets.
109251** "new_size" must be a power of 2.  The hash table might fail
109252** to resize if sqliteMalloc() fails.
109253**
109254** Return non-zero if a memory allocation error occurs.
109255*/
109256static int fts3Rehash(Fts3Hash *pH, int new_size){
109257  struct _fts3ht *new_ht;          /* The new hash table */
109258  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
109259  int (*xHash)(const void*,int);   /* The hash function */
109260
109261  assert( (new_size & (new_size-1))==0 );
109262  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
109263  if( new_ht==0 ) return 1;
109264  fts3HashFree(pH->ht);
109265  pH->ht = new_ht;
109266  pH->htsize = new_size;
109267  xHash = ftsHashFunction(pH->keyClass);
109268  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
109269    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
109270    next_elem = elem->next;
109271    fts3HashInsertElement(pH, &new_ht[h], elem);
109272  }
109273  return 0;
109274}
109275
109276/* This function (for internal use only) locates an element in an
109277** hash table that matches the given key.  The hash for this key has
109278** already been computed and is passed as the 4th parameter.
109279*/
109280static Fts3HashElem *fts3FindElementByHash(
109281  const Fts3Hash *pH, /* The pH to be searched */
109282  const void *pKey,   /* The key we are searching for */
109283  int nKey,
109284  int h               /* The hash for this key. */
109285){
109286  Fts3HashElem *elem;            /* Used to loop thru the element list */
109287  int count;                     /* Number of elements left to test */
109288  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
109289
109290  if( pH->ht ){
109291    struct _fts3ht *pEntry = &pH->ht[h];
109292    elem = pEntry->chain;
109293    count = pEntry->count;
109294    xCompare = ftsCompareFunction(pH->keyClass);
109295    while( count-- && elem ){
109296      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
109297        return elem;
109298      }
109299      elem = elem->next;
109300    }
109301  }
109302  return 0;
109303}
109304
109305/* Remove a single entry from the hash table given a pointer to that
109306** element and a hash on the element's key.
109307*/
109308static void fts3RemoveElementByHash(
109309  Fts3Hash *pH,         /* The pH containing "elem" */
109310  Fts3HashElem* elem,   /* The element to be removed from the pH */
109311  int h                 /* Hash value for the element */
109312){
109313  struct _fts3ht *pEntry;
109314  if( elem->prev ){
109315    elem->prev->next = elem->next;
109316  }else{
109317    pH->first = elem->next;
109318  }
109319  if( elem->next ){
109320    elem->next->prev = elem->prev;
109321  }
109322  pEntry = &pH->ht[h];
109323  if( pEntry->chain==elem ){
109324    pEntry->chain = elem->next;
109325  }
109326  pEntry->count--;
109327  if( pEntry->count<=0 ){
109328    pEntry->chain = 0;
109329  }
109330  if( pH->copyKey && elem->pKey ){
109331    fts3HashFree(elem->pKey);
109332  }
109333  fts3HashFree( elem );
109334  pH->count--;
109335  if( pH->count<=0 ){
109336    assert( pH->first==0 );
109337    assert( pH->count==0 );
109338    fts3HashClear(pH);
109339  }
109340}
109341
109342SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
109343  const Fts3Hash *pH,
109344  const void *pKey,
109345  int nKey
109346){
109347  int h;                          /* A hash on key */
109348  int (*xHash)(const void*,int);  /* The hash function */
109349
109350  if( pH==0 || pH->ht==0 ) return 0;
109351  xHash = ftsHashFunction(pH->keyClass);
109352  assert( xHash!=0 );
109353  h = (*xHash)(pKey,nKey);
109354  assert( (pH->htsize & (pH->htsize-1))==0 );
109355  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
109356}
109357
109358/*
109359** Attempt to locate an element of the hash table pH with a key
109360** that matches pKey,nKey.  Return the data for this element if it is
109361** found, or NULL if there is no match.
109362*/
109363SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
109364  Fts3HashElem *pElem;            /* The element that matches key (if any) */
109365
109366  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
109367  return pElem ? pElem->data : 0;
109368}
109369
109370/* Insert an element into the hash table pH.  The key is pKey,nKey
109371** and the data is "data".
109372**
109373** If no element exists with a matching key, then a new
109374** element is created.  A copy of the key is made if the copyKey
109375** flag is set.  NULL is returned.
109376**
109377** If another element already exists with the same key, then the
109378** new data replaces the old data and the old data is returned.
109379** The key is not copied in this instance.  If a malloc fails, then
109380** the new data is returned and the hash table is unchanged.
109381**
109382** If the "data" parameter to this function is NULL, then the
109383** element corresponding to "key" is removed from the hash table.
109384*/
109385SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
109386  Fts3Hash *pH,        /* The hash table to insert into */
109387  const void *pKey,    /* The key */
109388  int nKey,            /* Number of bytes in the key */
109389  void *data           /* The data */
109390){
109391  int hraw;                 /* Raw hash value of the key */
109392  int h;                    /* the hash of the key modulo hash table size */
109393  Fts3HashElem *elem;       /* Used to loop thru the element list */
109394  Fts3HashElem *new_elem;   /* New element added to the pH */
109395  int (*xHash)(const void*,int);  /* The hash function */
109396
109397  assert( pH!=0 );
109398  xHash = ftsHashFunction(pH->keyClass);
109399  assert( xHash!=0 );
109400  hraw = (*xHash)(pKey, nKey);
109401  assert( (pH->htsize & (pH->htsize-1))==0 );
109402  h = hraw & (pH->htsize-1);
109403  elem = fts3FindElementByHash(pH,pKey,nKey,h);
109404  if( elem ){
109405    void *old_data = elem->data;
109406    if( data==0 ){
109407      fts3RemoveElementByHash(pH,elem,h);
109408    }else{
109409      elem->data = data;
109410    }
109411    return old_data;
109412  }
109413  if( data==0 ) return 0;
109414  if( (pH->htsize==0 && fts3Rehash(pH,8))
109415   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
109416  ){
109417    pH->count = 0;
109418    return data;
109419  }
109420  assert( pH->htsize>0 );
109421  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
109422  if( new_elem==0 ) return data;
109423  if( pH->copyKey && pKey!=0 ){
109424    new_elem->pKey = fts3HashMalloc( nKey );
109425    if( new_elem->pKey==0 ){
109426      fts3HashFree(new_elem);
109427      return data;
109428    }
109429    memcpy((void*)new_elem->pKey, pKey, nKey);
109430  }else{
109431    new_elem->pKey = (void*)pKey;
109432  }
109433  new_elem->nKey = nKey;
109434  pH->count++;
109435  assert( pH->htsize>0 );
109436  assert( (pH->htsize & (pH->htsize-1))==0 );
109437  h = hraw & (pH->htsize-1);
109438  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
109439  new_elem->data = data;
109440  return 0;
109441}
109442
109443#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109444
109445/************** End of fts3_hash.c *******************************************/
109446/************** Begin file fts3_porter.c *************************************/
109447/*
109448** 2006 September 30
109449**
109450** The author disclaims copyright to this source code.  In place of
109451** a legal notice, here is a blessing:
109452**
109453**    May you do good and not evil.
109454**    May you find forgiveness for yourself and forgive others.
109455**    May you share freely, never taking more than you give.
109456**
109457*************************************************************************
109458** Implementation of the full-text-search tokenizer that implements
109459** a Porter stemmer.
109460*/
109461
109462/*
109463** The code in this file is only compiled if:
109464**
109465**     * The FTS3 module is being built as an extension
109466**       (in which case SQLITE_CORE is not defined), or
109467**
109468**     * The FTS3 module is being built into the core of
109469**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109470*/
109471#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109472
109473
109474
109475
109476/*
109477** Class derived from sqlite3_tokenizer
109478*/
109479typedef struct porter_tokenizer {
109480  sqlite3_tokenizer base;      /* Base class */
109481} porter_tokenizer;
109482
109483/*
109484** Class derived from sqlit3_tokenizer_cursor
109485*/
109486typedef struct porter_tokenizer_cursor {
109487  sqlite3_tokenizer_cursor base;
109488  const char *zInput;          /* input we are tokenizing */
109489  int nInput;                  /* size of the input */
109490  int iOffset;                 /* current position in zInput */
109491  int iToken;                  /* index of next token to be returned */
109492  char *zToken;                /* storage for current token */
109493  int nAllocated;              /* space allocated to zToken buffer */
109494} porter_tokenizer_cursor;
109495
109496
109497/*
109498** Create a new tokenizer instance.
109499*/
109500static int porterCreate(
109501  int argc, const char * const *argv,
109502  sqlite3_tokenizer **ppTokenizer
109503){
109504  porter_tokenizer *t;
109505
109506  UNUSED_PARAMETER(argc);
109507  UNUSED_PARAMETER(argv);
109508
109509  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
109510  if( t==NULL ) return SQLITE_NOMEM;
109511  memset(t, 0, sizeof(*t));
109512  *ppTokenizer = &t->base;
109513  return SQLITE_OK;
109514}
109515
109516/*
109517** Destroy a tokenizer
109518*/
109519static int porterDestroy(sqlite3_tokenizer *pTokenizer){
109520  sqlite3_free(pTokenizer);
109521  return SQLITE_OK;
109522}
109523
109524/*
109525** Prepare to begin tokenizing a particular string.  The input
109526** string to be tokenized is zInput[0..nInput-1].  A cursor
109527** used to incrementally tokenize this string is returned in
109528** *ppCursor.
109529*/
109530static int porterOpen(
109531  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
109532  const char *zInput, int nInput,        /* String to be tokenized */
109533  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
109534){
109535  porter_tokenizer_cursor *c;
109536
109537  UNUSED_PARAMETER(pTokenizer);
109538
109539  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
109540  if( c==NULL ) return SQLITE_NOMEM;
109541
109542  c->zInput = zInput;
109543  if( zInput==0 ){
109544    c->nInput = 0;
109545  }else if( nInput<0 ){
109546    c->nInput = (int)strlen(zInput);
109547  }else{
109548    c->nInput = nInput;
109549  }
109550  c->iOffset = 0;                 /* start tokenizing at the beginning */
109551  c->iToken = 0;
109552  c->zToken = NULL;               /* no space allocated, yet. */
109553  c->nAllocated = 0;
109554
109555  *ppCursor = &c->base;
109556  return SQLITE_OK;
109557}
109558
109559/*
109560** Close a tokenization cursor previously opened by a call to
109561** porterOpen() above.
109562*/
109563static int porterClose(sqlite3_tokenizer_cursor *pCursor){
109564  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
109565  sqlite3_free(c->zToken);
109566  sqlite3_free(c);
109567  return SQLITE_OK;
109568}
109569/*
109570** Vowel or consonant
109571*/
109572static const char cType[] = {
109573   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
109574   1, 1, 1, 2, 1
109575};
109576
109577/*
109578** isConsonant() and isVowel() determine if their first character in
109579** the string they point to is a consonant or a vowel, according
109580** to Porter ruls.
109581**
109582** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
109583** 'Y' is a consonant unless it follows another consonant,
109584** in which case it is a vowel.
109585**
109586** In these routine, the letters are in reverse order.  So the 'y' rule
109587** is that 'y' is a consonant unless it is followed by another
109588** consonent.
109589*/
109590static int isVowel(const char*);
109591static int isConsonant(const char *z){
109592  int j;
109593  char x = *z;
109594  if( x==0 ) return 0;
109595  assert( x>='a' && x<='z' );
109596  j = cType[x-'a'];
109597  if( j<2 ) return j;
109598  return z[1]==0 || isVowel(z + 1);
109599}
109600static int isVowel(const char *z){
109601  int j;
109602  char x = *z;
109603  if( x==0 ) return 0;
109604  assert( x>='a' && x<='z' );
109605  j = cType[x-'a'];
109606  if( j<2 ) return 1-j;
109607  return isConsonant(z + 1);
109608}
109609
109610/*
109611** Let any sequence of one or more vowels be represented by V and let
109612** C be sequence of one or more consonants.  Then every word can be
109613** represented as:
109614**
109615**           [C] (VC){m} [V]
109616**
109617** In prose:  A word is an optional consonant followed by zero or
109618** vowel-consonant pairs followed by an optional vowel.  "m" is the
109619** number of vowel consonant pairs.  This routine computes the value
109620** of m for the first i bytes of a word.
109621**
109622** Return true if the m-value for z is 1 or more.  In other words,
109623** return true if z contains at least one vowel that is followed
109624** by a consonant.
109625**
109626** In this routine z[] is in reverse order.  So we are really looking
109627** for an instance of of a consonant followed by a vowel.
109628*/
109629static int m_gt_0(const char *z){
109630  while( isVowel(z) ){ z++; }
109631  if( *z==0 ) return 0;
109632  while( isConsonant(z) ){ z++; }
109633  return *z!=0;
109634}
109635
109636/* Like mgt0 above except we are looking for a value of m which is
109637** exactly 1
109638*/
109639static int m_eq_1(const char *z){
109640  while( isVowel(z) ){ z++; }
109641  if( *z==0 ) return 0;
109642  while( isConsonant(z) ){ z++; }
109643  if( *z==0 ) return 0;
109644  while( isVowel(z) ){ z++; }
109645  if( *z==0 ) return 1;
109646  while( isConsonant(z) ){ z++; }
109647  return *z==0;
109648}
109649
109650/* Like mgt0 above except we are looking for a value of m>1 instead
109651** or m>0
109652*/
109653static int m_gt_1(const char *z){
109654  while( isVowel(z) ){ z++; }
109655  if( *z==0 ) return 0;
109656  while( isConsonant(z) ){ z++; }
109657  if( *z==0 ) return 0;
109658  while( isVowel(z) ){ z++; }
109659  if( *z==0 ) return 0;
109660  while( isConsonant(z) ){ z++; }
109661  return *z!=0;
109662}
109663
109664/*
109665** Return TRUE if there is a vowel anywhere within z[0..n-1]
109666*/
109667static int hasVowel(const char *z){
109668  while( isConsonant(z) ){ z++; }
109669  return *z!=0;
109670}
109671
109672/*
109673** Return TRUE if the word ends in a double consonant.
109674**
109675** The text is reversed here. So we are really looking at
109676** the first two characters of z[].
109677*/
109678static int doubleConsonant(const char *z){
109679  return isConsonant(z) && z[0]==z[1];
109680}
109681
109682/*
109683** Return TRUE if the word ends with three letters which
109684** are consonant-vowel-consonent and where the final consonant
109685** is not 'w', 'x', or 'y'.
109686**
109687** The word is reversed here.  So we are really checking the
109688** first three letters and the first one cannot be in [wxy].
109689*/
109690static int star_oh(const char *z){
109691  return
109692    isConsonant(z) &&
109693    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
109694    isVowel(z+1) &&
109695    isConsonant(z+2);
109696}
109697
109698/*
109699** If the word ends with zFrom and xCond() is true for the stem
109700** of the word that preceeds the zFrom ending, then change the
109701** ending to zTo.
109702**
109703** The input word *pz and zFrom are both in reverse order.  zTo
109704** is in normal order.
109705**
109706** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
109707** match.  Not that TRUE is returned even if xCond() fails and
109708** no substitution occurs.
109709*/
109710static int stem(
109711  char **pz,             /* The word being stemmed (Reversed) */
109712  const char *zFrom,     /* If the ending matches this... (Reversed) */
109713  const char *zTo,       /* ... change the ending to this (not reversed) */
109714  int (*xCond)(const char*)   /* Condition that must be true */
109715){
109716  char *z = *pz;
109717  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
109718  if( *zFrom!=0 ) return 0;
109719  if( xCond && !xCond(z) ) return 1;
109720  while( *zTo ){
109721    *(--z) = *(zTo++);
109722  }
109723  *pz = z;
109724  return 1;
109725}
109726
109727/*
109728** This is the fallback stemmer used when the porter stemmer is
109729** inappropriate.  The input word is copied into the output with
109730** US-ASCII case folding.  If the input word is too long (more
109731** than 20 bytes if it contains no digits or more than 6 bytes if
109732** it contains digits) then word is truncated to 20 or 6 bytes
109733** by taking 10 or 3 bytes from the beginning and end.
109734*/
109735static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
109736  int i, mx, j;
109737  int hasDigit = 0;
109738  for(i=0; i<nIn; i++){
109739    char c = zIn[i];
109740    if( c>='A' && c<='Z' ){
109741      zOut[i] = c - 'A' + 'a';
109742    }else{
109743      if( c>='0' && c<='9' ) hasDigit = 1;
109744      zOut[i] = c;
109745    }
109746  }
109747  mx = hasDigit ? 3 : 10;
109748  if( nIn>mx*2 ){
109749    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
109750      zOut[j] = zOut[i];
109751    }
109752    i = j;
109753  }
109754  zOut[i] = 0;
109755  *pnOut = i;
109756}
109757
109758
109759/*
109760** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
109761** zOut is at least big enough to hold nIn bytes.  Write the actual
109762** size of the output word (exclusive of the '\0' terminator) into *pnOut.
109763**
109764** Any upper-case characters in the US-ASCII character set ([A-Z])
109765** are converted to lower case.  Upper-case UTF characters are
109766** unchanged.
109767**
109768** Words that are longer than about 20 bytes are stemmed by retaining
109769** a few bytes from the beginning and the end of the word.  If the
109770** word contains digits, 3 bytes are taken from the beginning and
109771** 3 bytes from the end.  For long words without digits, 10 bytes
109772** are taken from each end.  US-ASCII case folding still applies.
109773**
109774** If the input word contains not digits but does characters not
109775** in [a-zA-Z] then no stemming is attempted and this routine just
109776** copies the input into the input into the output with US-ASCII
109777** case folding.
109778**
109779** Stemming never increases the length of the word.  So there is
109780** no chance of overflowing the zOut buffer.
109781*/
109782static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
109783  int i, j;
109784  char zReverse[28];
109785  char *z, *z2;
109786  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
109787    /* The word is too big or too small for the porter stemmer.
109788    ** Fallback to the copy stemmer */
109789    copy_stemmer(zIn, nIn, zOut, pnOut);
109790    return;
109791  }
109792  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
109793    char c = zIn[i];
109794    if( c>='A' && c<='Z' ){
109795      zReverse[j] = c + 'a' - 'A';
109796    }else if( c>='a' && c<='z' ){
109797      zReverse[j] = c;
109798    }else{
109799      /* The use of a character not in [a-zA-Z] means that we fallback
109800      ** to the copy stemmer */
109801      copy_stemmer(zIn, nIn, zOut, pnOut);
109802      return;
109803    }
109804  }
109805  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
109806  z = &zReverse[j+1];
109807
109808
109809  /* Step 1a */
109810  if( z[0]=='s' ){
109811    if(
109812     !stem(&z, "sess", "ss", 0) &&
109813     !stem(&z, "sei", "i", 0)  &&
109814     !stem(&z, "ss", "ss", 0)
109815    ){
109816      z++;
109817    }
109818  }
109819
109820  /* Step 1b */
109821  z2 = z;
109822  if( stem(&z, "dee", "ee", m_gt_0) ){
109823    /* Do nothing.  The work was all in the test */
109824  }else if(
109825     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
109826      && z!=z2
109827  ){
109828     if( stem(&z, "ta", "ate", 0) ||
109829         stem(&z, "lb", "ble", 0) ||
109830         stem(&z, "zi", "ize", 0) ){
109831       /* Do nothing.  The work was all in the test */
109832     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
109833       z++;
109834     }else if( m_eq_1(z) && star_oh(z) ){
109835       *(--z) = 'e';
109836     }
109837  }
109838
109839  /* Step 1c */
109840  if( z[0]=='y' && hasVowel(z+1) ){
109841    z[0] = 'i';
109842  }
109843
109844  /* Step 2 */
109845  switch( z[1] ){
109846   case 'a':
109847     stem(&z, "lanoita", "ate", m_gt_0) ||
109848     stem(&z, "lanoit", "tion", m_gt_0);
109849     break;
109850   case 'c':
109851     stem(&z, "icne", "ence", m_gt_0) ||
109852     stem(&z, "icna", "ance", m_gt_0);
109853     break;
109854   case 'e':
109855     stem(&z, "rezi", "ize", m_gt_0);
109856     break;
109857   case 'g':
109858     stem(&z, "igol", "log", m_gt_0);
109859     break;
109860   case 'l':
109861     stem(&z, "ilb", "ble", m_gt_0) ||
109862     stem(&z, "illa", "al", m_gt_0) ||
109863     stem(&z, "iltne", "ent", m_gt_0) ||
109864     stem(&z, "ile", "e", m_gt_0) ||
109865     stem(&z, "ilsuo", "ous", m_gt_0);
109866     break;
109867   case 'o':
109868     stem(&z, "noitazi", "ize", m_gt_0) ||
109869     stem(&z, "noita", "ate", m_gt_0) ||
109870     stem(&z, "rota", "ate", m_gt_0);
109871     break;
109872   case 's':
109873     stem(&z, "msila", "al", m_gt_0) ||
109874     stem(&z, "ssenevi", "ive", m_gt_0) ||
109875     stem(&z, "ssenluf", "ful", m_gt_0) ||
109876     stem(&z, "ssensuo", "ous", m_gt_0);
109877     break;
109878   case 't':
109879     stem(&z, "itila", "al", m_gt_0) ||
109880     stem(&z, "itivi", "ive", m_gt_0) ||
109881     stem(&z, "itilib", "ble", m_gt_0);
109882     break;
109883  }
109884
109885  /* Step 3 */
109886  switch( z[0] ){
109887   case 'e':
109888     stem(&z, "etaci", "ic", m_gt_0) ||
109889     stem(&z, "evita", "", m_gt_0)   ||
109890     stem(&z, "ezila", "al", m_gt_0);
109891     break;
109892   case 'i':
109893     stem(&z, "itici", "ic", m_gt_0);
109894     break;
109895   case 'l':
109896     stem(&z, "laci", "ic", m_gt_0) ||
109897     stem(&z, "luf", "", m_gt_0);
109898     break;
109899   case 's':
109900     stem(&z, "ssen", "", m_gt_0);
109901     break;
109902  }
109903
109904  /* Step 4 */
109905  switch( z[1] ){
109906   case 'a':
109907     if( z[0]=='l' && m_gt_1(z+2) ){
109908       z += 2;
109909     }
109910     break;
109911   case 'c':
109912     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
109913       z += 4;
109914     }
109915     break;
109916   case 'e':
109917     if( z[0]=='r' && m_gt_1(z+2) ){
109918       z += 2;
109919     }
109920     break;
109921   case 'i':
109922     if( z[0]=='c' && m_gt_1(z+2) ){
109923       z += 2;
109924     }
109925     break;
109926   case 'l':
109927     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
109928       z += 4;
109929     }
109930     break;
109931   case 'n':
109932     if( z[0]=='t' ){
109933       if( z[2]=='a' ){
109934         if( m_gt_1(z+3) ){
109935           z += 3;
109936         }
109937       }else if( z[2]=='e' ){
109938         stem(&z, "tneme", "", m_gt_1) ||
109939         stem(&z, "tnem", "", m_gt_1) ||
109940         stem(&z, "tne", "", m_gt_1);
109941       }
109942     }
109943     break;
109944   case 'o':
109945     if( z[0]=='u' ){
109946       if( m_gt_1(z+2) ){
109947         z += 2;
109948       }
109949     }else if( z[3]=='s' || z[3]=='t' ){
109950       stem(&z, "noi", "", m_gt_1);
109951     }
109952     break;
109953   case 's':
109954     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
109955       z += 3;
109956     }
109957     break;
109958   case 't':
109959     stem(&z, "eta", "", m_gt_1) ||
109960     stem(&z, "iti", "", m_gt_1);
109961     break;
109962   case 'u':
109963     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
109964       z += 3;
109965     }
109966     break;
109967   case 'v':
109968   case 'z':
109969     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
109970       z += 3;
109971     }
109972     break;
109973  }
109974
109975  /* Step 5a */
109976  if( z[0]=='e' ){
109977    if( m_gt_1(z+1) ){
109978      z++;
109979    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
109980      z++;
109981    }
109982  }
109983
109984  /* Step 5b */
109985  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
109986    z++;
109987  }
109988
109989  /* z[] is now the stemmed word in reverse order.  Flip it back
109990  ** around into forward order and return.
109991  */
109992  *pnOut = i = (int)strlen(z);
109993  zOut[i] = 0;
109994  while( *z ){
109995    zOut[--i] = *(z++);
109996  }
109997}
109998
109999/*
110000** Characters that can be part of a token.  We assume any character
110001** whose value is greater than 0x80 (any UTF character) can be
110002** part of a token.  In other words, delimiters all must have
110003** values of 0x7f or lower.
110004*/
110005static const char porterIdChar[] = {
110006/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
110007    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110008    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110009    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110010    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110011    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110012};
110013#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
110014
110015/*
110016** Extract the next token from a tokenization cursor.  The cursor must
110017** have been opened by a prior call to porterOpen().
110018*/
110019static int porterNext(
110020  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
110021  const char **pzToken,               /* OUT: *pzToken is the token text */
110022  int *pnBytes,                       /* OUT: Number of bytes in token */
110023  int *piStartOffset,                 /* OUT: Starting offset of token */
110024  int *piEndOffset,                   /* OUT: Ending offset of token */
110025  int *piPosition                     /* OUT: Position integer of token */
110026){
110027  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
110028  const char *z = c->zInput;
110029
110030  while( c->iOffset<c->nInput ){
110031    int iStartOffset, ch;
110032
110033    /* Scan past delimiter characters */
110034    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
110035      c->iOffset++;
110036    }
110037
110038    /* Count non-delimiter characters. */
110039    iStartOffset = c->iOffset;
110040    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
110041      c->iOffset++;
110042    }
110043
110044    if( c->iOffset>iStartOffset ){
110045      int n = c->iOffset-iStartOffset;
110046      if( n>c->nAllocated ){
110047        char *pNew;
110048        c->nAllocated = n+20;
110049        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
110050        if( !pNew ) return SQLITE_NOMEM;
110051        c->zToken = pNew;
110052      }
110053      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
110054      *pzToken = c->zToken;
110055      *piStartOffset = iStartOffset;
110056      *piEndOffset = c->iOffset;
110057      *piPosition = c->iToken++;
110058      return SQLITE_OK;
110059    }
110060  }
110061  return SQLITE_DONE;
110062}
110063
110064/*
110065** The set of routines that implement the porter-stemmer tokenizer
110066*/
110067static const sqlite3_tokenizer_module porterTokenizerModule = {
110068  0,
110069  porterCreate,
110070  porterDestroy,
110071  porterOpen,
110072  porterClose,
110073  porterNext,
110074};
110075
110076/*
110077** Allocate a new porter tokenizer.  Return a pointer to the new
110078** tokenizer in *ppModule
110079*/
110080SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
110081  sqlite3_tokenizer_module const**ppModule
110082){
110083  *ppModule = &porterTokenizerModule;
110084}
110085
110086#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110087
110088/************** End of fts3_porter.c *****************************************/
110089/************** Begin file fts3_tokenizer.c **********************************/
110090/*
110091** 2007 June 22
110092**
110093** The author disclaims copyright to this source code.  In place of
110094** a legal notice, here is a blessing:
110095**
110096**    May you do good and not evil.
110097**    May you find forgiveness for yourself and forgive others.
110098**    May you share freely, never taking more than you give.
110099**
110100******************************************************************************
110101**
110102** This is part of an SQLite module implementing full-text search.
110103** This particular file implements the generic tokenizer interface.
110104*/
110105
110106/*
110107** The code in this file is only compiled if:
110108**
110109**     * The FTS3 module is being built as an extension
110110**       (in which case SQLITE_CORE is not defined), or
110111**
110112**     * The FTS3 module is being built into the core of
110113**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110114*/
110115#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110116
110117#ifndef SQLITE_CORE
110118  SQLITE_EXTENSION_INIT1
110119#endif
110120
110121
110122/*
110123** Implementation of the SQL scalar function for accessing the underlying
110124** hash table. This function may be called as follows:
110125**
110126**   SELECT <function-name>(<key-name>);
110127**   SELECT <function-name>(<key-name>, <pointer>);
110128**
110129** where <function-name> is the name passed as the second argument
110130** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
110131**
110132** If the <pointer> argument is specified, it must be a blob value
110133** containing a pointer to be stored as the hash data corresponding
110134** to the string <key-name>. If <pointer> is not specified, then
110135** the string <key-name> must already exist in the has table. Otherwise,
110136** an error is returned.
110137**
110138** Whether or not the <pointer> argument is specified, the value returned
110139** is a blob containing the pointer stored as the hash data corresponding
110140** to string <key-name> (after the hash-table is updated, if applicable).
110141*/
110142static void scalarFunc(
110143  sqlite3_context *context,
110144  int argc,
110145  sqlite3_value **argv
110146){
110147  Fts3Hash *pHash;
110148  void *pPtr = 0;
110149  const unsigned char *zName;
110150  int nName;
110151
110152  assert( argc==1 || argc==2 );
110153
110154  pHash = (Fts3Hash *)sqlite3_user_data(context);
110155
110156  zName = sqlite3_value_text(argv[0]);
110157  nName = sqlite3_value_bytes(argv[0])+1;
110158
110159  if( argc==2 ){
110160    void *pOld;
110161    int n = sqlite3_value_bytes(argv[1]);
110162    if( n!=sizeof(pPtr) ){
110163      sqlite3_result_error(context, "argument type mismatch", -1);
110164      return;
110165    }
110166    pPtr = *(void **)sqlite3_value_blob(argv[1]);
110167    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
110168    if( pOld==pPtr ){
110169      sqlite3_result_error(context, "out of memory", -1);
110170      return;
110171    }
110172  }else{
110173    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
110174    if( !pPtr ){
110175      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110176      sqlite3_result_error(context, zErr, -1);
110177      sqlite3_free(zErr);
110178      return;
110179    }
110180  }
110181
110182  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
110183}
110184
110185static int fts3IsIdChar(char c){
110186  static const char isFtsIdChar[] = {
110187      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
110188      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
110189      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
110190      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110191      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110192      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110193      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110194      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110195  };
110196  return (c&0x80 || isFtsIdChar[(int)(c)]);
110197}
110198
110199SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
110200  const char *z1;
110201  const char *z2 = 0;
110202
110203  /* Find the start of the next token. */
110204  z1 = zStr;
110205  while( z2==0 ){
110206    char c = *z1;
110207    switch( c ){
110208      case '\0': return 0;        /* No more tokens here */
110209      case '\'':
110210      case '"':
110211      case '`': {
110212        z2 = z1;
110213        while( *++z2 && (*z2!=c || *++z2==c) );
110214        break;
110215      }
110216      case '[':
110217        z2 = &z1[1];
110218        while( *z2 && z2[0]!=']' ) z2++;
110219        if( *z2 ) z2++;
110220        break;
110221
110222      default:
110223        if( fts3IsIdChar(*z1) ){
110224          z2 = &z1[1];
110225          while( fts3IsIdChar(*z2) ) z2++;
110226        }else{
110227          z1++;
110228        }
110229    }
110230  }
110231
110232  *pn = (int)(z2-z1);
110233  return z1;
110234}
110235
110236SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
110237  Fts3Hash *pHash,                /* Tokenizer hash table */
110238  const char *zArg,               /* Possible tokenizer specification */
110239  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
110240  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
110241  char **pzErr                    /* OUT: Set to malloced error message */
110242){
110243  int rc;
110244  char *z = (char *)zArg;
110245  int n;
110246  char *zCopy;
110247  char *zEnd;                     /* Pointer to nul-term of zCopy */
110248  sqlite3_tokenizer_module *m;
110249
110250  if( !z ){
110251    zCopy = sqlite3_mprintf("simple");
110252  }else{
110253    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
110254      return SQLITE_OK;
110255    }
110256    zCopy = sqlite3_mprintf("%s", &z[8]);
110257    *pzTokenizer = zArg;
110258  }
110259  if( !zCopy ){
110260    return SQLITE_NOMEM;
110261  }
110262
110263  zEnd = &zCopy[strlen(zCopy)];
110264
110265  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
110266  z[n] = '\0';
110267  sqlite3Fts3Dequote(z);
110268
110269  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
110270  if( !m ){
110271    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
110272    rc = SQLITE_ERROR;
110273  }else{
110274    char const **aArg = 0;
110275    int iArg = 0;
110276    z = &z[n+1];
110277    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
110278      int nNew = sizeof(char *)*(iArg+1);
110279      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
110280      if( !aNew ){
110281        sqlite3_free(zCopy);
110282        sqlite3_free((void *)aArg);
110283        return SQLITE_NOMEM;
110284      }
110285      aArg = aNew;
110286      aArg[iArg++] = z;
110287      z[n] = '\0';
110288      sqlite3Fts3Dequote(z);
110289      z = &z[n+1];
110290    }
110291    rc = m->xCreate(iArg, aArg, ppTok);
110292    assert( rc!=SQLITE_OK || *ppTok );
110293    if( rc!=SQLITE_OK ){
110294      *pzErr = sqlite3_mprintf("unknown tokenizer");
110295    }else{
110296      (*ppTok)->pModule = m;
110297    }
110298    sqlite3_free((void *)aArg);
110299  }
110300
110301  sqlite3_free(zCopy);
110302  return rc;
110303}
110304
110305
110306#ifdef SQLITE_TEST
110307
110308
110309/*
110310** Implementation of a special SQL scalar function for testing tokenizers
110311** designed to be used in concert with the Tcl testing framework. This
110312** function must be called with two arguments:
110313**
110314**   SELECT <function-name>(<key-name>, <input-string>);
110315**   SELECT <function-name>(<key-name>, <pointer>);
110316**
110317** where <function-name> is the name passed as the second argument
110318** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
110319** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
110320**
110321** The return value is a string that may be interpreted as a Tcl
110322** list. For each token in the <input-string>, three elements are
110323** added to the returned list. The first is the token position, the
110324** second is the token text (folded, stemmed, etc.) and the third is the
110325** substring of <input-string> associated with the token. For example,
110326** using the built-in "simple" tokenizer:
110327**
110328**   SELECT fts_tokenizer_test('simple', 'I don't see how');
110329**
110330** will return the string:
110331**
110332**   "{0 i I 1 dont don't 2 see see 3 how how}"
110333**
110334*/
110335static void testFunc(
110336  sqlite3_context *context,
110337  int argc,
110338  sqlite3_value **argv
110339){
110340  Fts3Hash *pHash;
110341  sqlite3_tokenizer_module *p;
110342  sqlite3_tokenizer *pTokenizer = 0;
110343  sqlite3_tokenizer_cursor *pCsr = 0;
110344
110345  const char *zErr = 0;
110346
110347  const char *zName;
110348  int nName;
110349  const char *zInput;
110350  int nInput;
110351
110352  const char *zArg = 0;
110353
110354  const char *zToken;
110355  int nToken;
110356  int iStart;
110357  int iEnd;
110358  int iPos;
110359
110360  Tcl_Obj *pRet;
110361
110362  assert( argc==2 || argc==3 );
110363
110364  nName = sqlite3_value_bytes(argv[0]);
110365  zName = (const char *)sqlite3_value_text(argv[0]);
110366  nInput = sqlite3_value_bytes(argv[argc-1]);
110367  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
110368
110369  if( argc==3 ){
110370    zArg = (const char *)sqlite3_value_text(argv[1]);
110371  }
110372
110373  pHash = (Fts3Hash *)sqlite3_user_data(context);
110374  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
110375
110376  if( !p ){
110377    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110378    sqlite3_result_error(context, zErr, -1);
110379    sqlite3_free(zErr);
110380    return;
110381  }
110382
110383  pRet = Tcl_NewObj();
110384  Tcl_IncrRefCount(pRet);
110385
110386  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
110387    zErr = "error in xCreate()";
110388    goto finish;
110389  }
110390  pTokenizer->pModule = p;
110391  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
110392    zErr = "error in xOpen()";
110393    goto finish;
110394  }
110395  pCsr->pTokenizer = pTokenizer;
110396
110397  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
110398    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
110399    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110400    zToken = &zInput[iStart];
110401    nToken = iEnd-iStart;
110402    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110403  }
110404
110405  if( SQLITE_OK!=p->xClose(pCsr) ){
110406    zErr = "error in xClose()";
110407    goto finish;
110408  }
110409  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
110410    zErr = "error in xDestroy()";
110411    goto finish;
110412  }
110413
110414finish:
110415  if( zErr ){
110416    sqlite3_result_error(context, zErr, -1);
110417  }else{
110418    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
110419  }
110420  Tcl_DecrRefCount(pRet);
110421}
110422
110423static
110424int registerTokenizer(
110425  sqlite3 *db,
110426  char *zName,
110427  const sqlite3_tokenizer_module *p
110428){
110429  int rc;
110430  sqlite3_stmt *pStmt;
110431  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
110432
110433  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110434  if( rc!=SQLITE_OK ){
110435    return rc;
110436  }
110437
110438  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110439  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
110440  sqlite3_step(pStmt);
110441
110442  return sqlite3_finalize(pStmt);
110443}
110444
110445static
110446int queryTokenizer(
110447  sqlite3 *db,
110448  char *zName,
110449  const sqlite3_tokenizer_module **pp
110450){
110451  int rc;
110452  sqlite3_stmt *pStmt;
110453  const char zSql[] = "SELECT fts3_tokenizer(?)";
110454
110455  *pp = 0;
110456  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110457  if( rc!=SQLITE_OK ){
110458    return rc;
110459  }
110460
110461  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110462  if( SQLITE_ROW==sqlite3_step(pStmt) ){
110463    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
110464      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
110465    }
110466  }
110467
110468  return sqlite3_finalize(pStmt);
110469}
110470
110471SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110472
110473/*
110474** Implementation of the scalar function fts3_tokenizer_internal_test().
110475** This function is used for testing only, it is not included in the
110476** build unless SQLITE_TEST is defined.
110477**
110478** The purpose of this is to test that the fts3_tokenizer() function
110479** can be used as designed by the C-code in the queryTokenizer and
110480** registerTokenizer() functions above. These two functions are repeated
110481** in the README.tokenizer file as an example, so it is important to
110482** test them.
110483**
110484** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
110485** function with no arguments. An assert() will fail if a problem is
110486** detected. i.e.:
110487**
110488**     SELECT fts3_tokenizer_internal_test();
110489**
110490*/
110491static void intTestFunc(
110492  sqlite3_context *context,
110493  int argc,
110494  sqlite3_value **argv
110495){
110496  int rc;
110497  const sqlite3_tokenizer_module *p1;
110498  const sqlite3_tokenizer_module *p2;
110499  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
110500
110501  UNUSED_PARAMETER(argc);
110502  UNUSED_PARAMETER(argv);
110503
110504  /* Test the query function */
110505  sqlite3Fts3SimpleTokenizerModule(&p1);
110506  rc = queryTokenizer(db, "simple", &p2);
110507  assert( rc==SQLITE_OK );
110508  assert( p1==p2 );
110509  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110510  assert( rc==SQLITE_ERROR );
110511  assert( p2==0 );
110512  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
110513
110514  /* Test the storage function */
110515  rc = registerTokenizer(db, "nosuchtokenizer", p1);
110516  assert( rc==SQLITE_OK );
110517  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110518  assert( rc==SQLITE_OK );
110519  assert( p2==p1 );
110520
110521  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
110522}
110523
110524#endif
110525
110526/*
110527** Set up SQL objects in database db used to access the contents of
110528** the hash table pointed to by argument pHash. The hash table must
110529** been initialised to use string keys, and to take a private copy
110530** of the key when a value is inserted. i.e. by a call similar to:
110531**
110532**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
110533**
110534** This function adds a scalar function (see header comment above
110535** scalarFunc() in this file for details) and, if ENABLE_TABLE is
110536** defined at compilation time, a temporary virtual table (see header
110537** comment above struct HashTableVtab) to the database schema. Both
110538** provide read/write access to the contents of *pHash.
110539**
110540** The third argument to this function, zName, is used as the name
110541** of both the scalar and, if created, the virtual table.
110542*/
110543SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
110544  sqlite3 *db,
110545  Fts3Hash *pHash,
110546  const char *zName
110547){
110548  int rc = SQLITE_OK;
110549  void *p = (void *)pHash;
110550  const int any = SQLITE_ANY;
110551
110552#ifdef SQLITE_TEST
110553  char *zTest = 0;
110554  char *zTest2 = 0;
110555  void *pdb = (void *)db;
110556  zTest = sqlite3_mprintf("%s_test", zName);
110557  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
110558  if( !zTest || !zTest2 ){
110559    rc = SQLITE_NOMEM;
110560  }
110561#endif
110562
110563  if( SQLITE_OK!=rc
110564   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
110565   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
110566#ifdef SQLITE_TEST
110567   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
110568   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
110569   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
110570#endif
110571   );
110572
110573#ifdef SQLITE_TEST
110574  sqlite3_free(zTest);
110575  sqlite3_free(zTest2);
110576#endif
110577
110578  return rc;
110579}
110580
110581#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110582
110583/************** End of fts3_tokenizer.c **************************************/
110584/************** Begin file fts3_tokenizer1.c *********************************/
110585/*
110586** 2006 Oct 10
110587**
110588** The author disclaims copyright to this source code.  In place of
110589** a legal notice, here is a blessing:
110590**
110591**    May you do good and not evil.
110592**    May you find forgiveness for yourself and forgive others.
110593**    May you share freely, never taking more than you give.
110594**
110595******************************************************************************
110596**
110597** Implementation of the "simple" full-text-search tokenizer.
110598*/
110599
110600/*
110601** The code in this file is only compiled if:
110602**
110603**     * The FTS3 module is being built as an extension
110604**       (in which case SQLITE_CORE is not defined), or
110605**
110606**     * The FTS3 module is being built into the core of
110607**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110608*/
110609#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110610
110611
110612
110613
110614typedef struct simple_tokenizer {
110615  sqlite3_tokenizer base;
110616  char delim[128];             /* flag ASCII delimiters */
110617} simple_tokenizer;
110618
110619typedef struct simple_tokenizer_cursor {
110620  sqlite3_tokenizer_cursor base;
110621  const char *pInput;          /* input we are tokenizing */
110622  int nBytes;                  /* size of the input */
110623  int iOffset;                 /* current position in pInput */
110624  int iToken;                  /* index of next token to be returned */
110625  char *pToken;                /* storage for current token */
110626  int nTokenAllocated;         /* space allocated to zToken buffer */
110627} simple_tokenizer_cursor;
110628
110629
110630static int simpleDelim(simple_tokenizer *t, unsigned char c){
110631  return c<0x80 && t->delim[c];
110632}
110633
110634/*
110635** Create a new tokenizer instance.
110636*/
110637static int simpleCreate(
110638  int argc, const char * const *argv,
110639  sqlite3_tokenizer **ppTokenizer
110640){
110641  simple_tokenizer *t;
110642
110643  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
110644  if( t==NULL ) return SQLITE_NOMEM;
110645  memset(t, 0, sizeof(*t));
110646
110647  /* TODO(shess) Delimiters need to remain the same from run to run,
110648  ** else we need to reindex.  One solution would be a meta-table to
110649  ** track such information in the database, then we'd only want this
110650  ** information on the initial create.
110651  */
110652  if( argc>1 ){
110653    int i, n = (int)strlen(argv[1]);
110654    for(i=0; i<n; i++){
110655      unsigned char ch = argv[1][i];
110656      /* We explicitly don't support UTF-8 delimiters for now. */
110657      if( ch>=0x80 ){
110658        sqlite3_free(t);
110659        return SQLITE_ERROR;
110660      }
110661      t->delim[ch] = 1;
110662    }
110663  } else {
110664    /* Mark non-alphanumeric ASCII characters as delimiters */
110665    int i;
110666    for(i=1; i<0x80; i++){
110667      t->delim[i] = !isalnum(i) ? -1 : 0;
110668    }
110669  }
110670
110671  *ppTokenizer = &t->base;
110672  return SQLITE_OK;
110673}
110674
110675/*
110676** Destroy a tokenizer
110677*/
110678static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
110679  sqlite3_free(pTokenizer);
110680  return SQLITE_OK;
110681}
110682
110683/*
110684** Prepare to begin tokenizing a particular string.  The input
110685** string to be tokenized is pInput[0..nBytes-1].  A cursor
110686** used to incrementally tokenize this string is returned in
110687** *ppCursor.
110688*/
110689static int simpleOpen(
110690  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110691  const char *pInput, int nBytes,        /* String to be tokenized */
110692  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110693){
110694  simple_tokenizer_cursor *c;
110695
110696  UNUSED_PARAMETER(pTokenizer);
110697
110698  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
110699  if( c==NULL ) return SQLITE_NOMEM;
110700
110701  c->pInput = pInput;
110702  if( pInput==0 ){
110703    c->nBytes = 0;
110704  }else if( nBytes<0 ){
110705    c->nBytes = (int)strlen(pInput);
110706  }else{
110707    c->nBytes = nBytes;
110708  }
110709  c->iOffset = 0;                 /* start tokenizing at the beginning */
110710  c->iToken = 0;
110711  c->pToken = NULL;               /* no space allocated, yet. */
110712  c->nTokenAllocated = 0;
110713
110714  *ppCursor = &c->base;
110715  return SQLITE_OK;
110716}
110717
110718/*
110719** Close a tokenization cursor previously opened by a call to
110720** simpleOpen() above.
110721*/
110722static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
110723  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
110724  sqlite3_free(c->pToken);
110725  sqlite3_free(c);
110726  return SQLITE_OK;
110727}
110728
110729/*
110730** Extract the next token from a tokenization cursor.  The cursor must
110731** have been opened by a prior call to simpleOpen().
110732*/
110733static int simpleNext(
110734  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
110735  const char **ppToken,               /* OUT: *ppToken is the token text */
110736  int *pnBytes,                       /* OUT: Number of bytes in token */
110737  int *piStartOffset,                 /* OUT: Starting offset of token */
110738  int *piEndOffset,                   /* OUT: Ending offset of token */
110739  int *piPosition                     /* OUT: Position integer of token */
110740){
110741  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
110742  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
110743  unsigned char *p = (unsigned char *)c->pInput;
110744
110745  while( c->iOffset<c->nBytes ){
110746    int iStartOffset;
110747
110748    /* Scan past delimiter characters */
110749    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
110750      c->iOffset++;
110751    }
110752
110753    /* Count non-delimiter characters. */
110754    iStartOffset = c->iOffset;
110755    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
110756      c->iOffset++;
110757    }
110758
110759    if( c->iOffset>iStartOffset ){
110760      int i, n = c->iOffset-iStartOffset;
110761      if( n>c->nTokenAllocated ){
110762        char *pNew;
110763        c->nTokenAllocated = n+20;
110764        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
110765        if( !pNew ) return SQLITE_NOMEM;
110766        c->pToken = pNew;
110767      }
110768      for(i=0; i<n; i++){
110769        /* TODO(shess) This needs expansion to handle UTF-8
110770        ** case-insensitivity.
110771        */
110772        unsigned char ch = p[iStartOffset+i];
110773        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
110774      }
110775      *ppToken = c->pToken;
110776      *pnBytes = n;
110777      *piStartOffset = iStartOffset;
110778      *piEndOffset = c->iOffset;
110779      *piPosition = c->iToken++;
110780
110781      return SQLITE_OK;
110782    }
110783  }
110784  return SQLITE_DONE;
110785}
110786
110787/*
110788** The set of routines that implement the simple tokenizer
110789*/
110790static const sqlite3_tokenizer_module simpleTokenizerModule = {
110791  0,
110792  simpleCreate,
110793  simpleDestroy,
110794  simpleOpen,
110795  simpleClose,
110796  simpleNext,
110797};
110798
110799/*
110800** Allocate a new simple tokenizer.  Return a pointer to the new
110801** tokenizer in *ppModule
110802*/
110803SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
110804  sqlite3_tokenizer_module const**ppModule
110805){
110806  *ppModule = &simpleTokenizerModule;
110807}
110808
110809#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110810
110811/************** End of fts3_tokenizer1.c *************************************/
110812/************** Begin file fts3_write.c **************************************/
110813/*
110814** 2009 Oct 23
110815**
110816** The author disclaims copyright to this source code.  In place of
110817** a legal notice, here is a blessing:
110818**
110819**    May you do good and not evil.
110820**    May you find forgiveness for yourself and forgive others.
110821**    May you share freely, never taking more than you give.
110822**
110823******************************************************************************
110824**
110825** This file is part of the SQLite FTS3 extension module. Specifically,
110826** this file contains code to insert, update and delete rows from FTS3
110827** tables. It also contains code to merge FTS3 b-tree segments. Some
110828** of the sub-routines used to merge segments are also used by the query
110829** code in fts3.c.
110830*/
110831
110832#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110833
110834
110835typedef struct PendingList PendingList;
110836typedef struct SegmentNode SegmentNode;
110837typedef struct SegmentWriter SegmentWriter;
110838
110839/*
110840** Data structure used while accumulating terms in the pending-terms hash
110841** table. The hash table entry maps from term (a string) to a malloc'd
110842** instance of this structure.
110843*/
110844struct PendingList {
110845  int nData;
110846  char *aData;
110847  int nSpace;
110848  sqlite3_int64 iLastDocid;
110849  sqlite3_int64 iLastCol;
110850  sqlite3_int64 iLastPos;
110851};
110852
110853/*
110854** An instance of this structure is used to iterate through the terms on
110855** a contiguous set of segment b-tree leaf nodes. Although the details of
110856** this structure are only manipulated by code in this file, opaque handles
110857** of type Fts3SegReader* are also used by code in fts3.c to iterate through
110858** terms when querying the full-text index. See functions:
110859**
110860**   sqlite3Fts3SegReaderNew()
110861**   sqlite3Fts3SegReaderFree()
110862**   sqlite3Fts3SegReaderIterate()
110863**
110864** Methods used to manipulate Fts3SegReader structures:
110865**
110866**   fts3SegReaderNext()
110867**   fts3SegReaderFirstDocid()
110868**   fts3SegReaderNextDocid()
110869*/
110870struct Fts3SegReader {
110871  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
110872  sqlite3_int64 iStartBlock;
110873  sqlite3_int64 iEndBlock;
110874  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
110875  char *aNode;                    /* Pointer to node data (or NULL) */
110876  int nNode;                      /* Size of buffer at aNode (or 0) */
110877  int nTermAlloc;                 /* Allocated size of zTerm buffer */
110878  Fts3HashElem **ppNextElem;
110879
110880  /* Variables set by fts3SegReaderNext(). These may be read directly
110881  ** by the caller. They are valid from the time SegmentReaderNew() returns
110882  ** until SegmentReaderNext() returns something other than SQLITE_OK
110883  ** (i.e. SQLITE_DONE).
110884  */
110885  int nTerm;                      /* Number of bytes in current term */
110886  char *zTerm;                    /* Pointer to current term */
110887  char *aDoclist;                 /* Pointer to doclist of current entry */
110888  int nDoclist;                   /* Size of doclist in current entry */
110889
110890  /* The following variables are used to iterate through the current doclist */
110891  char *pOffsetList;
110892  sqlite3_int64 iDocid;
110893};
110894
110895#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
110896
110897/*
110898** An instance of this structure is used to create a segment b-tree in the
110899** database. The internal details of this type are only accessed by the
110900** following functions:
110901**
110902**   fts3SegWriterAdd()
110903**   fts3SegWriterFlush()
110904**   fts3SegWriterFree()
110905*/
110906struct SegmentWriter {
110907  SegmentNode *pTree;             /* Pointer to interior tree structure */
110908  sqlite3_int64 iFirst;           /* First slot in %_segments written */
110909  sqlite3_int64 iFree;            /* Next free slot in %_segments */
110910  char *zTerm;                    /* Pointer to previous term buffer */
110911  int nTerm;                      /* Number of bytes in zTerm */
110912  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
110913  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
110914  int nSize;                      /* Size of allocation at aData */
110915  int nData;                      /* Bytes of data in aData */
110916  char *aData;                    /* Pointer to block from malloc() */
110917};
110918
110919/*
110920** Type SegmentNode is used by the following three functions to create
110921** the interior part of the segment b+-tree structures (everything except
110922** the leaf nodes). These functions and type are only ever used by code
110923** within the fts3SegWriterXXX() family of functions described above.
110924**
110925**   fts3NodeAddTerm()
110926**   fts3NodeWrite()
110927**   fts3NodeFree()
110928*/
110929struct SegmentNode {
110930  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
110931  SegmentNode *pRight;            /* Pointer to right-sibling */
110932  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
110933  int nEntry;                     /* Number of terms written to node so far */
110934  char *zTerm;                    /* Pointer to previous term buffer */
110935  int nTerm;                      /* Number of bytes in zTerm */
110936  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
110937  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
110938  int nData;                      /* Bytes of valid data so far */
110939  char *aData;                    /* Node data */
110940};
110941
110942/*
110943** Valid values for the second argument to fts3SqlStmt().
110944*/
110945#define SQL_DELETE_CONTENT             0
110946#define SQL_IS_EMPTY                   1
110947#define SQL_DELETE_ALL_CONTENT         2
110948#define SQL_DELETE_ALL_SEGMENTS        3
110949#define SQL_DELETE_ALL_SEGDIR          4
110950#define SQL_DELETE_ALL_DOCSIZE         5
110951#define SQL_DELETE_ALL_STAT            6
110952#define SQL_SELECT_CONTENT_BY_ROWID    7
110953#define SQL_NEXT_SEGMENT_INDEX         8
110954#define SQL_INSERT_SEGMENTS            9
110955#define SQL_NEXT_SEGMENTS_ID          10
110956#define SQL_INSERT_SEGDIR             11
110957#define SQL_SELECT_LEVEL              12
110958#define SQL_SELECT_ALL_LEVEL          13
110959#define SQL_SELECT_LEVEL_COUNT        14
110960#define SQL_SELECT_SEGDIR_COUNT_MAX   15
110961#define SQL_DELETE_SEGDIR_BY_LEVEL    16
110962#define SQL_DELETE_SEGMENTS_RANGE     17
110963#define SQL_CONTENT_INSERT            18
110964#define SQL_GET_BLOCK                 19
110965#define SQL_DELETE_DOCSIZE            20
110966#define SQL_REPLACE_DOCSIZE           21
110967#define SQL_SELECT_DOCSIZE            22
110968#define SQL_SELECT_DOCTOTAL           23
110969#define SQL_REPLACE_DOCTOTAL          24
110970
110971/*
110972** This function is used to obtain an SQLite prepared statement handle
110973** for the statement identified by the second argument. If successful,
110974** *pp is set to the requested statement handle and SQLITE_OK returned.
110975** Otherwise, an SQLite error code is returned and *pp is set to 0.
110976**
110977** If argument apVal is not NULL, then it must point to an array with
110978** at least as many entries as the requested statement has bound
110979** parameters. The values are bound to the statements parameters before
110980** returning.
110981*/
110982static int fts3SqlStmt(
110983  Fts3Table *p,                   /* Virtual table handle */
110984  int eStmt,                      /* One of the SQL_XXX constants above */
110985  sqlite3_stmt **pp,              /* OUT: Statement handle */
110986  sqlite3_value **apVal           /* Values to bind to statement */
110987){
110988  const char *azSql[] = {
110989/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
110990/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
110991/* 2  */  "DELETE FROM %Q.'%q_content'",
110992/* 3  */  "DELETE FROM %Q.'%q_segments'",
110993/* 4  */  "DELETE FROM %Q.'%q_segdir'",
110994/* 5  */  "DELETE FROM %Q.'%q_docsize'",
110995/* 6  */  "DELETE FROM %Q.'%q_stat'",
110996/* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
110997/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
110998/* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
110999/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
111000/* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
111001
111002          /* Return segments in order from oldest to newest.*/
111003/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111004            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
111005/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111006            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
111007
111008/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
111009/* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
111010
111011/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
111012/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
111013/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
111014/* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
111015/* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
111016/* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
111017/* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
111018/* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
111019/* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
111020  };
111021  int rc = SQLITE_OK;
111022  sqlite3_stmt *pStmt;
111023
111024  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
111025  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
111026
111027  pStmt = p->aStmt[eStmt];
111028  if( !pStmt ){
111029    char *zSql;
111030    if( eStmt==SQL_CONTENT_INSERT ){
111031      int i;                      /* Iterator variable */
111032      char *zVarlist;             /* The "?, ?, ..." string */
111033      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
111034      if( !zVarlist ){
111035        *pp = 0;
111036        return SQLITE_NOMEM;
111037      }
111038      zVarlist[0] = '?';
111039      zVarlist[p->nColumn*2+1] = '\0';
111040      for(i=1; i<=p->nColumn; i++){
111041        zVarlist[i*2-1] = ',';
111042        zVarlist[i*2] = '?';
111043      }
111044      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
111045    }else{
111046      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
111047    }
111048    if( !zSql ){
111049      rc = SQLITE_NOMEM;
111050    }else{
111051      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
111052      sqlite3_free(zSql);
111053      assert( rc==SQLITE_OK || pStmt==0 );
111054      p->aStmt[eStmt] = pStmt;
111055    }
111056  }
111057  if( apVal ){
111058    int i;
111059    int nParam = sqlite3_bind_parameter_count(pStmt);
111060    for(i=0; rc==SQLITE_OK && i<nParam; i++){
111061      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
111062    }
111063  }
111064  *pp = pStmt;
111065  return rc;
111066}
111067
111068/*
111069** Similar to fts3SqlStmt(). Except, after binding the parameters in
111070** array apVal[] to the SQL statement identified by eStmt, the statement
111071** is executed.
111072**
111073** Returns SQLITE_OK if the statement is successfully executed, or an
111074** SQLite error code otherwise.
111075*/
111076static void fts3SqlExec(
111077  int *pRC,                /* Result code */
111078  Fts3Table *p,            /* The FTS3 table */
111079  int eStmt,               /* Index of statement to evaluate */
111080  sqlite3_value **apVal    /* Parameters to bind */
111081){
111082  sqlite3_stmt *pStmt;
111083  int rc;
111084  if( *pRC ) return;
111085  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
111086  if( rc==SQLITE_OK ){
111087    sqlite3_step(pStmt);
111088    rc = sqlite3_reset(pStmt);
111089  }
111090  *pRC = rc;
111091}
111092
111093
111094/*
111095** Read a single block from the %_segments table. If the specified block
111096** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
111097** etc.) occurs, return the appropriate SQLite error code.
111098**
111099** Otherwise, if successful, set *pzBlock to point to a buffer containing
111100** the block read from the database, and *pnBlock to the size of the read
111101** block in bytes.
111102**
111103** WARNING: The returned buffer is only valid until the next call to
111104** sqlite3Fts3ReadBlock().
111105*/
111106SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
111107  Fts3Table *p,
111108  sqlite3_int64 iBlock,
111109  char const **pzBlock,
111110  int *pnBlock
111111){
111112  sqlite3_stmt *pStmt;
111113  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
111114  if( rc!=SQLITE_OK ) return rc;
111115  sqlite3_reset(pStmt);
111116
111117  if( pzBlock ){
111118    sqlite3_bind_int64(pStmt, 1, iBlock);
111119    rc = sqlite3_step(pStmt);
111120    if( rc!=SQLITE_ROW ){
111121      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
111122    }
111123
111124    *pnBlock = sqlite3_column_bytes(pStmt, 0);
111125    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
111126    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
111127      return SQLITE_CORRUPT;
111128    }
111129  }
111130  return SQLITE_OK;
111131}
111132
111133/*
111134** Set *ppStmt to a statement handle that may be used to iterate through
111135** all rows in the %_segdir table, from oldest to newest. If successful,
111136** return SQLITE_OK. If an error occurs while preparing the statement,
111137** return an SQLite error code.
111138**
111139** There is only ever one instance of this SQL statement compiled for
111140** each FTS3 table.
111141**
111142** The statement returns the following columns from the %_segdir table:
111143**
111144**   0: idx
111145**   1: start_block
111146**   2: leaves_end_block
111147**   3: end_block
111148**   4: root
111149*/
111150SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
111151  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
111152}
111153
111154
111155/*
111156** Append a single varint to a PendingList buffer. SQLITE_OK is returned
111157** if successful, or an SQLite error code otherwise.
111158**
111159** This function also serves to allocate the PendingList structure itself.
111160** For example, to create a new PendingList structure containing two
111161** varints:
111162**
111163**   PendingList *p = 0;
111164**   fts3PendingListAppendVarint(&p, 1);
111165**   fts3PendingListAppendVarint(&p, 2);
111166*/
111167static int fts3PendingListAppendVarint(
111168  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
111169  sqlite3_int64 i                 /* Value to append to data */
111170){
111171  PendingList *p = *pp;
111172
111173  /* Allocate or grow the PendingList as required. */
111174  if( !p ){
111175    p = sqlite3_malloc(sizeof(*p) + 100);
111176    if( !p ){
111177      return SQLITE_NOMEM;
111178    }
111179    p->nSpace = 100;
111180    p->aData = (char *)&p[1];
111181    p->nData = 0;
111182  }
111183  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
111184    int nNew = p->nSpace * 2;
111185    p = sqlite3_realloc(p, sizeof(*p) + nNew);
111186    if( !p ){
111187      sqlite3_free(*pp);
111188      *pp = 0;
111189      return SQLITE_NOMEM;
111190    }
111191    p->nSpace = nNew;
111192    p->aData = (char *)&p[1];
111193  }
111194
111195  /* Append the new serialized varint to the end of the list. */
111196  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
111197  p->aData[p->nData] = '\0';
111198  *pp = p;
111199  return SQLITE_OK;
111200}
111201
111202/*
111203** Add a docid/column/position entry to a PendingList structure. Non-zero
111204** is returned if the structure is sqlite3_realloced as part of adding
111205** the entry. Otherwise, zero.
111206**
111207** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
111208** Zero is always returned in this case. Otherwise, if no OOM error occurs,
111209** it is set to SQLITE_OK.
111210*/
111211static int fts3PendingListAppend(
111212  PendingList **pp,               /* IN/OUT: PendingList structure */
111213  sqlite3_int64 iDocid,           /* Docid for entry to add */
111214  sqlite3_int64 iCol,             /* Column for entry to add */
111215  sqlite3_int64 iPos,             /* Position of term for entry to add */
111216  int *pRc                        /* OUT: Return code */
111217){
111218  PendingList *p = *pp;
111219  int rc = SQLITE_OK;
111220
111221  assert( !p || p->iLastDocid<=iDocid );
111222
111223  if( !p || p->iLastDocid!=iDocid ){
111224    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
111225    if( p ){
111226      assert( p->nData<p->nSpace );
111227      assert( p->aData[p->nData]==0 );
111228      p->nData++;
111229    }
111230    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
111231      goto pendinglistappend_out;
111232    }
111233    p->iLastCol = -1;
111234    p->iLastPos = 0;
111235    p->iLastDocid = iDocid;
111236  }
111237  if( iCol>0 && p->iLastCol!=iCol ){
111238    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
111239     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
111240    ){
111241      goto pendinglistappend_out;
111242    }
111243    p->iLastCol = iCol;
111244    p->iLastPos = 0;
111245  }
111246  if( iCol>=0 ){
111247    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
111248    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
111249    if( rc==SQLITE_OK ){
111250      p->iLastPos = iPos;
111251    }
111252  }
111253
111254 pendinglistappend_out:
111255  *pRc = rc;
111256  if( p!=*pp ){
111257    *pp = p;
111258    return 1;
111259  }
111260  return 0;
111261}
111262
111263/*
111264** Tokenize the nul-terminated string zText and add all tokens to the
111265** pending-terms hash-table. The docid used is that currently stored in
111266** p->iPrevDocid, and the column is specified by argument iCol.
111267**
111268** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
111269*/
111270static int fts3PendingTermsAdd(
111271  Fts3Table *p,          /* FTS table into which text will be inserted */
111272  const char *zText,     /* Text of document to be inseted */
111273  int iCol,              /* Column number into which text is inserted */
111274  u32 *pnWord            /* OUT: Number of tokens inserted */
111275){
111276  int rc;
111277  int iStart;
111278  int iEnd;
111279  int iPos;
111280  int nWord = 0;
111281
111282  char const *zToken;
111283  int nToken;
111284
111285  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
111286  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
111287  sqlite3_tokenizer_cursor *pCsr;
111288  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
111289      const char**,int*,int*,int*,int*);
111290
111291  assert( pTokenizer && pModule );
111292
111293  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
111294  if( rc!=SQLITE_OK ){
111295    return rc;
111296  }
111297  pCsr->pTokenizer = pTokenizer;
111298
111299  xNext = pModule->xNext;
111300  while( SQLITE_OK==rc
111301      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
111302  ){
111303    PendingList *pList;
111304
111305    if( iPos>=nWord ) nWord = iPos+1;
111306
111307    /* Positions cannot be negative; we use -1 as a terminator internally.
111308    ** Tokens must have a non-zero length.
111309    */
111310    if( iPos<0 || !zToken || nToken<=0 ){
111311      rc = SQLITE_ERROR;
111312      break;
111313    }
111314
111315    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
111316    if( pList ){
111317      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
111318    }
111319    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
111320      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
111321        /* Malloc failed while inserting the new entry. This can only
111322        ** happen if there was no previous entry for this token.
111323        */
111324        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
111325        sqlite3_free(pList);
111326        rc = SQLITE_NOMEM;
111327      }
111328    }
111329    if( rc==SQLITE_OK ){
111330      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
111331    }
111332  }
111333
111334  pModule->xClose(pCsr);
111335  *pnWord = nWord;
111336  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
111337}
111338
111339/*
111340** Calling this function indicates that subsequent calls to
111341** fts3PendingTermsAdd() are to add term/position-list pairs for the
111342** contents of the document with docid iDocid.
111343*/
111344static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
111345  /* TODO(shess) Explore whether partially flushing the buffer on
111346  ** forced-flush would provide better performance.  I suspect that if
111347  ** we ordered the doclists by size and flushed the largest until the
111348  ** buffer was half empty, that would let the less frequent terms
111349  ** generate longer doclists.
111350  */
111351  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
111352    int rc = sqlite3Fts3PendingTermsFlush(p);
111353    if( rc!=SQLITE_OK ) return rc;
111354  }
111355  p->iPrevDocid = iDocid;
111356  return SQLITE_OK;
111357}
111358
111359SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
111360  Fts3HashElem *pElem;
111361  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
111362    sqlite3_free(fts3HashData(pElem));
111363  }
111364  fts3HashClear(&p->pendingTerms);
111365  p->nPendingData = 0;
111366}
111367
111368/*
111369** This function is called by the xUpdate() method as part of an INSERT
111370** operation. It adds entries for each term in the new record to the
111371** pendingTerms hash table.
111372**
111373** Argument apVal is the same as the similarly named argument passed to
111374** fts3InsertData(). Parameter iDocid is the docid of the new row.
111375*/
111376static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
111377  int i;                          /* Iterator variable */
111378  for(i=2; i<p->nColumn+2; i++){
111379    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
111380    if( zText ){
111381      int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
111382      if( rc!=SQLITE_OK ){
111383        return rc;
111384      }
111385    }
111386  }
111387  return SQLITE_OK;
111388}
111389
111390/*
111391** This function is called by the xUpdate() method for an INSERT operation.
111392** The apVal parameter is passed a copy of the apVal argument passed by
111393** SQLite to the xUpdate() method. i.e:
111394**
111395**   apVal[0]                Not used for INSERT.
111396**   apVal[1]                rowid
111397**   apVal[2]                Left-most user-defined column
111398**   ...
111399**   apVal[p->nColumn+1]     Right-most user-defined column
111400**   apVal[p->nColumn+2]     Hidden column with same name as table
111401**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
111402*/
111403static int fts3InsertData(
111404  Fts3Table *p,                   /* Full-text table */
111405  sqlite3_value **apVal,          /* Array of values to insert */
111406  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
111407){
111408  int rc;                         /* Return code */
111409  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
111410
111411  /* Locate the statement handle used to insert data into the %_content
111412  ** table. The SQL for this statement is:
111413  **
111414  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
111415  **
111416  ** The statement features N '?' variables, where N is the number of user
111417  ** defined columns in the FTS3 table, plus one for the docid field.
111418  */
111419  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
111420  if( rc!=SQLITE_OK ){
111421    return rc;
111422  }
111423
111424  /* There is a quirk here. The users INSERT statement may have specified
111425  ** a value for the "rowid" field, for the "docid" field, or for both.
111426  ** Which is a problem, since "rowid" and "docid" are aliases for the
111427  ** same value. For example:
111428  **
111429  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
111430  **
111431  ** In FTS3, this is an error. It is an error to specify non-NULL values
111432  ** for both docid and some other rowid alias.
111433  */
111434  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
111435    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
111436     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
111437    ){
111438      /* A rowid/docid conflict. */
111439      return SQLITE_ERROR;
111440    }
111441    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
111442    if( rc!=SQLITE_OK ) return rc;
111443  }
111444
111445  /* Execute the statement to insert the record. Set *piDocid to the
111446  ** new docid value.
111447  */
111448  sqlite3_step(pContentInsert);
111449  rc = sqlite3_reset(pContentInsert);
111450
111451  *piDocid = sqlite3_last_insert_rowid(p->db);
111452  return rc;
111453}
111454
111455
111456
111457/*
111458** Remove all data from the FTS3 table. Clear the hash table containing
111459** pending terms.
111460*/
111461static int fts3DeleteAll(Fts3Table *p){
111462  int rc = SQLITE_OK;             /* Return code */
111463
111464  /* Discard the contents of the pending-terms hash table. */
111465  sqlite3Fts3PendingTermsClear(p);
111466
111467  /* Delete everything from the %_content, %_segments and %_segdir tables. */
111468  fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
111469  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
111470  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
111471  if( p->bHasDocsize ){
111472    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
111473    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
111474  }
111475  return rc;
111476}
111477
111478/*
111479** The first element in the apVal[] array is assumed to contain the docid
111480** (an integer) of a row about to be deleted. Remove all terms from the
111481** full-text index.
111482*/
111483static void fts3DeleteTerms(
111484  int *pRC,               /* Result code */
111485  Fts3Table *p,           /* The FTS table to delete from */
111486  sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
111487  u32 *aSz                /* Sizes of deleted document written here */
111488){
111489  int rc;
111490  sqlite3_stmt *pSelect;
111491
111492  if( *pRC ) return;
111493  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
111494  if( rc==SQLITE_OK ){
111495    if( SQLITE_ROW==sqlite3_step(pSelect) ){
111496      int i;
111497      for(i=1; i<=p->nColumn; i++){
111498        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
111499        rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
111500        if( rc!=SQLITE_OK ){
111501          sqlite3_reset(pSelect);
111502          *pRC = rc;
111503          return;
111504        }
111505      }
111506    }
111507    rc = sqlite3_reset(pSelect);
111508  }else{
111509    sqlite3_reset(pSelect);
111510  }
111511  *pRC = rc;
111512}
111513
111514/*
111515** Forward declaration to account for the circular dependency between
111516** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
111517*/
111518static int fts3SegmentMerge(Fts3Table *, int);
111519
111520/*
111521** This function allocates a new level iLevel index in the segdir table.
111522** Usually, indexes are allocated within a level sequentially starting
111523** with 0, so the allocated index is one greater than the value returned
111524** by:
111525**
111526**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
111527**
111528** However, if there are already FTS3_MERGE_COUNT indexes at the requested
111529** level, they are merged into a single level (iLevel+1) segment and the
111530** allocated index is 0.
111531**
111532** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
111533** returned. Otherwise, an SQLite error code is returned.
111534*/
111535static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
111536  int rc;                         /* Return Code */
111537  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
111538  int iNext = 0;                  /* Result of query pNextIdx */
111539
111540  /* Set variable iNext to the next available segdir index at level iLevel. */
111541  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
111542  if( rc==SQLITE_OK ){
111543    sqlite3_bind_int(pNextIdx, 1, iLevel);
111544    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
111545      iNext = sqlite3_column_int(pNextIdx, 0);
111546    }
111547    rc = sqlite3_reset(pNextIdx);
111548  }
111549
111550  if( rc==SQLITE_OK ){
111551    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
111552    ** full, merge all segments in level iLevel into a single iLevel+1
111553    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
111554    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
111555    */
111556    if( iNext>=FTS3_MERGE_COUNT ){
111557      rc = fts3SegmentMerge(p, iLevel);
111558      *piIdx = 0;
111559    }else{
111560      *piIdx = iNext;
111561    }
111562  }
111563
111564  return rc;
111565}
111566
111567/*
111568** Move the iterator passed as the first argument to the next term in the
111569** segment. If successful, SQLITE_OK is returned. If there is no next term,
111570** SQLITE_DONE. Otherwise, an SQLite error code.
111571*/
111572static int fts3SegReaderNext(Fts3SegReader *pReader){
111573  char *pNext;                    /* Cursor variable */
111574  int nPrefix;                    /* Number of bytes in term prefix */
111575  int nSuffix;                    /* Number of bytes in term suffix */
111576
111577  if( !pReader->aDoclist ){
111578    pNext = pReader->aNode;
111579  }else{
111580    pNext = &pReader->aDoclist[pReader->nDoclist];
111581  }
111582
111583  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
111584    int rc;
111585    if( fts3SegReaderIsPending(pReader) ){
111586      Fts3HashElem *pElem = *(pReader->ppNextElem);
111587      if( pElem==0 ){
111588        pReader->aNode = 0;
111589      }else{
111590        PendingList *pList = (PendingList *)fts3HashData(pElem);
111591        pReader->zTerm = (char *)fts3HashKey(pElem);
111592        pReader->nTerm = fts3HashKeysize(pElem);
111593        pReader->nNode = pReader->nDoclist = pList->nData + 1;
111594        pReader->aNode = pReader->aDoclist = pList->aData;
111595        pReader->ppNextElem++;
111596        assert( pReader->aNode );
111597      }
111598      return SQLITE_OK;
111599    }
111600    if( !pReader->pStmt ){
111601      pReader->aNode = 0;
111602      return SQLITE_OK;
111603    }
111604    rc = sqlite3_step(pReader->pStmt);
111605    if( rc!=SQLITE_ROW ){
111606      pReader->aNode = 0;
111607      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
111608    }
111609    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
111610    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
111611    pNext = pReader->aNode;
111612  }
111613
111614  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
111615  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
111616
111617  if( nPrefix+nSuffix>pReader->nTermAlloc ){
111618    int nNew = (nPrefix+nSuffix)*2;
111619    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
111620    if( !zNew ){
111621      return SQLITE_NOMEM;
111622    }
111623    pReader->zTerm = zNew;
111624    pReader->nTermAlloc = nNew;
111625  }
111626  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
111627  pReader->nTerm = nPrefix+nSuffix;
111628  pNext += nSuffix;
111629  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
111630  assert( pNext<&pReader->aNode[pReader->nNode] );
111631  pReader->aDoclist = pNext;
111632  pReader->pOffsetList = 0;
111633  return SQLITE_OK;
111634}
111635
111636/*
111637** Set the SegReader to point to the first docid in the doclist associated
111638** with the current term.
111639*/
111640static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
111641  int n;
111642  assert( pReader->aDoclist );
111643  assert( !pReader->pOffsetList );
111644  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
111645  pReader->pOffsetList = &pReader->aDoclist[n];
111646}
111647
111648/*
111649** Advance the SegReader to point to the next docid in the doclist
111650** associated with the current term.
111651**
111652** If arguments ppOffsetList and pnOffsetList are not NULL, then
111653** *ppOffsetList is set to point to the first column-offset list
111654** in the doclist entry (i.e. immediately past the docid varint).
111655** *pnOffsetList is set to the length of the set of column-offset
111656** lists, not including the nul-terminator byte. For example:
111657*/
111658static void fts3SegReaderNextDocid(
111659  Fts3SegReader *pReader,
111660  char **ppOffsetList,
111661  int *pnOffsetList
111662){
111663  char *p = pReader->pOffsetList;
111664  char c = 0;
111665
111666  /* Pointer p currently points at the first byte of an offset list. The
111667  ** following two lines advance it to point one byte past the end of
111668  ** the same offset list.
111669  */
111670  while( *p | c ) c = *p++ & 0x80;
111671  p++;
111672
111673  /* If required, populate the output variables with a pointer to and the
111674  ** size of the previous offset-list.
111675  */
111676  if( ppOffsetList ){
111677    *ppOffsetList = pReader->pOffsetList;
111678    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
111679  }
111680
111681  /* If there are no more entries in the doclist, set pOffsetList to
111682  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
111683  ** Fts3SegReader.pOffsetList to point to the next offset list before
111684  ** returning.
111685  */
111686  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
111687    pReader->pOffsetList = 0;
111688  }else{
111689    sqlite3_int64 iDelta;
111690    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
111691    pReader->iDocid += iDelta;
111692  }
111693}
111694
111695/*
111696** Free all allocations associated with the iterator passed as the
111697** second argument.
111698*/
111699SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
111700  if( pReader ){
111701    if( pReader->pStmt ){
111702      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
111703      ** so that it can be reused when required by another query.
111704      */
111705      assert( p->nLeavesStmt<p->nLeavesTotal );
111706      sqlite3_reset(pReader->pStmt);
111707      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
111708    }
111709    if( !fts3SegReaderIsPending(pReader) ){
111710      sqlite3_free(pReader->zTerm);
111711    }
111712    sqlite3_free(pReader);
111713  }
111714}
111715
111716/*
111717** Allocate a new SegReader object.
111718*/
111719SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
111720  Fts3Table *p,                   /* Virtual table handle */
111721  int iAge,                       /* Segment "age". */
111722  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
111723  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
111724  sqlite3_int64 iEndBlock,        /* Final block of segment */
111725  const char *zRoot,              /* Buffer containing root node */
111726  int nRoot,                      /* Size of buffer containing root node */
111727  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
111728){
111729  int rc = SQLITE_OK;             /* Return code */
111730  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
111731  int nExtra = 0;                 /* Bytes to allocate segment root node */
111732
111733  if( iStartLeaf==0 ){
111734    nExtra = nRoot;
111735  }
111736
111737  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
111738  if( !pReader ){
111739    return SQLITE_NOMEM;
111740  }
111741  memset(pReader, 0, sizeof(Fts3SegReader));
111742  pReader->iStartBlock = iStartLeaf;
111743  pReader->iIdx = iAge;
111744  pReader->iEndBlock = iEndBlock;
111745
111746  if( nExtra ){
111747    /* The entire segment is stored in the root node. */
111748    pReader->aNode = (char *)&pReader[1];
111749    pReader->nNode = nRoot;
111750    memcpy(pReader->aNode, zRoot, nRoot);
111751  }else{
111752    /* If the text of the SQL statement to iterate through a contiguous
111753    ** set of entries in the %_segments table has not yet been composed,
111754    ** compose it now.
111755    */
111756    if( !p->zSelectLeaves ){
111757      p->zSelectLeaves = sqlite3_mprintf(
111758          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
111759          "ORDER BY blockid", p->zDb, p->zName
111760      );
111761      if( !p->zSelectLeaves ){
111762        rc = SQLITE_NOMEM;
111763        goto finished;
111764      }
111765    }
111766
111767    /* If there are no free statements in the aLeavesStmt[] array, prepare
111768    ** a new statement now. Otherwise, reuse a prepared statement from
111769    ** aLeavesStmt[].
111770    */
111771    if( p->nLeavesStmt==0 ){
111772      if( p->nLeavesTotal==p->nLeavesAlloc ){
111773        int nNew = p->nLeavesAlloc + 16;
111774        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
111775            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
111776        );
111777        if( !aNew ){
111778          rc = SQLITE_NOMEM;
111779          goto finished;
111780        }
111781        p->nLeavesAlloc = nNew;
111782        p->aLeavesStmt = aNew;
111783      }
111784      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
111785      if( rc!=SQLITE_OK ){
111786        goto finished;
111787      }
111788      p->nLeavesTotal++;
111789    }else{
111790      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
111791    }
111792
111793    /* Bind the start and end leaf blockids to the prepared SQL statement. */
111794    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
111795    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
111796  }
111797  rc = fts3SegReaderNext(pReader);
111798
111799 finished:
111800  if( rc==SQLITE_OK ){
111801    *ppReader = pReader;
111802  }else{
111803    sqlite3Fts3SegReaderFree(p, pReader);
111804  }
111805  return rc;
111806}
111807
111808/*
111809** This is a comparison function used as a qsort() callback when sorting
111810** an array of pending terms by term. This occurs as part of flushing
111811** the contents of the pending-terms hash table to the database.
111812*/
111813static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
111814  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
111815  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
111816  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
111817  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
111818
111819  int n = (n1<n2 ? n1 : n2);
111820  int c = memcmp(z1, z2, n);
111821  if( c==0 ){
111822    c = n1 - n2;
111823  }
111824  return c;
111825}
111826
111827/*
111828** This function is used to allocate an Fts3SegReader that iterates through
111829** a subset of the terms stored in the Fts3Table.pendingTerms array.
111830*/
111831SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
111832  Fts3Table *p,                   /* Virtual table handle */
111833  const char *zTerm,              /* Term to search for */
111834  int nTerm,                      /* Size of buffer zTerm */
111835  int isPrefix,                   /* True for a term-prefix query */
111836  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
111837){
111838  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
111839  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
111840  int nElem = 0;                  /* Size of array at aElem */
111841  int rc = SQLITE_OK;             /* Return Code */
111842
111843  if( isPrefix ){
111844    int nAlloc = 0;               /* Size of allocated array at aElem */
111845    Fts3HashElem *pE = 0;         /* Iterator variable */
111846
111847    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
111848      char *zKey = (char *)fts3HashKey(pE);
111849      int nKey = fts3HashKeysize(pE);
111850      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
111851        if( nElem==nAlloc ){
111852          Fts3HashElem **aElem2;
111853          nAlloc += 16;
111854          aElem2 = (Fts3HashElem **)sqlite3_realloc(
111855              aElem, nAlloc*sizeof(Fts3HashElem *)
111856          );
111857          if( !aElem2 ){
111858            rc = SQLITE_NOMEM;
111859            nElem = 0;
111860            break;
111861          }
111862          aElem = aElem2;
111863        }
111864        aElem[nElem++] = pE;
111865      }
111866    }
111867
111868    /* If more than one term matches the prefix, sort the Fts3HashElem
111869    ** objects in term order using qsort(). This uses the same comparison
111870    ** callback as is used when flushing terms to disk.
111871    */
111872    if( nElem>1 ){
111873      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
111874    }
111875
111876  }else{
111877    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
111878    if( pE ){
111879      aElem = &pE;
111880      nElem = 1;
111881    }
111882  }
111883
111884  if( nElem>0 ){
111885    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
111886    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
111887    if( !pReader ){
111888      rc = SQLITE_NOMEM;
111889    }else{
111890      memset(pReader, 0, nByte);
111891      pReader->iIdx = 0x7FFFFFFF;
111892      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
111893      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
111894      fts3SegReaderNext(pReader);
111895    }
111896  }
111897
111898  if( isPrefix ){
111899    sqlite3_free(aElem);
111900  }
111901  *ppReader = pReader;
111902  return rc;
111903}
111904
111905
111906/*
111907** The second argument to this function is expected to be a statement of
111908** the form:
111909**
111910**   SELECT
111911**     idx,                  -- col 0
111912**     start_block,          -- col 1
111913**     leaves_end_block,     -- col 2
111914**     end_block,            -- col 3
111915**     root                  -- col 4
111916**   FROM %_segdir ...
111917**
111918** This function allocates and initializes a Fts3SegReader structure to
111919** iterate through the terms stored in the segment identified by the
111920** current row that pStmt is pointing to.
111921**
111922** If successful, the Fts3SegReader is left pointing to the first term
111923** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
111924** code is returned.
111925*/
111926static int fts3SegReaderNew(
111927  Fts3Table *p,                   /* Virtual table handle */
111928  sqlite3_stmt *pStmt,            /* See above */
111929  int iAge,                       /* Segment "age". */
111930  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
111931){
111932  return sqlite3Fts3SegReaderNew(p, iAge,
111933      sqlite3_column_int64(pStmt, 1),
111934      sqlite3_column_int64(pStmt, 2),
111935      sqlite3_column_int64(pStmt, 3),
111936      sqlite3_column_blob(pStmt, 4),
111937      sqlite3_column_bytes(pStmt, 4),
111938      ppReader
111939  );
111940}
111941
111942/*
111943** Compare the entries pointed to by two Fts3SegReader structures.
111944** Comparison is as follows:
111945**
111946**   1) EOF is greater than not EOF.
111947**
111948**   2) The current terms (if any) are compared using memcmp(). If one
111949**      term is a prefix of another, the longer term is considered the
111950**      larger.
111951**
111952**   3) By segment age. An older segment is considered larger.
111953*/
111954static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
111955  int rc;
111956  if( pLhs->aNode && pRhs->aNode ){
111957    int rc2 = pLhs->nTerm - pRhs->nTerm;
111958    if( rc2<0 ){
111959      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
111960    }else{
111961      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
111962    }
111963    if( rc==0 ){
111964      rc = rc2;
111965    }
111966  }else{
111967    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
111968  }
111969  if( rc==0 ){
111970    rc = pRhs->iIdx - pLhs->iIdx;
111971  }
111972  assert( rc!=0 );
111973  return rc;
111974}
111975
111976/*
111977** A different comparison function for SegReader structures. In this
111978** version, it is assumed that each SegReader points to an entry in
111979** a doclist for identical terms. Comparison is made as follows:
111980**
111981**   1) EOF (end of doclist in this case) is greater than not EOF.
111982**
111983**   2) By current docid.
111984**
111985**   3) By segment age. An older segment is considered larger.
111986*/
111987static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
111988  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
111989  if( rc==0 ){
111990    if( pLhs->iDocid==pRhs->iDocid ){
111991      rc = pRhs->iIdx - pLhs->iIdx;
111992    }else{
111993      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
111994    }
111995  }
111996  assert( pLhs->aNode && pRhs->aNode );
111997  return rc;
111998}
111999
112000/*
112001** Compare the term that the Fts3SegReader object passed as the first argument
112002** points to with the term specified by arguments zTerm and nTerm.
112003**
112004** If the pSeg iterator is already at EOF, return 0. Otherwise, return
112005** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
112006** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
112007*/
112008static int fts3SegReaderTermCmp(
112009  Fts3SegReader *pSeg,            /* Segment reader object */
112010  const char *zTerm,              /* Term to compare to */
112011  int nTerm                       /* Size of term zTerm in bytes */
112012){
112013  int res = 0;
112014  if( pSeg->aNode ){
112015    if( pSeg->nTerm>nTerm ){
112016      res = memcmp(pSeg->zTerm, zTerm, nTerm);
112017    }else{
112018      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
112019    }
112020    if( res==0 ){
112021      res = pSeg->nTerm-nTerm;
112022    }
112023  }
112024  return res;
112025}
112026
112027/*
112028** Argument apSegment is an array of nSegment elements. It is known that
112029** the final (nSegment-nSuspect) members are already in sorted order
112030** (according to the comparison function provided). This function shuffles
112031** the array around until all entries are in sorted order.
112032*/
112033static void fts3SegReaderSort(
112034  Fts3SegReader **apSegment,                     /* Array to sort entries of */
112035  int nSegment,                                  /* Size of apSegment array */
112036  int nSuspect,                                  /* Unsorted entry count */
112037  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
112038){
112039  int i;                          /* Iterator variable */
112040
112041  assert( nSuspect<=nSegment );
112042
112043  if( nSuspect==nSegment ) nSuspect--;
112044  for(i=nSuspect-1; i>=0; i--){
112045    int j;
112046    for(j=i; j<(nSegment-1); j++){
112047      Fts3SegReader *pTmp;
112048      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
112049      pTmp = apSegment[j+1];
112050      apSegment[j+1] = apSegment[j];
112051      apSegment[j] = pTmp;
112052    }
112053  }
112054
112055#ifndef NDEBUG
112056  /* Check that the list really is sorted now. */
112057  for(i=0; i<(nSuspect-1); i++){
112058    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
112059  }
112060#endif
112061}
112062
112063/*
112064** Insert a record into the %_segments table.
112065*/
112066static int fts3WriteSegment(
112067  Fts3Table *p,                   /* Virtual table handle */
112068  sqlite3_int64 iBlock,           /* Block id for new block */
112069  char *z,                        /* Pointer to buffer containing block data */
112070  int n                           /* Size of buffer z in bytes */
112071){
112072  sqlite3_stmt *pStmt;
112073  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
112074  if( rc==SQLITE_OK ){
112075    sqlite3_bind_int64(pStmt, 1, iBlock);
112076    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
112077    sqlite3_step(pStmt);
112078    rc = sqlite3_reset(pStmt);
112079  }
112080  return rc;
112081}
112082
112083/*
112084** Insert a record into the %_segdir table.
112085*/
112086static int fts3WriteSegdir(
112087  Fts3Table *p,                   /* Virtual table handle */
112088  int iLevel,                     /* Value for "level" field */
112089  int iIdx,                       /* Value for "idx" field */
112090  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
112091  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
112092  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
112093  char *zRoot,                    /* Blob value for "root" field */
112094  int nRoot                       /* Number of bytes in buffer zRoot */
112095){
112096  sqlite3_stmt *pStmt;
112097  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
112098  if( rc==SQLITE_OK ){
112099    sqlite3_bind_int(pStmt, 1, iLevel);
112100    sqlite3_bind_int(pStmt, 2, iIdx);
112101    sqlite3_bind_int64(pStmt, 3, iStartBlock);
112102    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
112103    sqlite3_bind_int64(pStmt, 5, iEndBlock);
112104    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
112105    sqlite3_step(pStmt);
112106    rc = sqlite3_reset(pStmt);
112107  }
112108  return rc;
112109}
112110
112111/*
112112** Return the size of the common prefix (if any) shared by zPrev and
112113** zNext, in bytes. For example,
112114**
112115**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
112116**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
112117**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
112118*/
112119static int fts3PrefixCompress(
112120  const char *zPrev,              /* Buffer containing previous term */
112121  int nPrev,                      /* Size of buffer zPrev in bytes */
112122  const char *zNext,              /* Buffer containing next term */
112123  int nNext                       /* Size of buffer zNext in bytes */
112124){
112125  int n;
112126  UNUSED_PARAMETER(nNext);
112127  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
112128  return n;
112129}
112130
112131/*
112132** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
112133** (according to memcmp) than the previous term.
112134*/
112135static int fts3NodeAddTerm(
112136  Fts3Table *p,               /* Virtual table handle */
112137  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
112138  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
112139  const char *zTerm,              /* Pointer to buffer containing term */
112140  int nTerm                       /* Size of term in bytes */
112141){
112142  SegmentNode *pTree = *ppTree;
112143  int rc;
112144  SegmentNode *pNew;
112145
112146  /* First try to append the term to the current node. Return early if
112147  ** this is possible.
112148  */
112149  if( pTree ){
112150    int nData = pTree->nData;     /* Current size of node in bytes */
112151    int nReq = nData;             /* Required space after adding zTerm */
112152    int nPrefix;                  /* Number of bytes of prefix compression */
112153    int nSuffix;                  /* Suffix length */
112154
112155    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
112156    nSuffix = nTerm-nPrefix;
112157
112158    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
112159    if( nReq<=p->nNodeSize || !pTree->zTerm ){
112160
112161      if( nReq>p->nNodeSize ){
112162        /* An unusual case: this is the first term to be added to the node
112163        ** and the static node buffer (p->nNodeSize bytes) is not large
112164        ** enough. Use a separately malloced buffer instead This wastes
112165        ** p->nNodeSize bytes, but since this scenario only comes about when
112166        ** the database contain two terms that share a prefix of almost 2KB,
112167        ** this is not expected to be a serious problem.
112168        */
112169        assert( pTree->aData==(char *)&pTree[1] );
112170        pTree->aData = (char *)sqlite3_malloc(nReq);
112171        if( !pTree->aData ){
112172          return SQLITE_NOMEM;
112173        }
112174      }
112175
112176      if( pTree->zTerm ){
112177        /* There is no prefix-length field for first term in a node */
112178        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
112179      }
112180
112181      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
112182      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
112183      pTree->nData = nData + nSuffix;
112184      pTree->nEntry++;
112185
112186      if( isCopyTerm ){
112187        if( pTree->nMalloc<nTerm ){
112188          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
112189          if( !zNew ){
112190            return SQLITE_NOMEM;
112191          }
112192          pTree->nMalloc = nTerm*2;
112193          pTree->zMalloc = zNew;
112194        }
112195        pTree->zTerm = pTree->zMalloc;
112196        memcpy(pTree->zTerm, zTerm, nTerm);
112197        pTree->nTerm = nTerm;
112198      }else{
112199        pTree->zTerm = (char *)zTerm;
112200        pTree->nTerm = nTerm;
112201      }
112202      return SQLITE_OK;
112203    }
112204  }
112205
112206  /* If control flows to here, it was not possible to append zTerm to the
112207  ** current node. Create a new node (a right-sibling of the current node).
112208  ** If this is the first node in the tree, the term is added to it.
112209  **
112210  ** Otherwise, the term is not added to the new node, it is left empty for
112211  ** now. Instead, the term is inserted into the parent of pTree. If pTree
112212  ** has no parent, one is created here.
112213  */
112214  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
112215  if( !pNew ){
112216    return SQLITE_NOMEM;
112217  }
112218  memset(pNew, 0, sizeof(SegmentNode));
112219  pNew->nData = 1 + FTS3_VARINT_MAX;
112220  pNew->aData = (char *)&pNew[1];
112221
112222  if( pTree ){
112223    SegmentNode *pParent = pTree->pParent;
112224    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
112225    if( pTree->pParent==0 ){
112226      pTree->pParent = pParent;
112227    }
112228    pTree->pRight = pNew;
112229    pNew->pLeftmost = pTree->pLeftmost;
112230    pNew->pParent = pParent;
112231    pNew->zMalloc = pTree->zMalloc;
112232    pNew->nMalloc = pTree->nMalloc;
112233    pTree->zMalloc = 0;
112234  }else{
112235    pNew->pLeftmost = pNew;
112236    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
112237  }
112238
112239  *ppTree = pNew;
112240  return rc;
112241}
112242
112243/*
112244** Helper function for fts3NodeWrite().
112245*/
112246static int fts3TreeFinishNode(
112247  SegmentNode *pTree,
112248  int iHeight,
112249  sqlite3_int64 iLeftChild
112250){
112251  int nStart;
112252  assert( iHeight>=1 && iHeight<128 );
112253  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
112254  pTree->aData[nStart] = (char)iHeight;
112255  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
112256  return nStart;
112257}
112258
112259/*
112260** Write the buffer for the segment node pTree and all of its peers to the
112261** database. Then call this function recursively to write the parent of
112262** pTree and its peers to the database.
112263**
112264** Except, if pTree is a root node, do not write it to the database. Instead,
112265** set output variables *paRoot and *pnRoot to contain the root node.
112266**
112267** If successful, SQLITE_OK is returned and output variable *piLast is
112268** set to the largest blockid written to the database (or zero if no
112269** blocks were written to the db). Otherwise, an SQLite error code is
112270** returned.
112271*/
112272static int fts3NodeWrite(
112273  Fts3Table *p,                   /* Virtual table handle */
112274  SegmentNode *pTree,             /* SegmentNode handle */
112275  int iHeight,                    /* Height of this node in tree */
112276  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
112277  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
112278  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
112279  char **paRoot,                  /* OUT: Data for root node */
112280  int *pnRoot                     /* OUT: Size of root node in bytes */
112281){
112282  int rc = SQLITE_OK;
112283
112284  if( !pTree->pParent ){
112285    /* Root node of the tree. */
112286    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
112287    *piLast = iFree-1;
112288    *pnRoot = pTree->nData - nStart;
112289    *paRoot = &pTree->aData[nStart];
112290  }else{
112291    SegmentNode *pIter;
112292    sqlite3_int64 iNextFree = iFree;
112293    sqlite3_int64 iNextLeaf = iLeaf;
112294    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
112295      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
112296      int nWrite = pIter->nData - nStart;
112297
112298      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
112299      iNextFree++;
112300      iNextLeaf += (pIter->nEntry+1);
112301    }
112302    if( rc==SQLITE_OK ){
112303      assert( iNextLeaf==iFree );
112304      rc = fts3NodeWrite(
112305          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
112306      );
112307    }
112308  }
112309
112310  return rc;
112311}
112312
112313/*
112314** Free all memory allocations associated with the tree pTree.
112315*/
112316static void fts3NodeFree(SegmentNode *pTree){
112317  if( pTree ){
112318    SegmentNode *p = pTree->pLeftmost;
112319    fts3NodeFree(p->pParent);
112320    while( p ){
112321      SegmentNode *pRight = p->pRight;
112322      if( p->aData!=(char *)&p[1] ){
112323        sqlite3_free(p->aData);
112324      }
112325      assert( pRight==0 || p->zMalloc==0 );
112326      sqlite3_free(p->zMalloc);
112327      sqlite3_free(p);
112328      p = pRight;
112329    }
112330  }
112331}
112332
112333/*
112334** Add a term to the segment being constructed by the SegmentWriter object
112335** *ppWriter. When adding the first term to a segment, *ppWriter should
112336** be passed NULL. This function will allocate a new SegmentWriter object
112337** and return it via the input/output variable *ppWriter in this case.
112338**
112339** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
112340*/
112341static int fts3SegWriterAdd(
112342  Fts3Table *p,                   /* Virtual table handle */
112343  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
112344  int isCopyTerm,                 /* True if buffer zTerm must be copied */
112345  const char *zTerm,              /* Pointer to buffer containing term */
112346  int nTerm,                      /* Size of term in bytes */
112347  const char *aDoclist,           /* Pointer to buffer containing doclist */
112348  int nDoclist                    /* Size of doclist in bytes */
112349){
112350  int nPrefix;                    /* Size of term prefix in bytes */
112351  int nSuffix;                    /* Size of term suffix in bytes */
112352  int nReq;                       /* Number of bytes required on leaf page */
112353  int nData;
112354  SegmentWriter *pWriter = *ppWriter;
112355
112356  if( !pWriter ){
112357    int rc;
112358    sqlite3_stmt *pStmt;
112359
112360    /* Allocate the SegmentWriter structure */
112361    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
112362    if( !pWriter ) return SQLITE_NOMEM;
112363    memset(pWriter, 0, sizeof(SegmentWriter));
112364    *ppWriter = pWriter;
112365
112366    /* Allocate a buffer in which to accumulate data */
112367    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
112368    if( !pWriter->aData ) return SQLITE_NOMEM;
112369    pWriter->nSize = p->nNodeSize;
112370
112371    /* Find the next free blockid in the %_segments table */
112372    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
112373    if( rc!=SQLITE_OK ) return rc;
112374    if( SQLITE_ROW==sqlite3_step(pStmt) ){
112375      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
112376      pWriter->iFirst = pWriter->iFree;
112377    }
112378    rc = sqlite3_reset(pStmt);
112379    if( rc!=SQLITE_OK ) return rc;
112380  }
112381  nData = pWriter->nData;
112382
112383  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
112384  nSuffix = nTerm-nPrefix;
112385
112386  /* Figure out how many bytes are required by this new entry */
112387  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
112388    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
112389    nSuffix +                               /* Term suffix */
112390    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
112391    nDoclist;                               /* Doclist data */
112392
112393  if( nData>0 && nData+nReq>p->nNodeSize ){
112394    int rc;
112395
112396    /* The current leaf node is full. Write it out to the database. */
112397    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
112398    if( rc!=SQLITE_OK ) return rc;
112399
112400    /* Add the current term to the interior node tree. The term added to
112401    ** the interior tree must:
112402    **
112403    **   a) be greater than the largest term on the leaf node just written
112404    **      to the database (still available in pWriter->zTerm), and
112405    **
112406    **   b) be less than or equal to the term about to be added to the new
112407    **      leaf node (zTerm/nTerm).
112408    **
112409    ** In other words, it must be the prefix of zTerm 1 byte longer than
112410    ** the common prefix (if any) of zTerm and pWriter->zTerm.
112411    */
112412    assert( nPrefix<nTerm );
112413    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
112414    if( rc!=SQLITE_OK ) return rc;
112415
112416    nData = 0;
112417    pWriter->nTerm = 0;
112418
112419    nPrefix = 0;
112420    nSuffix = nTerm;
112421    nReq = 1 +                              /* varint containing prefix size */
112422      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
112423      nTerm +                               /* Term suffix */
112424      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
112425      nDoclist;                             /* Doclist data */
112426  }
112427
112428  /* If the buffer currently allocated is too small for this entry, realloc
112429  ** the buffer to make it large enough.
112430  */
112431  if( nReq>pWriter->nSize ){
112432    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
112433    if( !aNew ) return SQLITE_NOMEM;
112434    pWriter->aData = aNew;
112435    pWriter->nSize = nReq;
112436  }
112437  assert( nData+nReq<=pWriter->nSize );
112438
112439  /* Append the prefix-compressed term and doclist to the buffer. */
112440  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
112441  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
112442  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
112443  nData += nSuffix;
112444  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
112445  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
112446  pWriter->nData = nData + nDoclist;
112447
112448  /* Save the current term so that it can be used to prefix-compress the next.
112449  ** If the isCopyTerm parameter is true, then the buffer pointed to by
112450  ** zTerm is transient, so take a copy of the term data. Otherwise, just
112451  ** store a copy of the pointer.
112452  */
112453  if( isCopyTerm ){
112454    if( nTerm>pWriter->nMalloc ){
112455      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
112456      if( !zNew ){
112457        return SQLITE_NOMEM;
112458      }
112459      pWriter->nMalloc = nTerm*2;
112460      pWriter->zMalloc = zNew;
112461      pWriter->zTerm = zNew;
112462    }
112463    assert( pWriter->zTerm==pWriter->zMalloc );
112464    memcpy(pWriter->zTerm, zTerm, nTerm);
112465  }else{
112466    pWriter->zTerm = (char *)zTerm;
112467  }
112468  pWriter->nTerm = nTerm;
112469
112470  return SQLITE_OK;
112471}
112472
112473/*
112474** Flush all data associated with the SegmentWriter object pWriter to the
112475** database. This function must be called after all terms have been added
112476** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
112477** returned. Otherwise, an SQLite error code.
112478*/
112479static int fts3SegWriterFlush(
112480  Fts3Table *p,                   /* Virtual table handle */
112481  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
112482  int iLevel,                     /* Value for 'level' column of %_segdir */
112483  int iIdx                        /* Value for 'idx' column of %_segdir */
112484){
112485  int rc;                         /* Return code */
112486  if( pWriter->pTree ){
112487    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
112488    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
112489    char *zRoot = NULL;           /* Pointer to buffer containing root node */
112490    int nRoot = 0;                /* Size of buffer zRoot */
112491
112492    iLastLeaf = pWriter->iFree;
112493    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
112494    if( rc==SQLITE_OK ){
112495      rc = fts3NodeWrite(p, pWriter->pTree, 1,
112496          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
112497    }
112498    if( rc==SQLITE_OK ){
112499      rc = fts3WriteSegdir(
112500          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
112501    }
112502  }else{
112503    /* The entire tree fits on the root node. Write it to the segdir table. */
112504    rc = fts3WriteSegdir(
112505        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
112506  }
112507  return rc;
112508}
112509
112510/*
112511** Release all memory held by the SegmentWriter object passed as the
112512** first argument.
112513*/
112514static void fts3SegWriterFree(SegmentWriter *pWriter){
112515  if( pWriter ){
112516    sqlite3_free(pWriter->aData);
112517    sqlite3_free(pWriter->zMalloc);
112518    fts3NodeFree(pWriter->pTree);
112519    sqlite3_free(pWriter);
112520  }
112521}
112522
112523/*
112524** The first value in the apVal[] array is assumed to contain an integer.
112525** This function tests if there exist any documents with docid values that
112526** are different from that integer. i.e. if deleting the document with docid
112527** apVal[0] would mean the FTS3 table were empty.
112528**
112529** If successful, *pisEmpty is set to true if the table is empty except for
112530** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
112531** error occurs, an SQLite error code is returned.
112532*/
112533static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
112534  sqlite3_stmt *pStmt;
112535  int rc;
112536  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
112537  if( rc==SQLITE_OK ){
112538    if( SQLITE_ROW==sqlite3_step(pStmt) ){
112539      *pisEmpty = sqlite3_column_int(pStmt, 0);
112540    }
112541    rc = sqlite3_reset(pStmt);
112542  }
112543  return rc;
112544}
112545
112546/*
112547** Set *pnSegment to the number of segments of level iLevel in the database.
112548**
112549** Return SQLITE_OK if successful, or an SQLite error code if not.
112550*/
112551static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
112552  sqlite3_stmt *pStmt;
112553  int rc;
112554
112555  assert( iLevel>=0 );
112556  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
112557  if( rc!=SQLITE_OK ) return rc;
112558  sqlite3_bind_int(pStmt, 1, iLevel);
112559  if( SQLITE_ROW==sqlite3_step(pStmt) ){
112560    *pnSegment = sqlite3_column_int(pStmt, 0);
112561  }
112562  return sqlite3_reset(pStmt);
112563}
112564
112565/*
112566** Set *pnSegment to the total number of segments in the database. Set
112567** *pnMax to the largest segment level in the database (segment levels
112568** are stored in the 'level' column of the %_segdir table).
112569**
112570** Return SQLITE_OK if successful, or an SQLite error code if not.
112571*/
112572static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
112573  sqlite3_stmt *pStmt;
112574  int rc;
112575
112576  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
112577  if( rc!=SQLITE_OK ) return rc;
112578  if( SQLITE_ROW==sqlite3_step(pStmt) ){
112579    *pnSegment = sqlite3_column_int(pStmt, 0);
112580    *pnMax = sqlite3_column_int(pStmt, 1);
112581  }
112582  return sqlite3_reset(pStmt);
112583}
112584
112585/*
112586** This function is used after merging multiple segments into a single large
112587** segment to delete the old, now redundant, segment b-trees. Specifically,
112588** it:
112589**
112590**   1) Deletes all %_segments entries for the segments associated with
112591**      each of the SegReader objects in the array passed as the third
112592**      argument, and
112593**
112594**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
112595**      entries regardless of level if (iLevel<0).
112596**
112597** SQLITE_OK is returned if successful, otherwise an SQLite error code.
112598*/
112599static int fts3DeleteSegdir(
112600  Fts3Table *p,                   /* Virtual table handle */
112601  int iLevel,                     /* Level of %_segdir entries to delete */
112602  Fts3SegReader **apSegment,      /* Array of SegReader objects */
112603  int nReader                     /* Size of array apSegment */
112604){
112605  int rc;                         /* Return Code */
112606  int i;                          /* Iterator variable */
112607  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
112608
112609  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
112610  for(i=0; rc==SQLITE_OK && i<nReader; i++){
112611    Fts3SegReader *pSegment = apSegment[i];
112612    if( pSegment->iStartBlock ){
112613      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
112614      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
112615      sqlite3_step(pDelete);
112616      rc = sqlite3_reset(pDelete);
112617    }
112618  }
112619  if( rc!=SQLITE_OK ){
112620    return rc;
112621  }
112622
112623  if( iLevel>=0 ){
112624    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
112625    if( rc==SQLITE_OK ){
112626      sqlite3_bind_int(pDelete, 1, iLevel);
112627      sqlite3_step(pDelete);
112628      rc = sqlite3_reset(pDelete);
112629    }
112630  }else{
112631    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
112632  }
112633
112634  return rc;
112635}
112636
112637/*
112638** When this function is called, buffer *ppList (size *pnList bytes) contains
112639** a position list that may (or may not) feature multiple columns. This
112640** function adjusts the pointer *ppList and the length *pnList so that they
112641** identify the subset of the position list that corresponds to column iCol.
112642**
112643** If there are no entries in the input position list for column iCol, then
112644** *pnList is set to zero before returning.
112645*/
112646static void fts3ColumnFilter(
112647  int iCol,                       /* Column to filter on */
112648  char **ppList,                  /* IN/OUT: Pointer to position list */
112649  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
112650){
112651  char *pList = *ppList;
112652  int nList = *pnList;
112653  char *pEnd = &pList[nList];
112654  int iCurrent = 0;
112655  char *p = pList;
112656
112657  assert( iCol>=0 );
112658  while( 1 ){
112659    char c = 0;
112660    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
112661
112662    if( iCol==iCurrent ){
112663      nList = (int)(p - pList);
112664      break;
112665    }
112666
112667    nList -= (int)(p - pList);
112668    pList = p;
112669    if( nList==0 ){
112670      break;
112671    }
112672    p = &pList[1];
112673    p += sqlite3Fts3GetVarint32(p, &iCurrent);
112674  }
112675
112676  *ppList = pList;
112677  *pnList = nList;
112678}
112679
112680/*
112681** sqlite3Fts3SegReaderIterate() callback used when merging multiple
112682** segments to create a single, larger segment.
112683*/
112684static int fts3MergeCallback(
112685  Fts3Table *p,                   /* FTS3 Virtual table handle */
112686  void *pContext,                 /* Pointer to SegmentWriter* to write with */
112687  char *zTerm,                    /* Term to write to the db */
112688  int nTerm,                      /* Number of bytes in zTerm */
112689  char *aDoclist,                 /* Doclist associated with zTerm */
112690  int nDoclist                    /* Number of bytes in doclist */
112691){
112692  SegmentWriter **ppW = (SegmentWriter **)pContext;
112693  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
112694}
112695
112696/*
112697** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
112698** of the pending-terms hash table to the database.
112699*/
112700static int fts3FlushCallback(
112701  Fts3Table *p,                   /* FTS3 Virtual table handle */
112702  void *pContext,                 /* Pointer to SegmentWriter* to write with */
112703  char *zTerm,                    /* Term to write to the db */
112704  int nTerm,                      /* Number of bytes in zTerm */
112705  char *aDoclist,                 /* Doclist associated with zTerm */
112706  int nDoclist                    /* Number of bytes in doclist */
112707){
112708  SegmentWriter **ppW = (SegmentWriter **)pContext;
112709  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
112710}
112711
112712/*
112713** This function is used to iterate through a contiguous set of terms
112714** stored in the full-text index. It merges data contained in one or
112715** more segments to support this.
112716**
112717** The second argument is passed an array of pointers to SegReader objects
112718** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
112719** of terms selected by each SegReader. If a single term is present in
112720** more than one segment, the associated doclists are merged. For each
112721** term and (possibly merged) doclist in the merged range, the callback
112722** function xFunc is invoked with its arguments set as follows.
112723**
112724**   arg 0: Copy of 'p' parameter passed to this function
112725**   arg 1: Copy of 'pContext' parameter passed to this function
112726**   arg 2: Pointer to buffer containing term
112727**   arg 3: Size of arg 2 buffer in bytes
112728**   arg 4: Pointer to buffer containing doclist
112729**   arg 5: Size of arg 2 buffer in bytes
112730**
112731** The 4th argument to this function is a pointer to a structure of type
112732** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
112733** further restrict the range of terms that callbacks are made for and
112734** modify the behaviour of this function. See comments above structure
112735** definition for details.
112736*/
112737SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
112738  Fts3Table *p,                   /* Virtual table handle */
112739  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
112740  int nSegment,                   /* Size of apSegment array */
112741  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
112742  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
112743  void *pContext                  /* Callback context (2nd argument) */
112744){
112745  int i;                          /* Iterator variable */
112746  char *aBuffer = 0;              /* Buffer to merge doclists in */
112747  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
112748  int rc = SQLITE_OK;             /* Return code */
112749
112750  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
112751  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
112752  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
112753  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
112754
112755  /* If there are zero segments, this function is a no-op. This scenario
112756  ** comes about only when reading from an empty database.
112757  */
112758  if( nSegment==0 ) goto finished;
112759
112760  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
112761  ** for, then advance each segment iterator until it points to a term of
112762  ** equal or greater value than the specified term. This prevents many
112763  ** unnecessary merge/sort operations for the case where single segment
112764  ** b-tree leaf nodes contain more than one term.
112765  */
112766  if( pFilter->zTerm ){
112767    int nTerm = pFilter->nTerm;
112768    const char *zTerm = pFilter->zTerm;
112769    for(i=0; i<nSegment; i++){
112770      Fts3SegReader *pSeg = apSegment[i];
112771      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
112772        rc = fts3SegReaderNext(pSeg);
112773        if( rc!=SQLITE_OK ) goto finished; }
112774    }
112775  }
112776
112777  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
112778  while( apSegment[0]->aNode ){
112779    int nTerm = apSegment[0]->nTerm;
112780    char *zTerm = apSegment[0]->zTerm;
112781    int nMerge = 1;
112782
112783    /* If this is a prefix-search, and if the term that apSegment[0] points
112784    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
112785    ** required callbacks have been made. In this case exit early.
112786    **
112787    ** Similarly, if this is a search for an exact match, and the first term
112788    ** of segment apSegment[0] is not a match, exit early.
112789    */
112790    if( pFilter->zTerm ){
112791      if( nTerm<pFilter->nTerm
112792       || (!isPrefix && nTerm>pFilter->nTerm)
112793       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
112794    ){
112795        goto finished;
112796      }
112797    }
112798
112799    while( nMerge<nSegment
112800        && apSegment[nMerge]->aNode
112801        && apSegment[nMerge]->nTerm==nTerm
112802        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
112803    ){
112804      nMerge++;
112805    }
112806
112807    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
112808    if( nMerge==1 && !isIgnoreEmpty ){
112809      Fts3SegReader *p0 = apSegment[0];
112810      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
112811      if( rc!=SQLITE_OK ) goto finished;
112812    }else{
112813      int nDoclist = 0;           /* Size of doclist */
112814      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
112815
112816      /* The current term of the first nMerge entries in the array
112817      ** of Fts3SegReader objects is the same. The doclists must be merged
112818      ** and a single term added to the new segment.
112819      */
112820      for(i=0; i<nMerge; i++){
112821        fts3SegReaderFirstDocid(apSegment[i]);
112822      }
112823      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
112824      while( apSegment[0]->pOffsetList ){
112825        int j;                    /* Number of segments that share a docid */
112826        char *pList;
112827        int nList;
112828        int nByte;
112829        sqlite3_int64 iDocid = apSegment[0]->iDocid;
112830        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
112831        j = 1;
112832        while( j<nMerge
112833            && apSegment[j]->pOffsetList
112834            && apSegment[j]->iDocid==iDocid
112835        ){
112836          fts3SegReaderNextDocid(apSegment[j], 0, 0);
112837          j++;
112838        }
112839
112840        if( isColFilter ){
112841          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
112842        }
112843
112844        if( !isIgnoreEmpty || nList>0 ){
112845          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
112846          if( nDoclist+nByte>nAlloc ){
112847            char *aNew;
112848            nAlloc = nDoclist+nByte*2;
112849            aNew = sqlite3_realloc(aBuffer, nAlloc);
112850            if( !aNew ){
112851              rc = SQLITE_NOMEM;
112852              goto finished;
112853            }
112854            aBuffer = aNew;
112855          }
112856          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
112857          iPrev = iDocid;
112858          if( isRequirePos ){
112859            memcpy(&aBuffer[nDoclist], pList, nList);
112860            nDoclist += nList;
112861            aBuffer[nDoclist++] = '\0';
112862          }
112863        }
112864
112865        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
112866      }
112867
112868      if( nDoclist>0 ){
112869        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
112870        if( rc!=SQLITE_OK ) goto finished;
112871      }
112872    }
112873
112874    /* If there is a term specified to filter on, and this is not a prefix
112875    ** search, return now. The callback that corresponds to the required
112876    ** term (if such a term exists in the index) has already been made.
112877    */
112878    if( pFilter->zTerm && !isPrefix ){
112879      goto finished;
112880    }
112881
112882    for(i=0; i<nMerge; i++){
112883      rc = fts3SegReaderNext(apSegment[i]);
112884      if( rc!=SQLITE_OK ) goto finished;
112885    }
112886    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
112887  }
112888
112889 finished:
112890  sqlite3_free(aBuffer);
112891  return rc;
112892}
112893
112894/*
112895** Merge all level iLevel segments in the database into a single
112896** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
112897** single segment with a level equal to the numerically largest level
112898** currently present in the database.
112899**
112900** If this function is called with iLevel<0, but there is only one
112901** segment in the database, SQLITE_DONE is returned immediately.
112902** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
112903** an SQLite error code is returned.
112904*/
112905static int fts3SegmentMerge(Fts3Table *p, int iLevel){
112906  int i;                          /* Iterator variable */
112907  int rc;                         /* Return code */
112908  int iIdx;                       /* Index of new segment */
112909  int iNewLevel;                  /* Level to create new segment at */
112910  sqlite3_stmt *pStmt = 0;
112911  SegmentWriter *pWriter = 0;
112912  int nSegment = 0;               /* Number of segments being merged */
112913  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
112914  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
112915  Fts3SegFilter filter;           /* Segment term filter condition */
112916
112917  if( iLevel<0 ){
112918    /* This call is to merge all segments in the database to a single
112919    ** segment. The level of the new segment is equal to the the numerically
112920    ** greatest segment level currently present in the database. The index
112921    ** of the new segment is always 0.
112922    */
112923    iIdx = 0;
112924    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
112925    if( rc!=SQLITE_OK ) goto finished;
112926    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
112927    if( rc!=SQLITE_OK ) goto finished;
112928    nSegment += (pPending!=0);
112929    if( nSegment<=1 ){
112930      return SQLITE_DONE;
112931    }
112932  }else{
112933    /* This call is to merge all segments at level iLevel. Find the next
112934    ** available segment index at level iLevel+1. The call to
112935    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
112936    ** a single iLevel+2 segment if necessary.
112937    */
112938    iNewLevel = iLevel+1;
112939    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
112940    if( rc!=SQLITE_OK ) goto finished;
112941    rc = fts3SegmentCount(p, iLevel, &nSegment);
112942    if( rc!=SQLITE_OK ) goto finished;
112943  }
112944  assert( nSegment>0 );
112945  assert( iNewLevel>=0 );
112946
112947  /* Allocate space for an array of pointers to segment iterators. */
112948  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
112949  if( !apSegment ){
112950    rc = SQLITE_NOMEM;
112951    goto finished;
112952  }
112953  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
112954
112955  /* Allocate a Fts3SegReader structure for each segment being merged. A
112956  ** Fts3SegReader stores the state data required to iterate through all
112957  ** entries on all leaves of a single segment.
112958  */
112959  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
112960  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
112961  if( rc!=SQLITE_OK ) goto finished;
112962  sqlite3_bind_int(pStmt, 1, iLevel);
112963  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
112964    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
112965    if( rc!=SQLITE_OK ){
112966      goto finished;
112967    }
112968  }
112969  rc = sqlite3_reset(pStmt);
112970  if( pPending ){
112971    apSegment[i] = pPending;
112972    pPending = 0;
112973  }
112974  pStmt = 0;
112975  if( rc!=SQLITE_OK ) goto finished;
112976
112977  memset(&filter, 0, sizeof(Fts3SegFilter));
112978  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
112979  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
112980  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
112981      &filter, fts3MergeCallback, (void *)&pWriter
112982  );
112983  if( rc!=SQLITE_OK ) goto finished;
112984
112985  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
112986  if( rc==SQLITE_OK ){
112987    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
112988  }
112989
112990 finished:
112991  fts3SegWriterFree(pWriter);
112992  if( apSegment ){
112993    for(i=0; i<nSegment; i++){
112994      sqlite3Fts3SegReaderFree(p, apSegment[i]);
112995    }
112996    sqlite3_free(apSegment);
112997  }
112998  sqlite3Fts3SegReaderFree(p, pPending);
112999  sqlite3_reset(pStmt);
113000  return rc;
113001}
113002
113003
113004/*
113005** Flush the contents of pendingTerms to a level 0 segment.
113006*/
113007SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
113008  int rc;                         /* Return Code */
113009  int idx;                        /* Index of new segment created */
113010  SegmentWriter *pWriter = 0;     /* Used to write the segment */
113011  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
113012
113013  /* Allocate a SegReader object to iterate through the contents of the
113014  ** pending-terms table. If an error occurs, or if there are no terms
113015  ** in the pending-terms table, return immediately.
113016  */
113017  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
113018  if( rc!=SQLITE_OK || pReader==0 ){
113019    return rc;
113020  }
113021
113022  /* Determine the next index at level 0. If level 0 is already full, this
113023  ** call may merge all existing level 0 segments into a single level 1
113024  ** segment.
113025  */
113026  rc = fts3AllocateSegdirIdx(p, 0, &idx);
113027
113028  /* If no errors have occured, iterate through the contents of the
113029  ** pending-terms hash table using the Fts3SegReader iterator. The callback
113030  ** writes each term (along with its doclist) to the database via the
113031  ** SegmentWriter handle pWriter.
113032  */
113033  if( rc==SQLITE_OK ){
113034    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
113035    Fts3SegFilter f;              /* SegReaderIterate() parameters */
113036
113037    memset(&f, 0, sizeof(Fts3SegFilter));
113038    f.flags = FTS3_SEGMENT_REQUIRE_POS;
113039    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
113040  }
113041  assert( pWriter || rc!=SQLITE_OK );
113042
113043  /* If no errors have occured, flush the SegmentWriter object to the
113044  ** database. Then delete the SegmentWriter and Fts3SegReader objects
113045  ** allocated by this function.
113046  */
113047  if( rc==SQLITE_OK ){
113048    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
113049  }
113050  fts3SegWriterFree(pWriter);
113051  sqlite3Fts3SegReaderFree(p, pReader);
113052
113053  if( rc==SQLITE_OK ){
113054    sqlite3Fts3PendingTermsClear(p);
113055  }
113056  return rc;
113057}
113058
113059/*
113060** Encode N integers as varints into a blob.
113061*/
113062static void fts3EncodeIntArray(
113063  int N,             /* The number of integers to encode */
113064  u32 *a,            /* The integer values */
113065  char *zBuf,        /* Write the BLOB here */
113066  int *pNBuf         /* Write number of bytes if zBuf[] used here */
113067){
113068  int i, j;
113069  for(i=j=0; i<N; i++){
113070    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
113071  }
113072  *pNBuf = j;
113073}
113074
113075/*
113076** Decode a blob of varints into N integers
113077*/
113078static void fts3DecodeIntArray(
113079  int N,             /* The number of integers to decode */
113080  u32 *a,            /* Write the integer values */
113081  const char *zBuf,  /* The BLOB containing the varints */
113082  int nBuf           /* size of the BLOB */
113083){
113084  int i, j;
113085  UNUSED_PARAMETER(nBuf);
113086  for(i=j=0; i<N; i++){
113087    sqlite3_int64 x;
113088    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
113089    assert(j<=nBuf);
113090    a[i] = (u32)(x & 0xffffffff);
113091  }
113092}
113093
113094/*
113095** Fill in the document size auxiliary information for the matchinfo
113096** structure.  The auxiliary information is:
113097**
113098**    N     Total number of documents in the full-text index
113099**    a0    Average length of column 0 over the whole index
113100**    n0    Length of column 0 on the matching row
113101**    ...
113102**    aM    Average length of column M over the whole index
113103**    nM    Length of column M on the matching row
113104**
113105** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
113106** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
113107*/
113108SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
113109  const char *pBlob;       /* The BLOB holding %_docsize info */
113110  int nBlob;               /* Size of the BLOB */
113111  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113112  int i, j;                /* Loop counters */
113113  sqlite3_int64 x;         /* Varint value */
113114  int rc;                  /* Result code from subfunctions */
113115  Fts3Table *p;            /* The FTS table */
113116
113117  p = (Fts3Table*)pCur->base.pVtab;
113118  rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
113119  if( rc ){
113120    return rc;
113121  }
113122  sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
113123  if( sqlite3_step(pStmt)==SQLITE_ROW ){
113124    nBlob = sqlite3_column_bytes(pStmt, 0);
113125    pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113126    for(i=j=0; i<p->nColumn && j<nBlob; i++){
113127      j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113128      a[2+i*2] = (u32)(x & 0xffffffff);
113129    }
113130  }
113131  sqlite3_reset(pStmt);
113132  return SQLITE_OK;
113133}
113134SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
113135  const char *pBlob;       /* The BLOB holding %_stat info */
113136  int nBlob;               /* Size of the BLOB */
113137  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113138  int i, j;                /* Loop counters */
113139  sqlite3_int64 x;         /* Varint value */
113140  int nDoc;                /* Number of documents */
113141  int rc;                  /* Result code from subfunctions */
113142  Fts3Table *p;            /* The FTS table */
113143
113144  p = (Fts3Table*)pCur->base.pVtab;
113145  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113146  if( rc ){
113147    return rc;
113148  }
113149  if( sqlite3_step(pStmt)==SQLITE_ROW ){
113150    nBlob = sqlite3_column_bytes(pStmt, 0);
113151    pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113152    j = sqlite3Fts3GetVarint(pBlob, &x);
113153    a[0] = nDoc = (u32)(x & 0xffffffff);
113154    for(i=0; i<p->nColumn && j<nBlob; i++){
113155      j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113156      a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
113157    }
113158  }
113159  sqlite3_reset(pStmt);
113160  return SQLITE_OK;
113161}
113162
113163/*
113164** Insert the sizes (in tokens) for each column of the document
113165** with docid equal to p->iPrevDocid.  The sizes are encoded as
113166** a blob of varints.
113167*/
113168static void fts3InsertDocsize(
113169  int *pRC,         /* Result code */
113170  Fts3Table *p,     /* Table into which to insert */
113171  u32 *aSz          /* Sizes of each column */
113172){
113173  char *pBlob;             /* The BLOB encoding of the document size */
113174  int nBlob;               /* Number of bytes in the BLOB */
113175  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
113176  int rc;                  /* Result code from subfunctions */
113177
113178  if( *pRC ) return;
113179  pBlob = sqlite3_malloc( 10*p->nColumn );
113180  if( pBlob==0 ){
113181    *pRC = SQLITE_NOMEM;
113182    return;
113183  }
113184  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
113185  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
113186  if( rc ){
113187    sqlite3_free(pBlob);
113188    *pRC = rc;
113189    return;
113190  }
113191  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
113192  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
113193  sqlite3_step(pStmt);
113194  *pRC = sqlite3_reset(pStmt);
113195}
113196
113197/*
113198** Update the 0 record of the %_stat table so that it holds a blob
113199** which contains the document count followed by the cumulative
113200** document sizes for all columns.
113201*/
113202static void fts3UpdateDocTotals(
113203  int *pRC,       /* The result code */
113204  Fts3Table *p,   /* Table being updated */
113205  u32 *aSzIns,    /* Size increases */
113206  u32 *aSzDel,    /* Size decreases */
113207  int nChng       /* Change in the number of documents */
113208){
113209  char *pBlob;             /* Storage for BLOB written into %_stat */
113210  int nBlob;               /* Size of BLOB written into %_stat */
113211  u32 *a;                  /* Array of integers that becomes the BLOB */
113212  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113213  int i;                   /* Loop counter */
113214  int rc;                  /* Result code from subfunctions */
113215
113216  if( *pRC ) return;
113217  a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
113218  if( a==0 ){
113219    *pRC = SQLITE_NOMEM;
113220    return;
113221  }
113222  pBlob = (char*)&a[p->nColumn+1];
113223  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113224  if( rc ){
113225    sqlite3_free(a);
113226    *pRC = rc;
113227    return;
113228  }
113229  if( sqlite3_step(pStmt)==SQLITE_ROW ){
113230    fts3DecodeIntArray(p->nColumn+1, a,
113231         sqlite3_column_blob(pStmt, 0),
113232         sqlite3_column_bytes(pStmt, 0));
113233  }else{
113234    memset(a, 0, sizeof(u32)*(p->nColumn+1) );
113235  }
113236  sqlite3_reset(pStmt);
113237  if( nChng<0 && a[0]<(u32)(-nChng) ){
113238    a[0] = 0;
113239  }else{
113240    a[0] += nChng;
113241  }
113242  for(i=0; i<p->nColumn; i++){
113243    u32 x = a[i+1];
113244    if( x+aSzIns[i] < aSzDel[i] ){
113245      x = 0;
113246    }else{
113247      x = x + aSzIns[i] - aSzDel[i];
113248    }
113249    a[i+1] = x;
113250  }
113251  fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
113252  rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
113253  if( rc ){
113254    sqlite3_free(a);
113255    *pRC = rc;
113256    return;
113257  }
113258  sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
113259  sqlite3_step(pStmt);
113260  *pRC = sqlite3_reset(pStmt);
113261  sqlite3_free(a);
113262}
113263
113264/*
113265** Handle a 'special' INSERT of the form:
113266**
113267**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
113268**
113269** Argument pVal contains the result of <expr>. Currently the only
113270** meaningful value to insert is the text 'optimize'.
113271*/
113272static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
113273  int rc;                         /* Return Code */
113274  const char *zVal = (const char *)sqlite3_value_text(pVal);
113275  int nVal = sqlite3_value_bytes(pVal);
113276
113277  if( !zVal ){
113278    return SQLITE_NOMEM;
113279  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
113280    rc = fts3SegmentMerge(p, -1);
113281    if( rc==SQLITE_DONE ){
113282      rc = SQLITE_OK;
113283    }else{
113284      sqlite3Fts3PendingTermsClear(p);
113285    }
113286#ifdef SQLITE_TEST
113287  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
113288    p->nNodeSize = atoi(&zVal[9]);
113289    rc = SQLITE_OK;
113290  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
113291    p->nMaxPendingData = atoi(&zVal[11]);
113292    rc = SQLITE_OK;
113293#endif
113294  }else{
113295    rc = SQLITE_ERROR;
113296  }
113297
113298  return rc;
113299}
113300
113301/*
113302** This function does the work for the xUpdate method of FTS3 virtual
113303** tables.
113304*/
113305SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
113306  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
113307  int nArg,                       /* Size of argument array */
113308  sqlite3_value **apVal,          /* Array of arguments */
113309  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
113310){
113311  Fts3Table *p = (Fts3Table *)pVtab;
113312  int rc = SQLITE_OK;             /* Return Code */
113313  int isRemove = 0;               /* True for an UPDATE or DELETE */
113314  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
113315  u32 *aSzIns;                    /* Sizes of inserted documents */
113316  u32 *aSzDel;                    /* Sizes of deleted documents */
113317  int nChng = 0;                  /* Net change in number of documents */
113318
113319
113320  /* Allocate space to hold the change in document sizes */
113321  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
113322  if( aSzIns==0 ) return SQLITE_NOMEM;
113323  aSzDel = &aSzIns[p->nColumn];
113324  memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
113325
113326  /* If this is a DELETE or UPDATE operation, remove the old record. */
113327  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
113328    int isEmpty;
113329    rc = fts3IsEmpty(p, apVal, &isEmpty);
113330    if( rc==SQLITE_OK ){
113331      if( isEmpty ){
113332        /* Deleting this row means the whole table is empty. In this case
113333        ** delete the contents of all three tables and throw away any
113334        ** data in the pendingTerms hash table.
113335        */
113336        rc = fts3DeleteAll(p);
113337      }else{
113338        isRemove = 1;
113339        iRemove = sqlite3_value_int64(apVal[0]);
113340        rc = fts3PendingTermsDocid(p, iRemove);
113341        fts3DeleteTerms(&rc, p, apVal, aSzDel);
113342        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
113343        if( p->bHasDocsize ){
113344          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
113345          nChng--;
113346        }
113347      }
113348    }
113349  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
113350    sqlite3_free(aSzIns);
113351    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
113352  }
113353
113354  /* If this is an INSERT or UPDATE operation, insert the new record. */
113355  if( nArg>1 && rc==SQLITE_OK ){
113356    rc = fts3InsertData(p, apVal, pRowid);
113357    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
113358      rc = fts3PendingTermsDocid(p, *pRowid);
113359    }
113360    if( rc==SQLITE_OK ){
113361      rc = fts3InsertTerms(p, apVal, aSzIns);
113362    }
113363    if( p->bHasDocsize ){
113364      nChng++;
113365      fts3InsertDocsize(&rc, p, aSzIns);
113366    }
113367  }
113368
113369  if( p->bHasDocsize ){
113370    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
113371  }
113372
113373  sqlite3_free(aSzIns);
113374  return rc;
113375}
113376
113377/*
113378** Flush any data in the pending-terms hash table to disk. If successful,
113379** merge all segments in the database (including the new segment, if
113380** there was any data to flush) into a single segment.
113381*/
113382SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
113383  int rc;
113384  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
113385  if( rc==SQLITE_OK ){
113386    rc = fts3SegmentMerge(p, -1);
113387    if( rc==SQLITE_OK ){
113388      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113389      if( rc==SQLITE_OK ){
113390        sqlite3Fts3PendingTermsClear(p);
113391      }
113392    }else{
113393      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
113394      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113395    }
113396  }
113397  return rc;
113398}
113399
113400#endif
113401
113402/************** End of fts3_write.c ******************************************/
113403/************** Begin file fts3_snippet.c ************************************/
113404/*
113405** 2009 Oct 23
113406**
113407** The author disclaims copyright to this source code.  In place of
113408** a legal notice, here is a blessing:
113409**
113410**    May you do good and not evil.
113411**    May you find forgiveness for yourself and forgive others.
113412**    May you share freely, never taking more than you give.
113413**
113414******************************************************************************
113415*/
113416
113417#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113418
113419
113420
113421/*
113422** Used as an fts3ExprIterate() context when loading phrase doclists to
113423** Fts3Expr.aDoclist[]/nDoclist.
113424*/
113425typedef struct LoadDoclistCtx LoadDoclistCtx;
113426struct LoadDoclistCtx {
113427  Fts3Table *pTab;                /* FTS3 Table */
113428  int nPhrase;                    /* Number of phrases seen so far */
113429  int nToken;                     /* Number of tokens seen so far */
113430};
113431
113432/*
113433** The following types are used as part of the implementation of the
113434** fts3BestSnippet() routine.
113435*/
113436typedef struct SnippetIter SnippetIter;
113437typedef struct SnippetPhrase SnippetPhrase;
113438typedef struct SnippetFragment SnippetFragment;
113439
113440struct SnippetIter {
113441  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
113442  int iCol;                       /* Extract snippet from this column */
113443  int nSnippet;                   /* Requested snippet length (in tokens) */
113444  int nPhrase;                    /* Number of phrases in query */
113445  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
113446  int iCurrent;                   /* First token of current snippet */
113447};
113448
113449struct SnippetPhrase {
113450  int nToken;                     /* Number of tokens in phrase */
113451  char *pList;                    /* Pointer to start of phrase position list */
113452  int iHead;                      /* Next value in position list */
113453  char *pHead;                    /* Position list data following iHead */
113454  int iTail;                      /* Next value in trailing position list */
113455  char *pTail;                    /* Position list data following iTail */
113456};
113457
113458struct SnippetFragment {
113459  int iCol;                       /* Column snippet is extracted from */
113460  int iPos;                       /* Index of first token in snippet */
113461  u64 covered;                    /* Mask of query phrases covered */
113462  u64 hlmask;                     /* Mask of snippet terms to highlight */
113463};
113464
113465/*
113466** This type is used as an fts3ExprIterate() context object while
113467** accumulating the data returned by the matchinfo() function.
113468*/
113469typedef struct MatchInfo MatchInfo;
113470struct MatchInfo {
113471  Fts3Cursor *pCursor;            /* FTS3 Cursor */
113472  int nCol;                       /* Number of columns in table */
113473  u32 *aMatchinfo;                /* Pre-allocated buffer */
113474};
113475
113476
113477
113478/*
113479** The snippet() and offsets() functions both return text values. An instance
113480** of the following structure is used to accumulate those values while the
113481** functions are running. See fts3StringAppend() for details.
113482*/
113483typedef struct StrBuffer StrBuffer;
113484struct StrBuffer {
113485  char *z;                        /* Pointer to buffer containing string */
113486  int n;                          /* Length of z in bytes (excl. nul-term) */
113487  int nAlloc;                     /* Allocated size of buffer z in bytes */
113488};
113489
113490
113491/*
113492** This function is used to help iterate through a position-list. A position
113493** list is a list of unique integers, sorted from smallest to largest. Each
113494** element of the list is represented by an FTS3 varint that takes the value
113495** of the difference between the current element and the previous one plus
113496** two. For example, to store the position-list:
113497**
113498**     4 9 113
113499**
113500** the three varints:
113501**
113502**     6 7 106
113503**
113504** are encoded.
113505**
113506** When this function is called, *pp points to the start of an element of
113507** the list. *piPos contains the value of the previous entry in the list.
113508** After it returns, *piPos contains the value of the next element of the
113509** list and *pp is advanced to the following varint.
113510*/
113511static void fts3GetDeltaPosition(char **pp, int *piPos){
113512  int iVal;
113513  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
113514  *piPos += (iVal-2);
113515}
113516
113517/*
113518** Helper function for fts3ExprIterate() (see below).
113519*/
113520static int fts3ExprIterate2(
113521  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113522  int *piPhrase,                  /* Pointer to phrase counter */
113523  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113524  void *pCtx                      /* Second argument to pass to callback */
113525){
113526  int rc;                         /* Return code */
113527  int eType = pExpr->eType;       /* Type of expression node pExpr */
113528
113529  if( eType!=FTSQUERY_PHRASE ){
113530    assert( pExpr->pLeft && pExpr->pRight );
113531    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
113532    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
113533      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
113534    }
113535  }else{
113536    rc = x(pExpr, *piPhrase, pCtx);
113537    (*piPhrase)++;
113538  }
113539  return rc;
113540}
113541
113542/*
113543** Iterate through all phrase nodes in an FTS3 query, except those that
113544** are part of a sub-tree that is the right-hand-side of a NOT operator.
113545** For each phrase node found, the supplied callback function is invoked.
113546**
113547** If the callback function returns anything other than SQLITE_OK,
113548** the iteration is abandoned and the error code returned immediately.
113549** Otherwise, SQLITE_OK is returned after a callback has been made for
113550** all eligible phrase nodes.
113551*/
113552static int fts3ExprIterate(
113553  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113554  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113555  void *pCtx                      /* Second argument to pass to callback */
113556){
113557  int iPhrase = 0;                /* Variable used as the phrase counter */
113558  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
113559}
113560
113561/*
113562** The argument to this function is always a phrase node. Its doclist
113563** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
113564** to the left of this one in the query tree have already been loaded.
113565**
113566** If this phrase node is part of a series of phrase nodes joined by
113567** NEAR operators (and is not the left-most of said series), then elements are
113568** removed from the phrases doclist consistent with the NEAR restriction. If
113569** required, elements may be removed from the doclists of phrases to the
113570** left of this one that are part of the same series of NEAR operator
113571** connected phrases.
113572**
113573** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
113574*/
113575static int fts3ExprNearTrim(Fts3Expr *pExpr){
113576  int rc = SQLITE_OK;
113577  Fts3Expr *pParent = pExpr->pParent;
113578
113579  assert( pExpr->eType==FTSQUERY_PHRASE );
113580  while( rc==SQLITE_OK
113581   && pParent
113582   && pParent->eType==FTSQUERY_NEAR
113583   && pParent->pRight==pExpr
113584  ){
113585    /* This expression (pExpr) is the right-hand-side of a NEAR operator.
113586    ** Find the expression to the left of the same operator.
113587    */
113588    int nNear = pParent->nNear;
113589    Fts3Expr *pLeft = pParent->pLeft;
113590
113591    if( pLeft->eType!=FTSQUERY_PHRASE ){
113592      assert( pLeft->eType==FTSQUERY_NEAR );
113593      assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
113594      pLeft = pLeft->pRight;
113595    }
113596
113597    rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
113598
113599    pExpr = pLeft;
113600    pParent = pExpr->pParent;
113601  }
113602
113603  return rc;
113604}
113605
113606/*
113607** This is an fts3ExprIterate() callback used while loading the doclists
113608** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
113609** fts3ExprLoadDoclists().
113610*/
113611static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
113612  int rc = SQLITE_OK;
113613  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
113614
113615  UNUSED_PARAMETER(iPhrase);
113616
113617  p->nPhrase++;
113618  p->nToken += pExpr->pPhrase->nToken;
113619
113620  if( pExpr->isLoaded==0 ){
113621    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
113622    pExpr->isLoaded = 1;
113623    if( rc==SQLITE_OK ){
113624      rc = fts3ExprNearTrim(pExpr);
113625    }
113626  }
113627
113628  return rc;
113629}
113630
113631/*
113632** This is an fts3ExprIterate() callback used while loading the doclists
113633** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
113634** fts3ExprLoadDoclists().
113635*/
113636static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
113637  UNUSED_PARAMETER(iPhrase);
113638  UNUSED_PARAMETER(ctx);
113639  if( pExpr->aDoclist ){
113640    pExpr->pCurrent = pExpr->aDoclist;
113641    pExpr->iCurrent = 0;
113642    pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
113643  }
113644  return SQLITE_OK;
113645}
113646
113647/*
113648** Load the doclists for each phrase in the query associated with FTS3 cursor
113649** pCsr.
113650**
113651** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
113652** phrases in the expression (all phrases except those directly or
113653** indirectly descended from the right-hand-side of a NOT operator). If
113654** pnToken is not NULL, then it is set to the number of tokens in all
113655** matchable phrases of the expression.
113656*/
113657static int fts3ExprLoadDoclists(
113658  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
113659  int *pnPhrase,                  /* OUT: Number of phrases in query */
113660  int *pnToken                    /* OUT: Number of tokens in query */
113661){
113662  int rc;                         /* Return Code */
113663  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
113664  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
113665  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
113666  if( rc==SQLITE_OK ){
113667    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
113668  }
113669  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
113670  if( pnToken ) *pnToken = sCtx.nToken;
113671  return rc;
113672}
113673
113674/*
113675** Advance the position list iterator specified by the first two
113676** arguments so that it points to the first element with a value greater
113677** than or equal to parameter iNext.
113678*/
113679static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
113680  char *pIter = *ppIter;
113681  if( pIter ){
113682    int iIter = *piIter;
113683
113684    while( iIter<iNext ){
113685      if( 0==(*pIter & 0xFE) ){
113686        iIter = -1;
113687        pIter = 0;
113688        break;
113689      }
113690      fts3GetDeltaPosition(&pIter, &iIter);
113691    }
113692
113693    *piIter = iIter;
113694    *ppIter = pIter;
113695  }
113696}
113697
113698/*
113699** Advance the snippet iterator to the next candidate snippet.
113700*/
113701static int fts3SnippetNextCandidate(SnippetIter *pIter){
113702  int i;                          /* Loop counter */
113703
113704  if( pIter->iCurrent<0 ){
113705    /* The SnippetIter object has just been initialized. The first snippet
113706    ** candidate always starts at offset 0 (even if this candidate has a
113707    ** score of 0.0).
113708    */
113709    pIter->iCurrent = 0;
113710
113711    /* Advance the 'head' iterator of each phrase to the first offset that
113712    ** is greater than or equal to (iNext+nSnippet).
113713    */
113714    for(i=0; i<pIter->nPhrase; i++){
113715      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
113716      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
113717    }
113718  }else{
113719    int iStart;
113720    int iEnd = 0x7FFFFFFF;
113721
113722    for(i=0; i<pIter->nPhrase; i++){
113723      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
113724      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
113725        iEnd = pPhrase->iHead;
113726      }
113727    }
113728    if( iEnd==0x7FFFFFFF ){
113729      return 1;
113730    }
113731
113732    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
113733    for(i=0; i<pIter->nPhrase; i++){
113734      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
113735      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
113736      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
113737    }
113738  }
113739
113740  return 0;
113741}
113742
113743/*
113744** Retrieve information about the current candidate snippet of snippet
113745** iterator pIter.
113746*/
113747static void fts3SnippetDetails(
113748  SnippetIter *pIter,             /* Snippet iterator */
113749  u64 mCovered,                   /* Bitmask of phrases already covered */
113750  int *piToken,                   /* OUT: First token of proposed snippet */
113751  int *piScore,                   /* OUT: "Score" for this snippet */
113752  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
113753  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
113754){
113755  int iStart = pIter->iCurrent;   /* First token of snippet */
113756  int iScore = 0;                 /* Score of this snippet */
113757  int i;                          /* Loop counter */
113758  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
113759  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
113760
113761  for(i=0; i<pIter->nPhrase; i++){
113762    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
113763    if( pPhrase->pTail ){
113764      char *pCsr = pPhrase->pTail;
113765      int iCsr = pPhrase->iTail;
113766
113767      while( iCsr<(iStart+pIter->nSnippet) ){
113768        int j;
113769        u64 mPhrase = (u64)1 << i;
113770        u64 mPos = (u64)1 << (iCsr - iStart);
113771        assert( iCsr>=iStart );
113772        if( (mCover|mCovered)&mPhrase ){
113773          iScore++;
113774        }else{
113775          iScore += 1000;
113776        }
113777        mCover |= mPhrase;
113778
113779        for(j=0; j<pPhrase->nToken; j++){
113780          mHighlight |= (mPos>>j);
113781        }
113782
113783        if( 0==(*pCsr & 0x0FE) ) break;
113784        fts3GetDeltaPosition(&pCsr, &iCsr);
113785      }
113786    }
113787  }
113788
113789  /* Set the output variables before returning. */
113790  *piToken = iStart;
113791  *piScore = iScore;
113792  *pmCover = mCover;
113793  *pmHighlight = mHighlight;
113794}
113795
113796/*
113797** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
113798** Each invocation populates an element of the SnippetIter.aPhrase[] array.
113799*/
113800static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
113801  SnippetIter *p = (SnippetIter *)ctx;
113802  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
113803  char *pCsr;
113804
113805  pPhrase->nToken = pExpr->pPhrase->nToken;
113806
113807  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
113808  if( pCsr ){
113809    int iFirst = 0;
113810    pPhrase->pList = pCsr;
113811    fts3GetDeltaPosition(&pCsr, &iFirst);
113812    pPhrase->pHead = pCsr;
113813    pPhrase->pTail = pCsr;
113814    pPhrase->iHead = iFirst;
113815    pPhrase->iTail = iFirst;
113816  }else{
113817    assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
113818  }
113819
113820  return SQLITE_OK;
113821}
113822
113823/*
113824** Select the fragment of text consisting of nFragment contiguous tokens
113825** from column iCol that represent the "best" snippet. The best snippet
113826** is the snippet with the highest score, where scores are calculated
113827** by adding:
113828**
113829**   (a) +1 point for each occurence of a matchable phrase in the snippet.
113830**
113831**   (b) +1000 points for the first occurence of each matchable phrase in
113832**       the snippet for which the corresponding mCovered bit is not set.
113833**
113834** The selected snippet parameters are stored in structure *pFragment before
113835** returning. The score of the selected snippet is stored in *piScore
113836** before returning.
113837*/
113838static int fts3BestSnippet(
113839  int nSnippet,                   /* Desired snippet length */
113840  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
113841  int iCol,                       /* Index of column to create snippet from */
113842  u64 mCovered,                   /* Mask of phrases already covered */
113843  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
113844  SnippetFragment *pFragment,     /* OUT: Best snippet found */
113845  int *piScore                    /* OUT: Score of snippet pFragment */
113846){
113847  int rc;                         /* Return Code */
113848  int nList;                      /* Number of phrases in expression */
113849  SnippetIter sIter;              /* Iterates through snippet candidates */
113850  int nByte;                      /* Number of bytes of space to allocate */
113851  int iBestScore = -1;            /* Best snippet score found so far */
113852  int i;                          /* Loop counter */
113853
113854  memset(&sIter, 0, sizeof(sIter));
113855
113856  /* Iterate through the phrases in the expression to count them. The same
113857  ** callback makes sure the doclists are loaded for each phrase.
113858  */
113859  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
113860  if( rc!=SQLITE_OK ){
113861    return rc;
113862  }
113863
113864  /* Now that it is known how many phrases there are, allocate and zero
113865  ** the required space using malloc().
113866  */
113867  nByte = sizeof(SnippetPhrase) * nList;
113868  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
113869  if( !sIter.aPhrase ){
113870    return SQLITE_NOMEM;
113871  }
113872  memset(sIter.aPhrase, 0, nByte);
113873
113874  /* Initialize the contents of the SnippetIter object. Then iterate through
113875  ** the set of phrases in the expression to populate the aPhrase[] array.
113876  */
113877  sIter.pCsr = pCsr;
113878  sIter.iCol = iCol;
113879  sIter.nSnippet = nSnippet;
113880  sIter.nPhrase = nList;
113881  sIter.iCurrent = -1;
113882  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
113883
113884  /* Set the *pmSeen output variable. */
113885  for(i=0; i<nList; i++){
113886    if( sIter.aPhrase[i].pHead ){
113887      *pmSeen |= (u64)1 << i;
113888    }
113889  }
113890
113891  /* Loop through all candidate snippets. Store the best snippet in
113892  ** *pFragment. Store its associated 'score' in iBestScore.
113893  */
113894  pFragment->iCol = iCol;
113895  while( !fts3SnippetNextCandidate(&sIter) ){
113896    int iPos;
113897    int iScore;
113898    u64 mCover;
113899    u64 mHighlight;
113900    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
113901    assert( iScore>=0 );
113902    if( iScore>iBestScore ){
113903      pFragment->iPos = iPos;
113904      pFragment->hlmask = mHighlight;
113905      pFragment->covered = mCover;
113906      iBestScore = iScore;
113907    }
113908  }
113909
113910  sqlite3_free(sIter.aPhrase);
113911  *piScore = iBestScore;
113912  return SQLITE_OK;
113913}
113914
113915
113916/*
113917** Append a string to the string-buffer passed as the first argument.
113918**
113919** If nAppend is negative, then the length of the string zAppend is
113920** determined using strlen().
113921*/
113922static int fts3StringAppend(
113923  StrBuffer *pStr,                /* Buffer to append to */
113924  const char *zAppend,            /* Pointer to data to append to buffer */
113925  int nAppend                     /* Size of zAppend in bytes (or -1) */
113926){
113927  if( nAppend<0 ){
113928    nAppend = (int)strlen(zAppend);
113929  }
113930
113931  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
113932  ** to grow the buffer until so that it is big enough to accomadate the
113933  ** appended data.
113934  */
113935  if( pStr->n+nAppend+1>=pStr->nAlloc ){
113936    int nAlloc = pStr->nAlloc+nAppend+100;
113937    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
113938    if( !zNew ){
113939      return SQLITE_NOMEM;
113940    }
113941    pStr->z = zNew;
113942    pStr->nAlloc = nAlloc;
113943  }
113944
113945  /* Append the data to the string buffer. */
113946  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
113947  pStr->n += nAppend;
113948  pStr->z[pStr->n] = '\0';
113949
113950  return SQLITE_OK;
113951}
113952
113953/*
113954** The fts3BestSnippet() function often selects snippets that end with a
113955** query term. That is, the final term of the snippet is always a term
113956** that requires highlighting. For example, if 'X' is a highlighted term
113957** and '.' is a non-highlighted term, BestSnippet() may select:
113958**
113959**     ........X.....X
113960**
113961** This function "shifts" the beginning of the snippet forward in the
113962** document so that there are approximately the same number of
113963** non-highlighted terms to the right of the final highlighted term as there
113964** are to the left of the first highlighted term. For example, to this:
113965**
113966**     ....X.....X....
113967**
113968** This is done as part of extracting the snippet text, not when selecting
113969** the snippet. Snippet selection is done based on doclists only, so there
113970** is no way for fts3BestSnippet() to know whether or not the document
113971** actually contains terms that follow the final highlighted term.
113972*/
113973static int fts3SnippetShift(
113974  Fts3Table *pTab,                /* FTS3 table snippet comes from */
113975  int nSnippet,                   /* Number of tokens desired for snippet */
113976  const char *zDoc,               /* Document text to extract snippet from */
113977  int nDoc,                       /* Size of buffer zDoc in bytes */
113978  int *piPos,                     /* IN/OUT: First token of snippet */
113979  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
113980){
113981  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
113982
113983  if( hlmask ){
113984    int nLeft;                    /* Tokens to the left of first highlight */
113985    int nRight;                   /* Tokens to the right of last highlight */
113986    int nDesired;                 /* Ideal number of tokens to shift forward */
113987
113988    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
113989    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
113990    nDesired = (nLeft-nRight)/2;
113991
113992    /* Ideally, the start of the snippet should be pushed forward in the
113993    ** document nDesired tokens. This block checks if there are actually
113994    ** nDesired tokens to the right of the snippet. If so, *piPos and
113995    ** *pHlMask are updated to shift the snippet nDesired tokens to the
113996    ** right. Otherwise, the snippet is shifted by the number of tokens
113997    ** available.
113998    */
113999    if( nDesired>0 ){
114000      int nShift;                 /* Number of tokens to shift snippet by */
114001      int iCurrent = 0;           /* Token counter */
114002      int rc;                     /* Return Code */
114003      sqlite3_tokenizer_module *pMod;
114004      sqlite3_tokenizer_cursor *pC;
114005      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114006
114007      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
114008      ** or more tokens in zDoc/nDoc.
114009      */
114010      rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114011      if( rc!=SQLITE_OK ){
114012        return rc;
114013      }
114014      pC->pTokenizer = pTab->pTokenizer;
114015      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
114016        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
114017        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
114018      }
114019      pMod->xClose(pC);
114020      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
114021
114022      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
114023      assert( nShift<=nDesired );
114024      if( nShift>0 ){
114025        *piPos += nShift;
114026        *pHlmask = hlmask >> nShift;
114027      }
114028    }
114029  }
114030  return SQLITE_OK;
114031}
114032
114033/*
114034** Extract the snippet text for fragment pFragment from cursor pCsr and
114035** append it to string buffer pOut.
114036*/
114037static int fts3SnippetText(
114038  Fts3Cursor *pCsr,               /* FTS3 Cursor */
114039  SnippetFragment *pFragment,     /* Snippet to extract */
114040  int iFragment,                  /* Fragment number */
114041  int isLast,                     /* True for final fragment in snippet */
114042  int nSnippet,                   /* Number of tokens in extracted snippet */
114043  const char *zOpen,              /* String inserted before highlighted term */
114044  const char *zClose,             /* String inserted after highlighted term */
114045  const char *zEllipsis,          /* String inserted between snippets */
114046  StrBuffer *pOut                 /* Write output here */
114047){
114048  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114049  int rc;                         /* Return code */
114050  const char *zDoc;               /* Document text to extract snippet from */
114051  int nDoc;                       /* Size of zDoc in bytes */
114052  int iCurrent = 0;               /* Current token number of document */
114053  int iEnd = 0;                   /* Byte offset of end of current token */
114054  int isShiftDone = 0;            /* True after snippet is shifted */
114055  int iPos = pFragment->iPos;     /* First token of snippet */
114056  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
114057  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
114058  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
114059  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
114060  const char *ZDUMMY;             /* Dummy argument used with tokenizer */
114061  int DUMMY1;                     /* Dummy argument used with tokenizer */
114062
114063  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
114064  if( zDoc==0 ){
114065    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
114066      return SQLITE_NOMEM;
114067    }
114068    return SQLITE_OK;
114069  }
114070  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
114071
114072  /* Open a token cursor on the document. */
114073  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114074  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114075  if( rc!=SQLITE_OK ){
114076    return rc;
114077  }
114078  pC->pTokenizer = pTab->pTokenizer;
114079
114080  while( rc==SQLITE_OK ){
114081    int iBegin;                   /* Offset in zDoc of start of token */
114082    int iFin;                     /* Offset in zDoc of end of token */
114083    int isHighlight;              /* True for highlighted terms */
114084
114085    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
114086    if( rc!=SQLITE_OK ){
114087      if( rc==SQLITE_DONE ){
114088        /* Special case - the last token of the snippet is also the last token
114089        ** of the column. Append any punctuation that occurred between the end
114090        ** of the previous token and the end of the document to the output.
114091        ** Then break out of the loop. */
114092        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
114093      }
114094      break;
114095    }
114096    if( iCurrent<iPos ){ continue; }
114097
114098    if( !isShiftDone ){
114099      int n = nDoc - iBegin;
114100      rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
114101      isShiftDone = 1;
114102
114103      /* Now that the shift has been done, check if the initial "..." are
114104      ** required. They are required if (a) this is not the first fragment,
114105      ** or (b) this fragment does not begin at position 0 of its column.
114106      */
114107      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
114108        rc = fts3StringAppend(pOut, zEllipsis, -1);
114109      }
114110      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
114111    }
114112
114113    if( iCurrent>=(iPos+nSnippet) ){
114114      if( isLast ){
114115        rc = fts3StringAppend(pOut, zEllipsis, -1);
114116      }
114117      break;
114118    }
114119
114120    /* Set isHighlight to true if this term should be highlighted. */
114121    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
114122
114123    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
114124    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
114125    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
114126    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
114127
114128    iEnd = iFin;
114129  }
114130
114131  pMod->xClose(pC);
114132  return rc;
114133}
114134
114135
114136/*
114137** This function is used to count the entries in a column-list (a
114138** delta-encoded list of term offsets within a single column of a single
114139** row). When this function is called, *ppCollist should point to the
114140** beginning of the first varint in the column-list (the varint that
114141** contains the position of the first matching term in the column data).
114142** Before returning, *ppCollist is set to point to the first byte after
114143** the last varint in the column-list (either the 0x00 signifying the end
114144** of the position-list, or the 0x01 that precedes the column number of
114145** the next column in the position-list).
114146**
114147** The number of elements in the column-list is returned.
114148*/
114149static int fts3ColumnlistCount(char **ppCollist){
114150  char *pEnd = *ppCollist;
114151  char c = 0;
114152  int nEntry = 0;
114153
114154  /* A column-list is terminated by either a 0x01 or 0x00. */
114155  while( 0xFE & (*pEnd | c) ){
114156    c = *pEnd++ & 0x80;
114157    if( !c ) nEntry++;
114158  }
114159
114160  *ppCollist = pEnd;
114161  return nEntry;
114162}
114163
114164static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
114165  char *pCsr = *pp;
114166  while( *pCsr ){
114167    int nHit;
114168    sqlite3_int64 iCol = 0;
114169    if( *pCsr==0x01 ){
114170      pCsr++;
114171      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
114172    }
114173    nHit = fts3ColumnlistCount(&pCsr);
114174    assert( nHit>0 );
114175    if( isGlobal ){
114176      aOut[iCol*3+1]++;
114177    }
114178    aOut[iCol*3] += nHit;
114179  }
114180  pCsr++;
114181  *pp = pCsr;
114182}
114183
114184/*
114185** fts3ExprIterate() callback used to collect the "global" matchinfo stats
114186** for a single query. The "global" stats are those elements of the matchinfo
114187** array that are constant for all rows returned by the current query.
114188*/
114189static int fts3ExprGlobalMatchinfoCb(
114190  Fts3Expr *pExpr,                /* Phrase expression node */
114191  int iPhrase,                    /* Phrase number (numbered from zero) */
114192  void *pCtx                      /* Pointer to MatchInfo structure */
114193){
114194  MatchInfo *p = (MatchInfo *)pCtx;
114195  char *pCsr;
114196  char *pEnd;
114197  const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
114198
114199  assert( pExpr->isLoaded );
114200
114201  /* Fill in the global hit count matrix row for this phrase. */
114202  pCsr = pExpr->aDoclist;
114203  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114204  while( pCsr<pEnd ){
114205    while( *pCsr++ & 0x80 );      /* Skip past docid. */
114206    fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
114207  }
114208
114209  return SQLITE_OK;
114210}
114211
114212/*
114213** fts3ExprIterate() callback used to collect the "local" matchinfo stats
114214** for a single query. The "local" stats are those elements of the matchinfo
114215** array that are different for each row returned by the query.
114216*/
114217static int fts3ExprLocalMatchinfoCb(
114218  Fts3Expr *pExpr,                /* Phrase expression node */
114219  int iPhrase,                    /* Phrase number */
114220  void *pCtx                      /* Pointer to MatchInfo structure */
114221){
114222  MatchInfo *p = (MatchInfo *)pCtx;
114223
114224  if( pExpr->aDoclist ){
114225    char *pCsr;
114226    int iStart = 2 + (iPhrase * p->nCol * 3);
114227    int i;
114228
114229    for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
114230
114231    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
114232    if( pCsr ){
114233      fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
114234    }
114235  }
114236
114237  return SQLITE_OK;
114238}
114239
114240/*
114241** Populate pCsr->aMatchinfo[] with data for the current row. The
114242** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
114243*/
114244static int fts3GetMatchinfo(Fts3Cursor *pCsr){
114245  MatchInfo sInfo;
114246  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114247  int rc = SQLITE_OK;
114248
114249  sInfo.pCursor = pCsr;
114250  sInfo.nCol = pTab->nColumn;
114251
114252  if( pCsr->aMatchinfo==0 ){
114253    /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
114254    ** matchinfo function has been called for this query. In this case
114255    ** allocate the array used to accumulate the matchinfo data and
114256    ** initialize those elements that are constant for every row.
114257    */
114258    int nPhrase;                  /* Number of phrases */
114259    int nMatchinfo;               /* Number of u32 elements in match-info */
114260
114261    /* Load doclists for each phrase in the query. */
114262    rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
114263    if( rc!=SQLITE_OK ){
114264      return rc;
114265    }
114266    nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
114267    if( pTab->bHasDocsize ){
114268      nMatchinfo += 1 + 2*pTab->nColumn;
114269    }
114270
114271    sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
114272    if( !sInfo.aMatchinfo ){
114273      return SQLITE_NOMEM;
114274    }
114275    memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
114276
114277
114278    /* First element of match-info is the number of phrases in the query */
114279    sInfo.aMatchinfo[0] = nPhrase;
114280    sInfo.aMatchinfo[1] = sInfo.nCol;
114281    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
114282    if( pTab->bHasDocsize ){
114283      int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114284      rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
114285    }
114286    pCsr->aMatchinfo = sInfo.aMatchinfo;
114287    pCsr->isMatchinfoNeeded = 1;
114288  }
114289
114290  sInfo.aMatchinfo = pCsr->aMatchinfo;
114291  if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
114292    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
114293    if( pTab->bHasDocsize ){
114294      int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114295      rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
114296    }
114297    pCsr->isMatchinfoNeeded = 0;
114298  }
114299
114300  return SQLITE_OK;
114301}
114302
114303/*
114304** Implementation of snippet() function.
114305*/
114306SQLITE_PRIVATE void sqlite3Fts3Snippet(
114307  sqlite3_context *pCtx,          /* SQLite function call context */
114308  Fts3Cursor *pCsr,               /* Cursor object */
114309  const char *zStart,             /* Snippet start text - "<b>" */
114310  const char *zEnd,               /* Snippet end text - "</b>" */
114311  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
114312  int iCol,                       /* Extract snippet from this column */
114313  int nToken                      /* Approximate number of tokens in snippet */
114314){
114315  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114316  int rc = SQLITE_OK;
114317  int i;
114318  StrBuffer res = {0, 0, 0};
114319
114320  /* The returned text includes up to four fragments of text extracted from
114321  ** the data in the current row. The first iteration of the for(...) loop
114322  ** below attempts to locate a single fragment of text nToken tokens in
114323  ** size that contains at least one instance of all phrases in the query
114324  ** expression that appear in the current row. If such a fragment of text
114325  ** cannot be found, the second iteration of the loop attempts to locate
114326  ** a pair of fragments, and so on.
114327  */
114328  int nSnippet = 0;               /* Number of fragments in this snippet */
114329  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
114330  int nFToken = -1;               /* Number of tokens in each fragment */
114331
114332  if( !pCsr->pExpr ){
114333    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114334    return;
114335  }
114336
114337  for(nSnippet=1; 1; nSnippet++){
114338
114339    int iSnip;                    /* Loop counter 0..nSnippet-1 */
114340    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
114341    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
114342
114343    if( nToken>=0 ){
114344      nFToken = (nToken+nSnippet-1) / nSnippet;
114345    }else{
114346      nFToken = -1 * nToken;
114347    }
114348
114349    for(iSnip=0; iSnip<nSnippet; iSnip++){
114350      int iBestScore = -1;        /* Best score of columns checked so far */
114351      int iRead;                  /* Used to iterate through columns */
114352      SnippetFragment *pFragment = &aSnippet[iSnip];
114353
114354      memset(pFragment, 0, sizeof(*pFragment));
114355
114356      /* Loop through all columns of the table being considered for snippets.
114357      ** If the iCol argument to this function was negative, this means all
114358      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
114359      */
114360      for(iRead=0; iRead<pTab->nColumn; iRead++){
114361        SnippetFragment sF;
114362        int iS;
114363        if( iCol>=0 && iRead!=iCol ) continue;
114364
114365        /* Find the best snippet of nFToken tokens in column iRead. */
114366        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
114367        if( rc!=SQLITE_OK ){
114368          goto snippet_out;
114369        }
114370        if( iS>iBestScore ){
114371          *pFragment = sF;
114372          iBestScore = iS;
114373        }
114374      }
114375
114376      mCovered |= pFragment->covered;
114377    }
114378
114379    /* If all query phrases seen by fts3BestSnippet() are present in at least
114380    ** one of the nSnippet snippet fragments, break out of the loop.
114381    */
114382    assert( (mCovered&mSeen)==mCovered );
114383    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
114384  }
114385
114386  assert( nFToken>0 );
114387
114388  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
114389    rc = fts3SnippetText(pCsr, &aSnippet[i],
114390        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
114391    );
114392  }
114393
114394 snippet_out:
114395  if( rc!=SQLITE_OK ){
114396    sqlite3_result_error_code(pCtx, rc);
114397    sqlite3_free(res.z);
114398  }else{
114399    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
114400  }
114401}
114402
114403
114404typedef struct TermOffset TermOffset;
114405typedef struct TermOffsetCtx TermOffsetCtx;
114406
114407struct TermOffset {
114408  char *pList;                    /* Position-list */
114409  int iPos;                       /* Position just read from pList */
114410  int iOff;                       /* Offset of this term from read positions */
114411};
114412
114413struct TermOffsetCtx {
114414  int iCol;                       /* Column of table to populate aTerm for */
114415  int iTerm;
114416  sqlite3_int64 iDocid;
114417  TermOffset *aTerm;
114418};
114419
114420/*
114421** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
114422*/
114423static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
114424  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
114425  int nTerm;                      /* Number of tokens in phrase */
114426  int iTerm;                      /* For looping through nTerm phrase terms */
114427  char *pList;                    /* Pointer to position list for phrase */
114428  int iPos = 0;                   /* First position in position-list */
114429
114430  UNUSED_PARAMETER(iPhrase);
114431  pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
114432  nTerm = pExpr->pPhrase->nToken;
114433  if( pList ){
114434    fts3GetDeltaPosition(&pList, &iPos);
114435    assert( iPos>=0 );
114436  }
114437
114438  for(iTerm=0; iTerm<nTerm; iTerm++){
114439    TermOffset *pT = &p->aTerm[p->iTerm++];
114440    pT->iOff = nTerm-iTerm-1;
114441    pT->pList = pList;
114442    pT->iPos = iPos;
114443  }
114444
114445  return SQLITE_OK;
114446}
114447
114448/*
114449** Implementation of offsets() function.
114450*/
114451SQLITE_PRIVATE void sqlite3Fts3Offsets(
114452  sqlite3_context *pCtx,          /* SQLite function call context */
114453  Fts3Cursor *pCsr                /* Cursor object */
114454){
114455  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114456  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
114457  const char *ZDUMMY;             /* Dummy argument used with xNext() */
114458  int NDUMMY;                     /* Dummy argument used with xNext() */
114459  int rc;                         /* Return Code */
114460  int nToken;                     /* Number of tokens in query */
114461  int iCol;                       /* Column currently being processed */
114462  StrBuffer res = {0, 0, 0};      /* Result string */
114463  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
114464
114465  if( !pCsr->pExpr ){
114466    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114467    return;
114468  }
114469
114470  memset(&sCtx, 0, sizeof(sCtx));
114471  assert( pCsr->isRequireSeek==0 );
114472
114473  /* Count the number of terms in the query */
114474  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
114475  if( rc!=SQLITE_OK ) goto offsets_out;
114476
114477  /* Allocate the array of TermOffset iterators. */
114478  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
114479  if( 0==sCtx.aTerm ){
114480    rc = SQLITE_NOMEM;
114481    goto offsets_out;
114482  }
114483  sCtx.iDocid = pCsr->iPrevId;
114484
114485  /* Loop through the table columns, appending offset information to
114486  ** string-buffer res for each column.
114487  */
114488  for(iCol=0; iCol<pTab->nColumn; iCol++){
114489    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
114490    int iStart;
114491    int iEnd;
114492    int iCurrent;
114493    const char *zDoc;
114494    int nDoc;
114495
114496    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
114497    ** no way that this operation can fail, so the return code from
114498    ** fts3ExprIterate() can be discarded.
114499    */
114500    sCtx.iCol = iCol;
114501    sCtx.iTerm = 0;
114502    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
114503
114504    /* Retreive the text stored in column iCol. If an SQL NULL is stored
114505    ** in column iCol, jump immediately to the next iteration of the loop.
114506    ** If an OOM occurs while retrieving the data (this can happen if SQLite
114507    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
114508    ** to the caller.
114509    */
114510    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
114511    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
114512    if( zDoc==0 ){
114513      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
114514        continue;
114515      }
114516      rc = SQLITE_NOMEM;
114517      goto offsets_out;
114518    }
114519
114520    /* Initialize a tokenizer iterator to iterate through column iCol. */
114521    rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114522    if( rc!=SQLITE_OK ) goto offsets_out;
114523    pC->pTokenizer = pTab->pTokenizer;
114524
114525    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114526    while( rc==SQLITE_OK ){
114527      int i;                      /* Used to loop through terms */
114528      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
114529      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
114530
114531      for(i=0; i<nToken; i++){
114532        TermOffset *pT = &sCtx.aTerm[i];
114533        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
114534          iMinPos = pT->iPos-pT->iOff;
114535          pTerm = pT;
114536        }
114537      }
114538
114539      if( !pTerm ){
114540        /* All offsets for this column have been gathered. */
114541        break;
114542      }else{
114543        assert( iCurrent<=iMinPos );
114544        if( 0==(0xFE&*pTerm->pList) ){
114545          pTerm->pList = 0;
114546        }else{
114547          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
114548        }
114549        while( rc==SQLITE_OK && iCurrent<iMinPos ){
114550          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114551        }
114552        if( rc==SQLITE_OK ){
114553          char aBuffer[64];
114554          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
114555              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
114556          );
114557          rc = fts3StringAppend(&res, aBuffer, -1);
114558        }else if( rc==SQLITE_DONE ){
114559          rc = SQLITE_CORRUPT;
114560        }
114561      }
114562    }
114563    if( rc==SQLITE_DONE ){
114564      rc = SQLITE_OK;
114565    }
114566
114567    pMod->xClose(pC);
114568    if( rc!=SQLITE_OK ) goto offsets_out;
114569  }
114570
114571 offsets_out:
114572  sqlite3_free(sCtx.aTerm);
114573  assert( rc!=SQLITE_DONE );
114574  if( rc!=SQLITE_OK ){
114575    sqlite3_result_error_code(pCtx,  rc);
114576    sqlite3_free(res.z);
114577  }else{
114578    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
114579  }
114580  return;
114581}
114582
114583/*
114584** Implementation of matchinfo() function.
114585*/
114586SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
114587  int rc;
114588  if( !pCsr->pExpr ){
114589    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
114590    return;
114591  }
114592  rc = fts3GetMatchinfo(pCsr);
114593  if( rc!=SQLITE_OK ){
114594    sqlite3_result_error_code(pContext, rc);
114595  }else{
114596    Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
114597    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
114598    if( pTab->bHasDocsize ){
114599      n += sizeof(u32)*(1 + 2*pTab->nColumn);
114600    }
114601    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
114602  }
114603}
114604
114605#endif
114606
114607/************** End of fts3_snippet.c ****************************************/
114608/************** Begin file rtree.c *******************************************/
114609/*
114610** 2001 September 15
114611**
114612** The author disclaims copyright to this source code.  In place of
114613** a legal notice, here is a blessing:
114614**
114615**    May you do good and not evil.
114616**    May you find forgiveness for yourself and forgive others.
114617**    May you share freely, never taking more than you give.
114618**
114619*************************************************************************
114620** This file contains code for implementations of the r-tree and r*-tree
114621** algorithms packaged as an SQLite virtual table module.
114622*/
114623
114624#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
114625
114626/*
114627** This file contains an implementation of a couple of different variants
114628** of the r-tree algorithm. See the README file for further details. The
114629** same data-structure is used for all, but the algorithms for insert and
114630** delete operations vary. The variants used are selected at compile time
114631** by defining the following symbols:
114632*/
114633
114634/* Either, both or none of the following may be set to activate
114635** r*tree variant algorithms.
114636*/
114637#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
114638#define VARIANT_RSTARTREE_REINSERT      1
114639
114640/*
114641** Exactly one of the following must be set to 1.
114642*/
114643#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
114644#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
114645#define VARIANT_RSTARTREE_SPLIT         1
114646
114647#define VARIANT_GUTTMAN_SPLIT \
114648        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
114649
114650#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
114651  #define PickNext QuadraticPickNext
114652  #define PickSeeds QuadraticPickSeeds
114653  #define AssignCells splitNodeGuttman
114654#endif
114655#if VARIANT_GUTTMAN_LINEAR_SPLIT
114656  #define PickNext LinearPickNext
114657  #define PickSeeds LinearPickSeeds
114658  #define AssignCells splitNodeGuttman
114659#endif
114660#if VARIANT_RSTARTREE_SPLIT
114661  #define AssignCells splitNodeStartree
114662#endif
114663
114664
114665#ifndef SQLITE_CORE
114666  SQLITE_EXTENSION_INIT1
114667#else
114668#endif
114669
114670
114671#ifndef SQLITE_AMALGAMATION
114672typedef sqlite3_int64 i64;
114673typedef unsigned char u8;
114674typedef unsigned int u32;
114675#endif
114676
114677typedef struct Rtree Rtree;
114678typedef struct RtreeCursor RtreeCursor;
114679typedef struct RtreeNode RtreeNode;
114680typedef struct RtreeCell RtreeCell;
114681typedef struct RtreeConstraint RtreeConstraint;
114682typedef union RtreeCoord RtreeCoord;
114683
114684/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
114685#define RTREE_MAX_DIMENSIONS 5
114686
114687/* Size of hash table Rtree.aHash. This hash table is not expected to
114688** ever contain very many entries, so a fixed number of buckets is
114689** used.
114690*/
114691#define HASHSIZE 128
114692
114693/*
114694** An rtree virtual-table object.
114695*/
114696struct Rtree {
114697  sqlite3_vtab base;
114698  sqlite3 *db;                /* Host database connection */
114699  int iNodeSize;              /* Size in bytes of each node in the node table */
114700  int nDim;                   /* Number of dimensions */
114701  int nBytesPerCell;          /* Bytes consumed per cell */
114702  int iDepth;                 /* Current depth of the r-tree structure */
114703  char *zDb;                  /* Name of database containing r-tree table */
114704  char *zName;                /* Name of r-tree table */
114705  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
114706  int nBusy;                  /* Current number of users of this structure */
114707
114708  /* List of nodes removed during a CondenseTree operation. List is
114709  ** linked together via the pointer normally used for hash chains -
114710  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
114711  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
114712  */
114713  RtreeNode *pDeleted;
114714  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
114715
114716  /* Statements to read/write/delete a record from xxx_node */
114717  sqlite3_stmt *pReadNode;
114718  sqlite3_stmt *pWriteNode;
114719  sqlite3_stmt *pDeleteNode;
114720
114721  /* Statements to read/write/delete a record from xxx_rowid */
114722  sqlite3_stmt *pReadRowid;
114723  sqlite3_stmt *pWriteRowid;
114724  sqlite3_stmt *pDeleteRowid;
114725
114726  /* Statements to read/write/delete a record from xxx_parent */
114727  sqlite3_stmt *pReadParent;
114728  sqlite3_stmt *pWriteParent;
114729  sqlite3_stmt *pDeleteParent;
114730
114731  int eCoordType;
114732};
114733
114734/* Possible values for eCoordType: */
114735#define RTREE_COORD_REAL32 0
114736#define RTREE_COORD_INT32  1
114737
114738/*
114739** The minimum number of cells allowed for a node is a third of the
114740** maximum. In Gutman's notation:
114741**
114742**     m = M/3
114743**
114744** If an R*-tree "Reinsert" operation is required, the same number of
114745** cells are removed from the overfull node and reinserted into the tree.
114746*/
114747#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
114748#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
114749#define RTREE_MAXCELLS 51
114750
114751/*
114752** An rtree cursor object.
114753*/
114754struct RtreeCursor {
114755  sqlite3_vtab_cursor base;
114756  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
114757  int iCell;                        /* Index of current cell in pNode */
114758  int iStrategy;                    /* Copy of idxNum search parameter */
114759  int nConstraint;                  /* Number of entries in aConstraint */
114760  RtreeConstraint *aConstraint;     /* Search constraints. */
114761};
114762
114763union RtreeCoord {
114764  float f;
114765  int i;
114766};
114767
114768/*
114769** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
114770** formatted as a double. This macro assumes that local variable pRtree points
114771** to the Rtree structure associated with the RtreeCoord.
114772*/
114773#define DCOORD(coord) (                           \
114774  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
114775    ((double)coord.f) :                           \
114776    ((double)coord.i)                             \
114777)
114778
114779/*
114780** A search constraint.
114781*/
114782struct RtreeConstraint {
114783  int iCoord;                       /* Index of constrained coordinate */
114784  int op;                           /* Constraining operation */
114785  double rValue;                    /* Constraint value. */
114786};
114787
114788/* Possible values for RtreeConstraint.op */
114789#define RTREE_EQ 0x41
114790#define RTREE_LE 0x42
114791#define RTREE_LT 0x43
114792#define RTREE_GE 0x44
114793#define RTREE_GT 0x45
114794
114795/*
114796** An rtree structure node.
114797**
114798** Data format (RtreeNode.zData):
114799**
114800**   1. If the node is the root node (node 1), then the first 2 bytes
114801**      of the node contain the tree depth as a big-endian integer.
114802**      For non-root nodes, the first 2 bytes are left unused.
114803**
114804**   2. The next 2 bytes contain the number of entries currently
114805**      stored in the node.
114806**
114807**   3. The remainder of the node contains the node entries. Each entry
114808**      consists of a single 8-byte integer followed by an even number
114809**      of 4-byte coordinates. For leaf nodes the integer is the rowid
114810**      of a record. For internal nodes it is the node number of a
114811**      child page.
114812*/
114813struct RtreeNode {
114814  RtreeNode *pParent;               /* Parent node */
114815  i64 iNode;
114816  int nRef;
114817  int isDirty;
114818  u8 *zData;
114819  RtreeNode *pNext;                 /* Next node in this hash chain */
114820};
114821#define NCELL(pNode) readInt16(&(pNode)->zData[2])
114822
114823/*
114824** Structure to store a deserialized rtree record.
114825*/
114826struct RtreeCell {
114827  i64 iRowid;
114828  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
114829};
114830
114831#ifndef MAX
114832# define MAX(x,y) ((x) < (y) ? (y) : (x))
114833#endif
114834#ifndef MIN
114835# define MIN(x,y) ((x) > (y) ? (y) : (x))
114836#endif
114837
114838/*
114839** Functions to deserialize a 16 bit integer, 32 bit real number and
114840** 64 bit integer. The deserialized value is returned.
114841*/
114842static int readInt16(u8 *p){
114843  return (p[0]<<8) + p[1];
114844}
114845static void readCoord(u8 *p, RtreeCoord *pCoord){
114846  u32 i = (
114847    (((u32)p[0]) << 24) +
114848    (((u32)p[1]) << 16) +
114849    (((u32)p[2]) <<  8) +
114850    (((u32)p[3]) <<  0)
114851  );
114852  *(u32 *)pCoord = i;
114853}
114854static i64 readInt64(u8 *p){
114855  return (
114856    (((i64)p[0]) << 56) +
114857    (((i64)p[1]) << 48) +
114858    (((i64)p[2]) << 40) +
114859    (((i64)p[3]) << 32) +
114860    (((i64)p[4]) << 24) +
114861    (((i64)p[5]) << 16) +
114862    (((i64)p[6]) <<  8) +
114863    (((i64)p[7]) <<  0)
114864  );
114865}
114866
114867/*
114868** Functions to serialize a 16 bit integer, 32 bit real number and
114869** 64 bit integer. The value returned is the number of bytes written
114870** to the argument buffer (always 2, 4 and 8 respectively).
114871*/
114872static int writeInt16(u8 *p, int i){
114873  p[0] = (i>> 8)&0xFF;
114874  p[1] = (i>> 0)&0xFF;
114875  return 2;
114876}
114877static int writeCoord(u8 *p, RtreeCoord *pCoord){
114878  u32 i;
114879  assert( sizeof(RtreeCoord)==4 );
114880  assert( sizeof(u32)==4 );
114881  i = *(u32 *)pCoord;
114882  p[0] = (i>>24)&0xFF;
114883  p[1] = (i>>16)&0xFF;
114884  p[2] = (i>> 8)&0xFF;
114885  p[3] = (i>> 0)&0xFF;
114886  return 4;
114887}
114888static int writeInt64(u8 *p, i64 i){
114889  p[0] = (i>>56)&0xFF;
114890  p[1] = (i>>48)&0xFF;
114891  p[2] = (i>>40)&0xFF;
114892  p[3] = (i>>32)&0xFF;
114893  p[4] = (i>>24)&0xFF;
114894  p[5] = (i>>16)&0xFF;
114895  p[6] = (i>> 8)&0xFF;
114896  p[7] = (i>> 0)&0xFF;
114897  return 8;
114898}
114899
114900/*
114901** Increment the reference count of node p.
114902*/
114903static void nodeReference(RtreeNode *p){
114904  if( p ){
114905    p->nRef++;
114906  }
114907}
114908
114909/*
114910** Clear the content of node p (set all bytes to 0x00).
114911*/
114912static void nodeZero(Rtree *pRtree, RtreeNode *p){
114913  if( p ){
114914    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
114915    p->isDirty = 1;
114916  }
114917}
114918
114919/*
114920** Given a node number iNode, return the corresponding key to use
114921** in the Rtree.aHash table.
114922*/
114923static int nodeHash(i64 iNode){
114924  return (
114925    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
114926    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
114927  ) % HASHSIZE;
114928}
114929
114930/*
114931** Search the node hash table for node iNode. If found, return a pointer
114932** to it. Otherwise, return 0.
114933*/
114934static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
114935  RtreeNode *p;
114936  assert( iNode!=0 );
114937  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
114938  return p;
114939}
114940
114941/*
114942** Add node pNode to the node hash table.
114943*/
114944static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
114945  if( pNode ){
114946    int iHash;
114947    assert( pNode->pNext==0 );
114948    iHash = nodeHash(pNode->iNode);
114949    pNode->pNext = pRtree->aHash[iHash];
114950    pRtree->aHash[iHash] = pNode;
114951  }
114952}
114953
114954/*
114955** Remove node pNode from the node hash table.
114956*/
114957static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
114958  RtreeNode **pp;
114959  if( pNode->iNode!=0 ){
114960    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
114961    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
114962    *pp = pNode->pNext;
114963    pNode->pNext = 0;
114964  }
114965}
114966
114967/*
114968** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
114969** indicating that node has not yet been assigned a node number. It is
114970** assigned a node number when nodeWrite() is called to write the
114971** node contents out to the database.
114972*/
114973static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
114974  RtreeNode *pNode;
114975  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
114976  if( pNode ){
114977    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
114978    pNode->zData = (u8 *)&pNode[1];
114979    pNode->nRef = 1;
114980    pNode->pParent = pParent;
114981    pNode->isDirty = 1;
114982    nodeReference(pParent);
114983  }
114984  return pNode;
114985}
114986
114987/*
114988** Obtain a reference to an r-tree node.
114989*/
114990static int
114991nodeAcquire(
114992  Rtree *pRtree,             /* R-tree structure */
114993  i64 iNode,                 /* Node number to load */
114994  RtreeNode *pParent,        /* Either the parent node or NULL */
114995  RtreeNode **ppNode         /* OUT: Acquired node */
114996){
114997  int rc;
114998  RtreeNode *pNode;
114999
115000  /* Check if the requested node is already in the hash table. If so,
115001  ** increase its reference count and return it.
115002  */
115003  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
115004    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
115005    if( pParent && !pNode->pParent ){
115006      nodeReference(pParent);
115007      pNode->pParent = pParent;
115008    }
115009    pNode->nRef++;
115010    *ppNode = pNode;
115011    return SQLITE_OK;
115012  }
115013
115014  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
115015  if( !pNode ){
115016    *ppNode = 0;
115017    return SQLITE_NOMEM;
115018  }
115019  pNode->pParent = pParent;
115020  pNode->zData = (u8 *)&pNode[1];
115021  pNode->nRef = 1;
115022  pNode->iNode = iNode;
115023  pNode->isDirty = 0;
115024  pNode->pNext = 0;
115025
115026  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
115027  rc = sqlite3_step(pRtree->pReadNode);
115028  if( rc==SQLITE_ROW ){
115029    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
115030    assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
115031    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
115032    nodeReference(pParent);
115033  }else{
115034    sqlite3_free(pNode);
115035    pNode = 0;
115036  }
115037
115038  *ppNode = pNode;
115039  rc = sqlite3_reset(pRtree->pReadNode);
115040
115041  if( rc==SQLITE_OK && iNode==1 ){
115042    pRtree->iDepth = readInt16(pNode->zData);
115043  }
115044
115045  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
115046  nodeHashInsert(pRtree, pNode);
115047
115048  return rc;
115049}
115050
115051/*
115052** Overwrite cell iCell of node pNode with the contents of pCell.
115053*/
115054static void nodeOverwriteCell(
115055  Rtree *pRtree,
115056  RtreeNode *pNode,
115057  RtreeCell *pCell,
115058  int iCell
115059){
115060  int ii;
115061  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115062  p += writeInt64(p, pCell->iRowid);
115063  for(ii=0; ii<(pRtree->nDim*2); ii++){
115064    p += writeCoord(p, &pCell->aCoord[ii]);
115065  }
115066  pNode->isDirty = 1;
115067}
115068
115069/*
115070** Remove cell the cell with index iCell from node pNode.
115071*/
115072static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
115073  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115074  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
115075  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
115076  memmove(pDst, pSrc, nByte);
115077  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
115078  pNode->isDirty = 1;
115079}
115080
115081/*
115082** Insert the contents of cell pCell into node pNode. If the insert
115083** is successful, return SQLITE_OK.
115084**
115085** If there is not enough free space in pNode, return SQLITE_FULL.
115086*/
115087static int
115088nodeInsertCell(
115089  Rtree *pRtree,
115090  RtreeNode *pNode,
115091  RtreeCell *pCell
115092){
115093  int nCell;                    /* Current number of cells in pNode */
115094  int nMaxCell;                 /* Maximum number of cells for pNode */
115095
115096  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
115097  nCell = NCELL(pNode);
115098
115099  assert(nCell<=nMaxCell);
115100
115101  if( nCell<nMaxCell ){
115102    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
115103    writeInt16(&pNode->zData[2], nCell+1);
115104    pNode->isDirty = 1;
115105  }
115106
115107  return (nCell==nMaxCell);
115108}
115109
115110/*
115111** If the node is dirty, write it out to the database.
115112*/
115113static int
115114nodeWrite(Rtree *pRtree, RtreeNode *pNode){
115115  int rc = SQLITE_OK;
115116  if( pNode->isDirty ){
115117    sqlite3_stmt *p = pRtree->pWriteNode;
115118    if( pNode->iNode ){
115119      sqlite3_bind_int64(p, 1, pNode->iNode);
115120    }else{
115121      sqlite3_bind_null(p, 1);
115122    }
115123    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
115124    sqlite3_step(p);
115125    pNode->isDirty = 0;
115126    rc = sqlite3_reset(p);
115127    if( pNode->iNode==0 && rc==SQLITE_OK ){
115128      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
115129      nodeHashInsert(pRtree, pNode);
115130    }
115131  }
115132  return rc;
115133}
115134
115135/*
115136** Release a reference to a node. If the node is dirty and the reference
115137** count drops to zero, the node data is written to the database.
115138*/
115139static int
115140nodeRelease(Rtree *pRtree, RtreeNode *pNode){
115141  int rc = SQLITE_OK;
115142  if( pNode ){
115143    assert( pNode->nRef>0 );
115144    pNode->nRef--;
115145    if( pNode->nRef==0 ){
115146      if( pNode->iNode==1 ){
115147        pRtree->iDepth = -1;
115148      }
115149      if( pNode->pParent ){
115150        rc = nodeRelease(pRtree, pNode->pParent);
115151      }
115152      if( rc==SQLITE_OK ){
115153        rc = nodeWrite(pRtree, pNode);
115154      }
115155      nodeHashDelete(pRtree, pNode);
115156      sqlite3_free(pNode);
115157    }
115158  }
115159  return rc;
115160}
115161
115162/*
115163** Return the 64-bit integer value associated with cell iCell of
115164** node pNode. If pNode is a leaf node, this is a rowid. If it is
115165** an internal node, then the 64-bit integer is a child page number.
115166*/
115167static i64 nodeGetRowid(
115168  Rtree *pRtree,
115169  RtreeNode *pNode,
115170  int iCell
115171){
115172  assert( iCell<NCELL(pNode) );
115173  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
115174}
115175
115176/*
115177** Return coordinate iCoord from cell iCell in node pNode.
115178*/
115179static void nodeGetCoord(
115180  Rtree *pRtree,
115181  RtreeNode *pNode,
115182  int iCell,
115183  int iCoord,
115184  RtreeCoord *pCoord           /* Space to write result to */
115185){
115186  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
115187}
115188
115189/*
115190** Deserialize cell iCell of node pNode. Populate the structure pointed
115191** to by pCell with the results.
115192*/
115193static void nodeGetCell(
115194  Rtree *pRtree,
115195  RtreeNode *pNode,
115196  int iCell,
115197  RtreeCell *pCell
115198){
115199  int ii;
115200  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
115201  for(ii=0; ii<pRtree->nDim*2; ii++){
115202    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
115203  }
115204}
115205
115206
115207/* Forward declaration for the function that does the work of
115208** the virtual table module xCreate() and xConnect() methods.
115209*/
115210static int rtreeInit(
115211  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
115212);
115213
115214/*
115215** Rtree virtual table module xCreate method.
115216*/
115217static int rtreeCreate(
115218  sqlite3 *db,
115219  void *pAux,
115220  int argc, const char *const*argv,
115221  sqlite3_vtab **ppVtab,
115222  char **pzErr
115223){
115224  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
115225}
115226
115227/*
115228** Rtree virtual table module xConnect method.
115229*/
115230static int rtreeConnect(
115231  sqlite3 *db,
115232  void *pAux,
115233  int argc, const char *const*argv,
115234  sqlite3_vtab **ppVtab,
115235  char **pzErr
115236){
115237  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
115238}
115239
115240/*
115241** Increment the r-tree reference count.
115242*/
115243static void rtreeReference(Rtree *pRtree){
115244  pRtree->nBusy++;
115245}
115246
115247/*
115248** Decrement the r-tree reference count. When the reference count reaches
115249** zero the structure is deleted.
115250*/
115251static void rtreeRelease(Rtree *pRtree){
115252  pRtree->nBusy--;
115253  if( pRtree->nBusy==0 ){
115254    sqlite3_finalize(pRtree->pReadNode);
115255    sqlite3_finalize(pRtree->pWriteNode);
115256    sqlite3_finalize(pRtree->pDeleteNode);
115257    sqlite3_finalize(pRtree->pReadRowid);
115258    sqlite3_finalize(pRtree->pWriteRowid);
115259    sqlite3_finalize(pRtree->pDeleteRowid);
115260    sqlite3_finalize(pRtree->pReadParent);
115261    sqlite3_finalize(pRtree->pWriteParent);
115262    sqlite3_finalize(pRtree->pDeleteParent);
115263    sqlite3_free(pRtree);
115264  }
115265}
115266
115267/*
115268** Rtree virtual table module xDisconnect method.
115269*/
115270static int rtreeDisconnect(sqlite3_vtab *pVtab){
115271  rtreeRelease((Rtree *)pVtab);
115272  return SQLITE_OK;
115273}
115274
115275/*
115276** Rtree virtual table module xDestroy method.
115277*/
115278static int rtreeDestroy(sqlite3_vtab *pVtab){
115279  Rtree *pRtree = (Rtree *)pVtab;
115280  int rc;
115281  char *zCreate = sqlite3_mprintf(
115282    "DROP TABLE '%q'.'%q_node';"
115283    "DROP TABLE '%q'.'%q_rowid';"
115284    "DROP TABLE '%q'.'%q_parent';",
115285    pRtree->zDb, pRtree->zName,
115286    pRtree->zDb, pRtree->zName,
115287    pRtree->zDb, pRtree->zName
115288  );
115289  if( !zCreate ){
115290    rc = SQLITE_NOMEM;
115291  }else{
115292    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
115293    sqlite3_free(zCreate);
115294  }
115295  if( rc==SQLITE_OK ){
115296    rtreeRelease(pRtree);
115297  }
115298
115299  return rc;
115300}
115301
115302/*
115303** Rtree virtual table module xOpen method.
115304*/
115305static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
115306  int rc = SQLITE_NOMEM;
115307  RtreeCursor *pCsr;
115308
115309  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
115310  if( pCsr ){
115311    memset(pCsr, 0, sizeof(RtreeCursor));
115312    pCsr->base.pVtab = pVTab;
115313    rc = SQLITE_OK;
115314  }
115315  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
115316
115317  return rc;
115318}
115319
115320/*
115321** Rtree virtual table module xClose method.
115322*/
115323static int rtreeClose(sqlite3_vtab_cursor *cur){
115324  Rtree *pRtree = (Rtree *)(cur->pVtab);
115325  int rc;
115326  RtreeCursor *pCsr = (RtreeCursor *)cur;
115327  sqlite3_free(pCsr->aConstraint);
115328  rc = nodeRelease(pRtree, pCsr->pNode);
115329  sqlite3_free(pCsr);
115330  return rc;
115331}
115332
115333/*
115334** Rtree virtual table module xEof method.
115335**
115336** Return non-zero if the cursor does not currently point to a valid
115337** record (i.e if the scan has finished), or zero otherwise.
115338*/
115339static int rtreeEof(sqlite3_vtab_cursor *cur){
115340  RtreeCursor *pCsr = (RtreeCursor *)cur;
115341  return (pCsr->pNode==0);
115342}
115343
115344/*
115345** Cursor pCursor currently points to a cell in a non-leaf page.
115346** Return true if the sub-tree headed by the cell is filtered
115347** (excluded) by the constraints in the pCursor->aConstraint[]
115348** array, or false otherwise.
115349*/
115350static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
115351  RtreeCell cell;
115352  int ii;
115353  int bRes = 0;
115354
115355  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115356  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
115357    RtreeConstraint *p = &pCursor->aConstraint[ii];
115358    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
115359    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
115360
115361    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
115362        || p->op==RTREE_GT || p->op==RTREE_EQ
115363    );
115364
115365    switch( p->op ){
115366      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
115367      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
115368      case RTREE_EQ:
115369        bRes = (p->rValue>cell_max || p->rValue<cell_min);
115370        break;
115371    }
115372  }
115373
115374  return bRes;
115375}
115376
115377/*
115378** Return true if the cell that cursor pCursor currently points to
115379** would be filtered (excluded) by the constraints in the
115380** pCursor->aConstraint[] array, or false otherwise.
115381**
115382** This function assumes that the cell is part of a leaf node.
115383*/
115384static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
115385  RtreeCell cell;
115386  int ii;
115387
115388  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115389  for(ii=0; ii<pCursor->nConstraint; ii++){
115390    RtreeConstraint *p = &pCursor->aConstraint[ii];
115391    double coord = DCOORD(cell.aCoord[p->iCoord]);
115392    int res;
115393    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
115394        || p->op==RTREE_GT || p->op==RTREE_EQ
115395    );
115396    switch( p->op ){
115397      case RTREE_LE: res = (coord<=p->rValue); break;
115398      case RTREE_LT: res = (coord<p->rValue);  break;
115399      case RTREE_GE: res = (coord>=p->rValue); break;
115400      case RTREE_GT: res = (coord>p->rValue);  break;
115401      case RTREE_EQ: res = (coord==p->rValue); break;
115402    }
115403
115404    if( !res ) return 1;
115405  }
115406
115407  return 0;
115408}
115409
115410/*
115411** Cursor pCursor currently points at a node that heads a sub-tree of
115412** height iHeight (if iHeight==0, then the node is a leaf). Descend
115413** to point to the left-most cell of the sub-tree that matches the
115414** configured constraints.
115415*/
115416static int descendToCell(
115417  Rtree *pRtree,
115418  RtreeCursor *pCursor,
115419  int iHeight,
115420  int *pEof                 /* OUT: Set to true if cannot descend */
115421){
115422  int isEof;
115423  int rc;
115424  int ii;
115425  RtreeNode *pChild;
115426  sqlite3_int64 iRowid;
115427
115428  RtreeNode *pSavedNode = pCursor->pNode;
115429  int iSavedCell = pCursor->iCell;
115430
115431  assert( iHeight>=0 );
115432
115433  if( iHeight==0 ){
115434    isEof = testRtreeEntry(pRtree, pCursor);
115435  }else{
115436    isEof = testRtreeCell(pRtree, pCursor);
115437  }
115438  if( isEof || iHeight==0 ){
115439    *pEof = isEof;
115440    return SQLITE_OK;
115441  }
115442
115443  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
115444  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
115445  if( rc!=SQLITE_OK ){
115446    return rc;
115447  }
115448
115449  nodeRelease(pRtree, pCursor->pNode);
115450  pCursor->pNode = pChild;
115451  isEof = 1;
115452  for(ii=0; isEof && ii<NCELL(pChild); ii++){
115453    pCursor->iCell = ii;
115454    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
115455    if( rc!=SQLITE_OK ){
115456      return rc;
115457    }
115458  }
115459
115460  if( isEof ){
115461    assert( pCursor->pNode==pChild );
115462    nodeReference(pSavedNode);
115463    nodeRelease(pRtree, pChild);
115464    pCursor->pNode = pSavedNode;
115465    pCursor->iCell = iSavedCell;
115466  }
115467
115468  *pEof = isEof;
115469  return SQLITE_OK;
115470}
115471
115472/*
115473** One of the cells in node pNode is guaranteed to have a 64-bit
115474** integer value equal to iRowid. Return the index of this cell.
115475*/
115476static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
115477  int ii;
115478  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
115479    assert( ii<(NCELL(pNode)-1) );
115480  }
115481  return ii;
115482}
115483
115484/*
115485** Return the index of the cell containing a pointer to node pNode
115486** in its parent. If pNode is the root node, return -1.
115487*/
115488static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
115489  RtreeNode *pParent = pNode->pParent;
115490  if( pParent ){
115491    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
115492  }
115493  return -1;
115494}
115495
115496/*
115497** Rtree virtual table module xNext method.
115498*/
115499static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
115500  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
115501  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115502  int rc = SQLITE_OK;
115503
115504  if( pCsr->iStrategy==1 ){
115505    /* This "scan" is a direct lookup by rowid. There is no next entry. */
115506    nodeRelease(pRtree, pCsr->pNode);
115507    pCsr->pNode = 0;
115508  }
115509
115510  else if( pCsr->pNode ){
115511    /* Move to the next entry that matches the configured constraints. */
115512    int iHeight = 0;
115513    while( pCsr->pNode ){
115514      RtreeNode *pNode = pCsr->pNode;
115515      int nCell = NCELL(pNode);
115516      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
115517        int isEof;
115518        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
115519        if( rc!=SQLITE_OK || !isEof ){
115520          return rc;
115521        }
115522      }
115523      pCsr->pNode = pNode->pParent;
115524      pCsr->iCell = nodeParentIndex(pRtree, pNode);
115525      nodeReference(pCsr->pNode);
115526      nodeRelease(pRtree, pNode);
115527      iHeight++;
115528    }
115529  }
115530
115531  return rc;
115532}
115533
115534/*
115535** Rtree virtual table module xRowid method.
115536*/
115537static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
115538  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
115539  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115540
115541  assert(pCsr->pNode);
115542  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115543
115544  return SQLITE_OK;
115545}
115546
115547/*
115548** Rtree virtual table module xColumn method.
115549*/
115550static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
115551  Rtree *pRtree = (Rtree *)cur->pVtab;
115552  RtreeCursor *pCsr = (RtreeCursor *)cur;
115553
115554  if( i==0 ){
115555    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115556    sqlite3_result_int64(ctx, iRowid);
115557  }else{
115558    RtreeCoord c;
115559    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
115560    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
115561      sqlite3_result_double(ctx, c.f);
115562    }else{
115563      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
115564      sqlite3_result_int(ctx, c.i);
115565    }
115566  }
115567
115568  return SQLITE_OK;
115569}
115570
115571/*
115572** Use nodeAcquire() to obtain the leaf node containing the record with
115573** rowid iRowid. If successful, set *ppLeaf to point to the node and
115574** return SQLITE_OK. If there is no such record in the table, set
115575** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
115576** to zero and return an SQLite error code.
115577*/
115578static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
115579  int rc;
115580  *ppLeaf = 0;
115581  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
115582  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
115583    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
115584    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
115585    sqlite3_reset(pRtree->pReadRowid);
115586  }else{
115587    rc = sqlite3_reset(pRtree->pReadRowid);
115588  }
115589  return rc;
115590}
115591
115592
115593/*
115594** Rtree virtual table module xFilter method.
115595*/
115596static int rtreeFilter(
115597  sqlite3_vtab_cursor *pVtabCursor,
115598  int idxNum, const char *idxStr,
115599  int argc, sqlite3_value **argv
115600){
115601  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
115602  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115603
115604  RtreeNode *pRoot = 0;
115605  int ii;
115606  int rc = SQLITE_OK;
115607
115608  rtreeReference(pRtree);
115609
115610  sqlite3_free(pCsr->aConstraint);
115611  pCsr->aConstraint = 0;
115612  pCsr->iStrategy = idxNum;
115613
115614  if( idxNum==1 ){
115615    /* Special case - lookup by rowid. */
115616    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
115617    i64 iRowid = sqlite3_value_int64(argv[0]);
115618    rc = findLeafNode(pRtree, iRowid, &pLeaf);
115619    pCsr->pNode = pLeaf;
115620    if( pLeaf && rc==SQLITE_OK ){
115621      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
115622    }
115623  }else{
115624    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
115625    ** with the configured constraints.
115626    */
115627    if( argc>0 ){
115628      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
115629      pCsr->nConstraint = argc;
115630      if( !pCsr->aConstraint ){
115631        rc = SQLITE_NOMEM;
115632      }else{
115633        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
115634        for(ii=0; ii<argc; ii++){
115635          RtreeConstraint *p = &pCsr->aConstraint[ii];
115636          p->op = idxStr[ii*2];
115637          p->iCoord = idxStr[ii*2+1]-'a';
115638          p->rValue = sqlite3_value_double(argv[ii]);
115639        }
115640      }
115641    }
115642
115643    if( rc==SQLITE_OK ){
115644      pCsr->pNode = 0;
115645      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
115646    }
115647    if( rc==SQLITE_OK ){
115648      int isEof = 1;
115649      int nCell = NCELL(pRoot);
115650      pCsr->pNode = pRoot;
115651      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
115652        assert( pCsr->pNode==pRoot );
115653        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
115654        if( !isEof ){
115655          break;
115656        }
115657      }
115658      if( rc==SQLITE_OK && isEof ){
115659        assert( pCsr->pNode==pRoot );
115660        nodeRelease(pRtree, pRoot);
115661        pCsr->pNode = 0;
115662      }
115663      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
115664    }
115665  }
115666
115667  rtreeRelease(pRtree);
115668  return rc;
115669}
115670
115671/*
115672** Rtree virtual table module xBestIndex method. There are three
115673** table scan strategies to choose from (in order from most to
115674** least desirable):
115675**
115676**   idxNum     idxStr        Strategy
115677**   ------------------------------------------------
115678**     1        Unused        Direct lookup by rowid.
115679**     2        See below     R-tree query.
115680**     3        Unused        Full table scan.
115681**   ------------------------------------------------
115682**
115683** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
115684** 2 is used, idxStr is formatted to contain 2 bytes for each
115685** constraint used. The first two bytes of idxStr correspond to
115686** the constraint in sqlite3_index_info.aConstraintUsage[] with
115687** (argvIndex==1) etc.
115688**
115689** The first of each pair of bytes in idxStr identifies the constraint
115690** operator as follows:
115691**
115692**   Operator    Byte Value
115693**   ----------------------
115694**      =        0x41 ('A')
115695**     <=        0x42 ('B')
115696**      <        0x43 ('C')
115697**     >=        0x44 ('D')
115698**      >        0x45 ('E')
115699**   ----------------------
115700**
115701** The second of each pair of bytes identifies the coordinate column
115702** to which the constraint applies. The leftmost coordinate column
115703** is 'a', the second from the left 'b' etc.
115704*/
115705static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
115706  int rc = SQLITE_OK;
115707  int ii, cCol;
115708
115709  int iIdx = 0;
115710  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
115711  memset(zIdxStr, 0, sizeof(zIdxStr));
115712
115713  assert( pIdxInfo->idxStr==0 );
115714  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
115715    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
115716
115717    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
115718      /* We have an equality constraint on the rowid. Use strategy 1. */
115719      int jj;
115720      for(jj=0; jj<ii; jj++){
115721        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
115722        pIdxInfo->aConstraintUsage[jj].omit = 0;
115723      }
115724      pIdxInfo->idxNum = 1;
115725      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
115726      pIdxInfo->aConstraintUsage[jj].omit = 1;
115727
115728      /* This strategy involves a two rowid lookups on an B-Tree structures
115729      ** and then a linear search of an R-Tree node. This should be
115730      ** considered almost as quick as a direct rowid lookup (for which
115731      ** sqlite uses an internal cost of 0.0).
115732      */
115733      pIdxInfo->estimatedCost = 10.0;
115734      return SQLITE_OK;
115735    }
115736
115737    if( p->usable && p->iColumn>0 ){
115738      u8 op = 0;
115739      switch( p->op ){
115740        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
115741        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
115742        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
115743        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
115744        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
115745      }
115746      if( op ){
115747        /* Make sure this particular constraint has not been used before.
115748        ** If it has been used before, ignore it.
115749        **
115750        ** A <= or < can be used if there is a prior >= or >.
115751        ** A >= or > can be used if there is a prior < or <=.
115752        ** A <= or < is disqualified if there is a prior <=, <, or ==.
115753        ** A >= or > is disqualified if there is a prior >=, >, or ==.
115754        ** A == is disqualifed if there is any prior constraint.
115755        */
115756        int j, opmsk;
115757        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
115758        assert( compatible[RTREE_EQ & 7]==0 );
115759        assert( compatible[RTREE_LT & 7]==1 );
115760        assert( compatible[RTREE_LE & 7]==1 );
115761        assert( compatible[RTREE_GT & 7]==2 );
115762        assert( compatible[RTREE_GE & 7]==2 );
115763        cCol = p->iColumn - 1 + 'a';
115764        opmsk = compatible[op & 7];
115765        for(j=0; j<iIdx; j+=2){
115766          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
115767            op = 0;
115768            break;
115769          }
115770        }
115771      }
115772      if( op ){
115773        assert( iIdx<sizeof(zIdxStr)-1 );
115774        zIdxStr[iIdx++] = op;
115775        zIdxStr[iIdx++] = cCol;
115776        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
115777        pIdxInfo->aConstraintUsage[ii].omit = 1;
115778      }
115779    }
115780  }
115781
115782  pIdxInfo->idxNum = 2;
115783  pIdxInfo->needToFreeIdxStr = 1;
115784  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
115785    return SQLITE_NOMEM;
115786  }
115787  assert( iIdx>=0 );
115788  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
115789  return rc;
115790}
115791
115792/*
115793** Return the N-dimensional volumn of the cell stored in *p.
115794*/
115795static float cellArea(Rtree *pRtree, RtreeCell *p){
115796  float area = 1.0;
115797  int ii;
115798  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
115799    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
115800  }
115801  return area;
115802}
115803
115804/*
115805** Return the margin length of cell p. The margin length is the sum
115806** of the objects size in each dimension.
115807*/
115808static float cellMargin(Rtree *pRtree, RtreeCell *p){
115809  float margin = 0.0;
115810  int ii;
115811  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
115812    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
115813  }
115814  return margin;
115815}
115816
115817/*
115818** Store the union of cells p1 and p2 in p1.
115819*/
115820static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
115821  int ii;
115822  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
115823    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
115824      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
115825      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
115826    }
115827  }else{
115828    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
115829      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
115830      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
115831    }
115832  }
115833}
115834
115835/*
115836** Return true if the area covered by p2 is a subset of the area covered
115837** by p1. False otherwise.
115838*/
115839static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
115840  int ii;
115841  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
115842  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
115843    RtreeCoord *a1 = &p1->aCoord[ii];
115844    RtreeCoord *a2 = &p2->aCoord[ii];
115845    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
115846     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
115847    ){
115848      return 0;
115849    }
115850  }
115851  return 1;
115852}
115853
115854/*
115855** Return the amount cell p would grow by if it were unioned with pCell.
115856*/
115857static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
115858  float area;
115859  RtreeCell cell;
115860  memcpy(&cell, p, sizeof(RtreeCell));
115861  area = cellArea(pRtree, &cell);
115862  cellUnion(pRtree, &cell, pCell);
115863  return (cellArea(pRtree, &cell)-area);
115864}
115865
115866#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
115867static float cellOverlap(
115868  Rtree *pRtree,
115869  RtreeCell *p,
115870  RtreeCell *aCell,
115871  int nCell,
115872  int iExclude
115873){
115874  int ii;
115875  float overlap = 0.0;
115876  for(ii=0; ii<nCell; ii++){
115877    if( ii!=iExclude ){
115878      int jj;
115879      float o = 1.0;
115880      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
115881        double x1;
115882        double x2;
115883
115884        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
115885        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
115886
115887        if( x2<x1 ){
115888          o = 0.0;
115889          break;
115890        }else{
115891          o = o * (x2-x1);
115892        }
115893      }
115894      overlap += o;
115895    }
115896  }
115897  return overlap;
115898}
115899#endif
115900
115901#if VARIANT_RSTARTREE_CHOOSESUBTREE
115902static float cellOverlapEnlargement(
115903  Rtree *pRtree,
115904  RtreeCell *p,
115905  RtreeCell *pInsert,
115906  RtreeCell *aCell,
115907  int nCell,
115908  int iExclude
115909){
115910  float before;
115911  float after;
115912  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
115913  cellUnion(pRtree, p, pInsert);
115914  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
115915  return after-before;
115916}
115917#endif
115918
115919
115920/*
115921** This function implements the ChooseLeaf algorithm from Gutman[84].
115922** ChooseSubTree in r*tree terminology.
115923*/
115924static int ChooseLeaf(
115925  Rtree *pRtree,               /* Rtree table */
115926  RtreeCell *pCell,            /* Cell to insert into rtree */
115927  int iHeight,                 /* Height of sub-tree rooted at pCell */
115928  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
115929){
115930  int rc;
115931  int ii;
115932  RtreeNode *pNode;
115933  rc = nodeAcquire(pRtree, 1, 0, &pNode);
115934
115935  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
115936    int iCell;
115937    sqlite3_int64 iBest;
115938
115939    float fMinGrowth;
115940    float fMinArea;
115941    float fMinOverlap;
115942
115943    int nCell = NCELL(pNode);
115944    RtreeCell cell;
115945    RtreeNode *pChild;
115946
115947    RtreeCell *aCell = 0;
115948
115949#if VARIANT_RSTARTREE_CHOOSESUBTREE
115950    if( ii==(pRtree->iDepth-1) ){
115951      int jj;
115952      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
115953      if( !aCell ){
115954        rc = SQLITE_NOMEM;
115955        nodeRelease(pRtree, pNode);
115956        pNode = 0;
115957        continue;
115958      }
115959      for(jj=0; jj<nCell; jj++){
115960        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
115961      }
115962    }
115963#endif
115964
115965    /* Select the child node which will be enlarged the least if pCell
115966    ** is inserted into it. Resolve ties by choosing the entry with
115967    ** the smallest area.
115968    */
115969    for(iCell=0; iCell<nCell; iCell++){
115970      float growth;
115971      float area;
115972      float overlap = 0.0;
115973      nodeGetCell(pRtree, pNode, iCell, &cell);
115974      growth = cellGrowth(pRtree, &cell, pCell);
115975      area = cellArea(pRtree, &cell);
115976#if VARIANT_RSTARTREE_CHOOSESUBTREE
115977      if( ii==(pRtree->iDepth-1) ){
115978        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
115979      }
115980#endif
115981      if( (iCell==0)
115982       || (overlap<fMinOverlap)
115983       || (overlap==fMinOverlap && growth<fMinGrowth)
115984       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
115985      ){
115986        fMinOverlap = overlap;
115987        fMinGrowth = growth;
115988        fMinArea = area;
115989        iBest = cell.iRowid;
115990      }
115991    }
115992
115993    sqlite3_free(aCell);
115994    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
115995    nodeRelease(pRtree, pNode);
115996    pNode = pChild;
115997  }
115998
115999  *ppLeaf = pNode;
116000  return rc;
116001}
116002
116003/*
116004** A cell with the same content as pCell has just been inserted into
116005** the node pNode. This function updates the bounding box cells in
116006** all ancestor elements.
116007*/
116008static void AdjustTree(
116009  Rtree *pRtree,                    /* Rtree table */
116010  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
116011  RtreeCell *pCell                  /* This cell was just inserted */
116012){
116013  RtreeNode *p = pNode;
116014  while( p->pParent ){
116015    RtreeCell cell;
116016    RtreeNode *pParent = p->pParent;
116017    int iCell = nodeParentIndex(pRtree, p);
116018
116019    nodeGetCell(pRtree, pParent, iCell, &cell);
116020    if( !cellContains(pRtree, &cell, pCell) ){
116021      cellUnion(pRtree, &cell, pCell);
116022      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
116023    }
116024
116025    p = pParent;
116026  }
116027}
116028
116029/*
116030** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
116031*/
116032static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
116033  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
116034  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
116035  sqlite3_step(pRtree->pWriteRowid);
116036  return sqlite3_reset(pRtree->pWriteRowid);
116037}
116038
116039/*
116040** Write mapping (iNode->iPar) to the <rtree>_parent table.
116041*/
116042static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
116043  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
116044  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
116045  sqlite3_step(pRtree->pWriteParent);
116046  return sqlite3_reset(pRtree->pWriteParent);
116047}
116048
116049static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
116050
116051#if VARIANT_GUTTMAN_LINEAR_SPLIT
116052/*
116053** Implementation of the linear variant of the PickNext() function from
116054** Guttman[84].
116055*/
116056static RtreeCell *LinearPickNext(
116057  Rtree *pRtree,
116058  RtreeCell *aCell,
116059  int nCell,
116060  RtreeCell *pLeftBox,
116061  RtreeCell *pRightBox,
116062  int *aiUsed
116063){
116064  int ii;
116065  for(ii=0; aiUsed[ii]; ii++);
116066  aiUsed[ii] = 1;
116067  return &aCell[ii];
116068}
116069
116070/*
116071** Implementation of the linear variant of the PickSeeds() function from
116072** Guttman[84].
116073*/
116074static void LinearPickSeeds(
116075  Rtree *pRtree,
116076  RtreeCell *aCell,
116077  int nCell,
116078  int *piLeftSeed,
116079  int *piRightSeed
116080){
116081  int i;
116082  int iLeftSeed = 0;
116083  int iRightSeed = 1;
116084  float maxNormalInnerWidth = 0.0;
116085
116086  /* Pick two "seed" cells from the array of cells. The algorithm used
116087  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
116088  ** indices of the two seed cells in the array are stored in local
116089  ** variables iLeftSeek and iRightSeed.
116090  */
116091  for(i=0; i<pRtree->nDim; i++){
116092    float x1 = DCOORD(aCell[0].aCoord[i*2]);
116093    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
116094    float x3 = x1;
116095    float x4 = x2;
116096    int jj;
116097
116098    int iCellLeft = 0;
116099    int iCellRight = 0;
116100
116101    for(jj=1; jj<nCell; jj++){
116102      float left = DCOORD(aCell[jj].aCoord[i*2]);
116103      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
116104
116105      if( left<x1 ) x1 = left;
116106      if( right>x4 ) x4 = right;
116107      if( left>x3 ){
116108        x3 = left;
116109        iCellRight = jj;
116110      }
116111      if( right<x2 ){
116112        x2 = right;
116113        iCellLeft = jj;
116114      }
116115    }
116116
116117    if( x4!=x1 ){
116118      float normalwidth = (x3 - x2) / (x4 - x1);
116119      if( normalwidth>maxNormalInnerWidth ){
116120        iLeftSeed = iCellLeft;
116121        iRightSeed = iCellRight;
116122      }
116123    }
116124  }
116125
116126  *piLeftSeed = iLeftSeed;
116127  *piRightSeed = iRightSeed;
116128}
116129#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
116130
116131#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
116132/*
116133** Implementation of the quadratic variant of the PickNext() function from
116134** Guttman[84].
116135*/
116136static RtreeCell *QuadraticPickNext(
116137  Rtree *pRtree,
116138  RtreeCell *aCell,
116139  int nCell,
116140  RtreeCell *pLeftBox,
116141  RtreeCell *pRightBox,
116142  int *aiUsed
116143){
116144  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
116145
116146  int iSelect = -1;
116147  float fDiff;
116148  int ii;
116149  for(ii=0; ii<nCell; ii++){
116150    if( aiUsed[ii]==0 ){
116151      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116152      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116153      float diff = FABS(right-left);
116154      if( iSelect<0 || diff>fDiff ){
116155        fDiff = diff;
116156        iSelect = ii;
116157      }
116158    }
116159  }
116160  aiUsed[iSelect] = 1;
116161  return &aCell[iSelect];
116162}
116163
116164/*
116165** Implementation of the quadratic variant of the PickSeeds() function from
116166** Guttman[84].
116167*/
116168static void QuadraticPickSeeds(
116169  Rtree *pRtree,
116170  RtreeCell *aCell,
116171  int nCell,
116172  int *piLeftSeed,
116173  int *piRightSeed
116174){
116175  int ii;
116176  int jj;
116177
116178  int iLeftSeed = 0;
116179  int iRightSeed = 1;
116180  float fWaste = 0.0;
116181
116182  for(ii=0; ii<nCell; ii++){
116183    for(jj=ii+1; jj<nCell; jj++){
116184      float right = cellArea(pRtree, &aCell[jj]);
116185      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
116186      float waste = growth - right;
116187
116188      if( waste>fWaste ){
116189        iLeftSeed = ii;
116190        iRightSeed = jj;
116191        fWaste = waste;
116192      }
116193    }
116194  }
116195
116196  *piLeftSeed = iLeftSeed;
116197  *piRightSeed = iRightSeed;
116198}
116199#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
116200
116201/*
116202** Arguments aIdx, aDistance and aSpare all point to arrays of size
116203** nIdx. The aIdx array contains the set of integers from 0 to
116204** (nIdx-1) in no particular order. This function sorts the values
116205** in aIdx according to the indexed values in aDistance. For
116206** example, assuming the inputs:
116207**
116208**   aIdx      = { 0,   1,   2,   3 }
116209**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
116210**
116211** this function sets the aIdx array to contain:
116212**
116213**   aIdx      = { 0,   1,   2,   3 }
116214**
116215** The aSpare array is used as temporary working space by the
116216** sorting algorithm.
116217*/
116218static void SortByDistance(
116219  int *aIdx,
116220  int nIdx,
116221  float *aDistance,
116222  int *aSpare
116223){
116224  if( nIdx>1 ){
116225    int iLeft = 0;
116226    int iRight = 0;
116227
116228    int nLeft = nIdx/2;
116229    int nRight = nIdx-nLeft;
116230    int *aLeft = aIdx;
116231    int *aRight = &aIdx[nLeft];
116232
116233    SortByDistance(aLeft, nLeft, aDistance, aSpare);
116234    SortByDistance(aRight, nRight, aDistance, aSpare);
116235
116236    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116237    aLeft = aSpare;
116238
116239    while( iLeft<nLeft || iRight<nRight ){
116240      if( iLeft==nLeft ){
116241        aIdx[iLeft+iRight] = aRight[iRight];
116242        iRight++;
116243      }else if( iRight==nRight ){
116244        aIdx[iLeft+iRight] = aLeft[iLeft];
116245        iLeft++;
116246      }else{
116247        float fLeft = aDistance[aLeft[iLeft]];
116248        float fRight = aDistance[aRight[iRight]];
116249        if( fLeft<fRight ){
116250          aIdx[iLeft+iRight] = aLeft[iLeft];
116251          iLeft++;
116252        }else{
116253          aIdx[iLeft+iRight] = aRight[iRight];
116254          iRight++;
116255        }
116256      }
116257    }
116258
116259#if 0
116260    /* Check that the sort worked */
116261    {
116262      int jj;
116263      for(jj=1; jj<nIdx; jj++){
116264        float left = aDistance[aIdx[jj-1]];
116265        float right = aDistance[aIdx[jj]];
116266        assert( left<=right );
116267      }
116268    }
116269#endif
116270  }
116271}
116272
116273/*
116274** Arguments aIdx, aCell and aSpare all point to arrays of size
116275** nIdx. The aIdx array contains the set of integers from 0 to
116276** (nIdx-1) in no particular order. This function sorts the values
116277** in aIdx according to dimension iDim of the cells in aCell. The
116278** minimum value of dimension iDim is considered first, the
116279** maximum used to break ties.
116280**
116281** The aSpare array is used as temporary working space by the
116282** sorting algorithm.
116283*/
116284static void SortByDimension(
116285  Rtree *pRtree,
116286  int *aIdx,
116287  int nIdx,
116288  int iDim,
116289  RtreeCell *aCell,
116290  int *aSpare
116291){
116292  if( nIdx>1 ){
116293
116294    int iLeft = 0;
116295    int iRight = 0;
116296
116297    int nLeft = nIdx/2;
116298    int nRight = nIdx-nLeft;
116299    int *aLeft = aIdx;
116300    int *aRight = &aIdx[nLeft];
116301
116302    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
116303    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
116304
116305    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116306    aLeft = aSpare;
116307    while( iLeft<nLeft || iRight<nRight ){
116308      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
116309      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
116310      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
116311      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
116312      if( (iLeft!=nLeft) && ((iRight==nRight)
116313       || (xleft1<xright1)
116314       || (xleft1==xright1 && xleft2<xright2)
116315      )){
116316        aIdx[iLeft+iRight] = aLeft[iLeft];
116317        iLeft++;
116318      }else{
116319        aIdx[iLeft+iRight] = aRight[iRight];
116320        iRight++;
116321      }
116322    }
116323
116324#if 0
116325    /* Check that the sort worked */
116326    {
116327      int jj;
116328      for(jj=1; jj<nIdx; jj++){
116329        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
116330        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
116331        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
116332        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
116333        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
116334      }
116335    }
116336#endif
116337  }
116338}
116339
116340#if VARIANT_RSTARTREE_SPLIT
116341/*
116342** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
116343*/
116344static int splitNodeStartree(
116345  Rtree *pRtree,
116346  RtreeCell *aCell,
116347  int nCell,
116348  RtreeNode *pLeft,
116349  RtreeNode *pRight,
116350  RtreeCell *pBboxLeft,
116351  RtreeCell *pBboxRight
116352){
116353  int **aaSorted;
116354  int *aSpare;
116355  int ii;
116356
116357  int iBestDim;
116358  int iBestSplit;
116359  float fBestMargin;
116360
116361  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
116362
116363  aaSorted = (int **)sqlite3_malloc(nByte);
116364  if( !aaSorted ){
116365    return SQLITE_NOMEM;
116366  }
116367
116368  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
116369  memset(aaSorted, 0, nByte);
116370  for(ii=0; ii<pRtree->nDim; ii++){
116371    int jj;
116372    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
116373    for(jj=0; jj<nCell; jj++){
116374      aaSorted[ii][jj] = jj;
116375    }
116376    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
116377  }
116378
116379  for(ii=0; ii<pRtree->nDim; ii++){
116380    float margin = 0.0;
116381    float fBestOverlap;
116382    float fBestArea;
116383    int iBestLeft;
116384    int nLeft;
116385
116386    for(
116387      nLeft=RTREE_MINCELLS(pRtree);
116388      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
116389      nLeft++
116390    ){
116391      RtreeCell left;
116392      RtreeCell right;
116393      int kk;
116394      float overlap;
116395      float area;
116396
116397      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
116398      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
116399      for(kk=1; kk<(nCell-1); kk++){
116400        if( kk<nLeft ){
116401          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
116402        }else{
116403          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
116404        }
116405      }
116406      margin += cellMargin(pRtree, &left);
116407      margin += cellMargin(pRtree, &right);
116408      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
116409      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
116410      if( (nLeft==RTREE_MINCELLS(pRtree))
116411       || (overlap<fBestOverlap)
116412       || (overlap==fBestOverlap && area<fBestArea)
116413      ){
116414        iBestLeft = nLeft;
116415        fBestOverlap = overlap;
116416        fBestArea = area;
116417      }
116418    }
116419
116420    if( ii==0 || margin<fBestMargin ){
116421      iBestDim = ii;
116422      fBestMargin = margin;
116423      iBestSplit = iBestLeft;
116424    }
116425  }
116426
116427  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
116428  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
116429  for(ii=0; ii<nCell; ii++){
116430    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
116431    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
116432    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
116433    nodeInsertCell(pRtree, pTarget, pCell);
116434    cellUnion(pRtree, pBbox, pCell);
116435  }
116436
116437  sqlite3_free(aaSorted);
116438  return SQLITE_OK;
116439}
116440#endif
116441
116442#if VARIANT_GUTTMAN_SPLIT
116443/*
116444** Implementation of the regular R-tree SplitNode from Guttman[1984].
116445*/
116446static int splitNodeGuttman(
116447  Rtree *pRtree,
116448  RtreeCell *aCell,
116449  int nCell,
116450  RtreeNode *pLeft,
116451  RtreeNode *pRight,
116452  RtreeCell *pBboxLeft,
116453  RtreeCell *pBboxRight
116454){
116455  int iLeftSeed = 0;
116456  int iRightSeed = 1;
116457  int *aiUsed;
116458  int i;
116459
116460  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
116461  if( !aiUsed ){
116462    return SQLITE_NOMEM;
116463  }
116464  memset(aiUsed, 0, sizeof(int)*nCell);
116465
116466  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
116467
116468  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
116469  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
116470  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
116471  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
116472  aiUsed[iLeftSeed] = 1;
116473  aiUsed[iRightSeed] = 1;
116474
116475  for(i=nCell-2; i>0; i--){
116476    RtreeCell *pNext;
116477    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
116478    float diff =
116479      cellGrowth(pRtree, pBboxLeft, pNext) -
116480      cellGrowth(pRtree, pBboxRight, pNext)
116481    ;
116482    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
116483     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
116484    ){
116485      nodeInsertCell(pRtree, pRight, pNext);
116486      cellUnion(pRtree, pBboxRight, pNext);
116487    }else{
116488      nodeInsertCell(pRtree, pLeft, pNext);
116489      cellUnion(pRtree, pBboxLeft, pNext);
116490    }
116491  }
116492
116493  sqlite3_free(aiUsed);
116494  return SQLITE_OK;
116495}
116496#endif
116497
116498static int updateMapping(
116499  Rtree *pRtree,
116500  i64 iRowid,
116501  RtreeNode *pNode,
116502  int iHeight
116503){
116504  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
116505  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
116506  if( iHeight>0 ){
116507    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
116508    if( pChild ){
116509      nodeRelease(pRtree, pChild->pParent);
116510      nodeReference(pNode);
116511      pChild->pParent = pNode;
116512    }
116513  }
116514  return xSetMapping(pRtree, iRowid, pNode->iNode);
116515}
116516
116517static int SplitNode(
116518  Rtree *pRtree,
116519  RtreeNode *pNode,
116520  RtreeCell *pCell,
116521  int iHeight
116522){
116523  int i;
116524  int newCellIsRight = 0;
116525
116526  int rc = SQLITE_OK;
116527  int nCell = NCELL(pNode);
116528  RtreeCell *aCell;
116529  int *aiUsed;
116530
116531  RtreeNode *pLeft = 0;
116532  RtreeNode *pRight = 0;
116533
116534  RtreeCell leftbbox;
116535  RtreeCell rightbbox;
116536
116537  /* Allocate an array and populate it with a copy of pCell and
116538  ** all cells from node pLeft. Then zero the original node.
116539  */
116540  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
116541  if( !aCell ){
116542    rc = SQLITE_NOMEM;
116543    goto splitnode_out;
116544  }
116545  aiUsed = (int *)&aCell[nCell+1];
116546  memset(aiUsed, 0, sizeof(int)*(nCell+1));
116547  for(i=0; i<nCell; i++){
116548    nodeGetCell(pRtree, pNode, i, &aCell[i]);
116549  }
116550  nodeZero(pRtree, pNode);
116551  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
116552  nCell++;
116553
116554  if( pNode->iNode==1 ){
116555    pRight = nodeNew(pRtree, pNode, 1);
116556    pLeft = nodeNew(pRtree, pNode, 1);
116557    pRtree->iDepth++;
116558    pNode->isDirty = 1;
116559    writeInt16(pNode->zData, pRtree->iDepth);
116560  }else{
116561    pLeft = pNode;
116562    pRight = nodeNew(pRtree, pLeft->pParent, 1);
116563    nodeReference(pLeft);
116564  }
116565
116566  if( !pLeft || !pRight ){
116567    rc = SQLITE_NOMEM;
116568    goto splitnode_out;
116569  }
116570
116571  memset(pLeft->zData, 0, pRtree->iNodeSize);
116572  memset(pRight->zData, 0, pRtree->iNodeSize);
116573
116574  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
116575  if( rc!=SQLITE_OK ){
116576    goto splitnode_out;
116577  }
116578
116579  /* Ensure both child nodes have node numbers assigned to them. */
116580  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
116581   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
116582  ){
116583    goto splitnode_out;
116584  }
116585
116586  rightbbox.iRowid = pRight->iNode;
116587  leftbbox.iRowid = pLeft->iNode;
116588
116589  if( pNode->iNode==1 ){
116590    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
116591    if( rc!=SQLITE_OK ){
116592      goto splitnode_out;
116593    }
116594  }else{
116595    RtreeNode *pParent = pLeft->pParent;
116596    int iCell = nodeParentIndex(pRtree, pLeft);
116597    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
116598    AdjustTree(pRtree, pParent, &leftbbox);
116599  }
116600  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
116601    goto splitnode_out;
116602  }
116603
116604  for(i=0; i<NCELL(pRight); i++){
116605    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
116606    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
116607    if( iRowid==pCell->iRowid ){
116608      newCellIsRight = 1;
116609    }
116610    if( rc!=SQLITE_OK ){
116611      goto splitnode_out;
116612    }
116613  }
116614  if( pNode->iNode==1 ){
116615    for(i=0; i<NCELL(pLeft); i++){
116616      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
116617      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
116618      if( rc!=SQLITE_OK ){
116619        goto splitnode_out;
116620      }
116621    }
116622  }else if( newCellIsRight==0 ){
116623    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
116624  }
116625
116626  if( rc==SQLITE_OK ){
116627    rc = nodeRelease(pRtree, pRight);
116628    pRight = 0;
116629  }
116630  if( rc==SQLITE_OK ){
116631    rc = nodeRelease(pRtree, pLeft);
116632    pLeft = 0;
116633  }
116634
116635splitnode_out:
116636  nodeRelease(pRtree, pRight);
116637  nodeRelease(pRtree, pLeft);
116638  sqlite3_free(aCell);
116639  return rc;
116640}
116641
116642static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
116643  int rc = SQLITE_OK;
116644  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
116645    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
116646    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
116647      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
116648      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
116649    }else{
116650      rc = SQLITE_ERROR;
116651    }
116652    sqlite3_reset(pRtree->pReadParent);
116653    if( rc==SQLITE_OK ){
116654      rc = fixLeafParent(pRtree, pLeaf->pParent);
116655    }
116656  }
116657  return rc;
116658}
116659
116660static int deleteCell(Rtree *, RtreeNode *, int, int);
116661
116662static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
116663  int rc;
116664  RtreeNode *pParent;
116665  int iCell;
116666
116667  assert( pNode->nRef==1 );
116668
116669  /* Remove the entry in the parent cell. */
116670  iCell = nodeParentIndex(pRtree, pNode);
116671  pParent = pNode->pParent;
116672  pNode->pParent = 0;
116673  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
116674   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
116675  ){
116676    return rc;
116677  }
116678
116679  /* Remove the xxx_node entry. */
116680  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
116681  sqlite3_step(pRtree->pDeleteNode);
116682  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
116683    return rc;
116684  }
116685
116686  /* Remove the xxx_parent entry. */
116687  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
116688  sqlite3_step(pRtree->pDeleteParent);
116689  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
116690    return rc;
116691  }
116692
116693  /* Remove the node from the in-memory hash table and link it into
116694  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
116695  */
116696  nodeHashDelete(pRtree, pNode);
116697  pNode->iNode = iHeight;
116698  pNode->pNext = pRtree->pDeleted;
116699  pNode->nRef++;
116700  pRtree->pDeleted = pNode;
116701
116702  return SQLITE_OK;
116703}
116704
116705static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
116706  RtreeNode *pParent = pNode->pParent;
116707  if( pParent ){
116708    int ii;
116709    int nCell = NCELL(pNode);
116710    RtreeCell box;                            /* Bounding box for pNode */
116711    nodeGetCell(pRtree, pNode, 0, &box);
116712    for(ii=1; ii<nCell; ii++){
116713      RtreeCell cell;
116714      nodeGetCell(pRtree, pNode, ii, &cell);
116715      cellUnion(pRtree, &box, &cell);
116716    }
116717    box.iRowid = pNode->iNode;
116718    ii = nodeParentIndex(pRtree, pNode);
116719    nodeOverwriteCell(pRtree, pParent, &box, ii);
116720    fixBoundingBox(pRtree, pParent);
116721  }
116722}
116723
116724/*
116725** Delete the cell at index iCell of node pNode. After removing the
116726** cell, adjust the r-tree data structure if required.
116727*/
116728static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
116729  int rc;
116730
116731  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
116732    return rc;
116733  }
116734
116735  /* Remove the cell from the node. This call just moves bytes around
116736  ** the in-memory node image, so it cannot fail.
116737  */
116738  nodeDeleteCell(pRtree, pNode, iCell);
116739
116740  /* If the node is not the tree root and now has less than the minimum
116741  ** number of cells, remove it from the tree. Otherwise, update the
116742  ** cell in the parent node so that it tightly contains the updated
116743  ** node.
116744  */
116745  if( pNode->iNode!=1 ){
116746    RtreeNode *pParent = pNode->pParent;
116747    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
116748     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
116749    ){
116750      rc = removeNode(pRtree, pNode, iHeight);
116751    }else{
116752      fixBoundingBox(pRtree, pNode);
116753    }
116754  }
116755
116756  return rc;
116757}
116758
116759static int Reinsert(
116760  Rtree *pRtree,
116761  RtreeNode *pNode,
116762  RtreeCell *pCell,
116763  int iHeight
116764){
116765  int *aOrder;
116766  int *aSpare;
116767  RtreeCell *aCell;
116768  float *aDistance;
116769  int nCell;
116770  float aCenterCoord[RTREE_MAX_DIMENSIONS];
116771  int iDim;
116772  int ii;
116773  int rc = SQLITE_OK;
116774
116775  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
116776
116777  nCell = NCELL(pNode)+1;
116778
116779  /* Allocate the buffers used by this operation. The allocation is
116780  ** relinquished before this function returns.
116781  */
116782  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
116783    sizeof(RtreeCell) +         /* aCell array */
116784    sizeof(int)       +         /* aOrder array */
116785    sizeof(int)       +         /* aSpare array */
116786    sizeof(float)               /* aDistance array */
116787  ));
116788  if( !aCell ){
116789    return SQLITE_NOMEM;
116790  }
116791  aOrder    = (int *)&aCell[nCell];
116792  aSpare    = (int *)&aOrder[nCell];
116793  aDistance = (float *)&aSpare[nCell];
116794
116795  for(ii=0; ii<nCell; ii++){
116796    if( ii==(nCell-1) ){
116797      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
116798    }else{
116799      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
116800    }
116801    aOrder[ii] = ii;
116802    for(iDim=0; iDim<pRtree->nDim; iDim++){
116803      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
116804      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
116805    }
116806  }
116807  for(iDim=0; iDim<pRtree->nDim; iDim++){
116808    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
116809  }
116810
116811  for(ii=0; ii<nCell; ii++){
116812    aDistance[ii] = 0.0;
116813    for(iDim=0; iDim<pRtree->nDim; iDim++){
116814      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
116815          DCOORD(aCell[ii].aCoord[iDim*2]);
116816      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
116817    }
116818  }
116819
116820  SortByDistance(aOrder, nCell, aDistance, aSpare);
116821  nodeZero(pRtree, pNode);
116822
116823  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
116824    RtreeCell *p = &aCell[aOrder[ii]];
116825    nodeInsertCell(pRtree, pNode, p);
116826    if( p->iRowid==pCell->iRowid ){
116827      if( iHeight==0 ){
116828        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
116829      }else{
116830        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
116831      }
116832    }
116833  }
116834  if( rc==SQLITE_OK ){
116835    fixBoundingBox(pRtree, pNode);
116836  }
116837  for(; rc==SQLITE_OK && ii<nCell; ii++){
116838    /* Find a node to store this cell in. pNode->iNode currently contains
116839    ** the height of the sub-tree headed by the cell.
116840    */
116841    RtreeNode *pInsert;
116842    RtreeCell *p = &aCell[aOrder[ii]];
116843    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
116844    if( rc==SQLITE_OK ){
116845      int rc2;
116846      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
116847      rc2 = nodeRelease(pRtree, pInsert);
116848      if( rc==SQLITE_OK ){
116849        rc = rc2;
116850      }
116851    }
116852  }
116853
116854  sqlite3_free(aCell);
116855  return rc;
116856}
116857
116858/*
116859** Insert cell pCell into node pNode. Node pNode is the head of a
116860** subtree iHeight high (leaf nodes have iHeight==0).
116861*/
116862static int rtreeInsertCell(
116863  Rtree *pRtree,
116864  RtreeNode *pNode,
116865  RtreeCell *pCell,
116866  int iHeight
116867){
116868  int rc = SQLITE_OK;
116869  if( iHeight>0 ){
116870    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
116871    if( pChild ){
116872      nodeRelease(pRtree, pChild->pParent);
116873      nodeReference(pNode);
116874      pChild->pParent = pNode;
116875    }
116876  }
116877  if( nodeInsertCell(pRtree, pNode, pCell) ){
116878#if VARIANT_RSTARTREE_REINSERT
116879    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
116880      rc = SplitNode(pRtree, pNode, pCell, iHeight);
116881    }else{
116882      pRtree->iReinsertHeight = iHeight;
116883      rc = Reinsert(pRtree, pNode, pCell, iHeight);
116884    }
116885#else
116886    rc = SplitNode(pRtree, pNode, pCell, iHeight);
116887#endif
116888  }else{
116889    AdjustTree(pRtree, pNode, pCell);
116890    if( iHeight==0 ){
116891      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
116892    }else{
116893      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
116894    }
116895  }
116896  return rc;
116897}
116898
116899static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
116900  int ii;
116901  int rc = SQLITE_OK;
116902  int nCell = NCELL(pNode);
116903
116904  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
116905    RtreeNode *pInsert;
116906    RtreeCell cell;
116907    nodeGetCell(pRtree, pNode, ii, &cell);
116908
116909    /* Find a node to store this cell in. pNode->iNode currently contains
116910    ** the height of the sub-tree headed by the cell.
116911    */
116912    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
116913    if( rc==SQLITE_OK ){
116914      int rc2;
116915      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
116916      rc2 = nodeRelease(pRtree, pInsert);
116917      if( rc==SQLITE_OK ){
116918        rc = rc2;
116919      }
116920    }
116921  }
116922  return rc;
116923}
116924
116925/*
116926** Select a currently unused rowid for a new r-tree record.
116927*/
116928static int newRowid(Rtree *pRtree, i64 *piRowid){
116929  int rc;
116930  sqlite3_bind_null(pRtree->pWriteRowid, 1);
116931  sqlite3_bind_null(pRtree->pWriteRowid, 2);
116932  sqlite3_step(pRtree->pWriteRowid);
116933  rc = sqlite3_reset(pRtree->pWriteRowid);
116934  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
116935  return rc;
116936}
116937
116938#ifndef NDEBUG
116939static int hashIsEmpty(Rtree *pRtree){
116940  int ii;
116941  for(ii=0; ii<HASHSIZE; ii++){
116942    assert( !pRtree->aHash[ii] );
116943  }
116944  return 1;
116945}
116946#endif
116947
116948/*
116949** The xUpdate method for rtree module virtual tables.
116950*/
116951static int rtreeUpdate(
116952  sqlite3_vtab *pVtab,
116953  int nData,
116954  sqlite3_value **azData,
116955  sqlite_int64 *pRowid
116956){
116957  Rtree *pRtree = (Rtree *)pVtab;
116958  int rc = SQLITE_OK;
116959
116960  rtreeReference(pRtree);
116961
116962  assert(nData>=1);
116963  assert(hashIsEmpty(pRtree));
116964
116965  /* If azData[0] is not an SQL NULL value, it is the rowid of a
116966  ** record to delete from the r-tree table. The following block does
116967  ** just that.
116968  */
116969  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
116970    i64 iDelete;                /* The rowid to delete */
116971    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
116972    int iCell;                  /* Index of iDelete cell in pLeaf */
116973    RtreeNode *pRoot;
116974
116975    /* Obtain a reference to the root node to initialise Rtree.iDepth */
116976    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
116977
116978    /* Obtain a reference to the leaf node that contains the entry
116979    ** about to be deleted.
116980    */
116981    if( rc==SQLITE_OK ){
116982      iDelete = sqlite3_value_int64(azData[0]);
116983      rc = findLeafNode(pRtree, iDelete, &pLeaf);
116984    }
116985
116986    /* Delete the cell in question from the leaf node. */
116987    if( rc==SQLITE_OK ){
116988      int rc2;
116989      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
116990      rc = deleteCell(pRtree, pLeaf, iCell, 0);
116991      rc2 = nodeRelease(pRtree, pLeaf);
116992      if( rc==SQLITE_OK ){
116993        rc = rc2;
116994      }
116995    }
116996
116997    /* Delete the corresponding entry in the <rtree>_rowid table. */
116998    if( rc==SQLITE_OK ){
116999      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
117000      sqlite3_step(pRtree->pDeleteRowid);
117001      rc = sqlite3_reset(pRtree->pDeleteRowid);
117002    }
117003
117004    /* Check if the root node now has exactly one child. If so, remove
117005    ** it, schedule the contents of the child for reinsertion and
117006    ** reduce the tree height by one.
117007    **
117008    ** This is equivalent to copying the contents of the child into
117009    ** the root node (the operation that Gutman's paper says to perform
117010    ** in this scenario).
117011    */
117012    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
117013      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
117014        RtreeNode *pChild;
117015        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
117016        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
117017        if( rc==SQLITE_OK ){
117018          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
117019        }
117020        if( rc==SQLITE_OK ){
117021          pRtree->iDepth--;
117022          writeInt16(pRoot->zData, pRtree->iDepth);
117023          pRoot->isDirty = 1;
117024        }
117025      }
117026    }
117027
117028    /* Re-insert the contents of any underfull nodes removed from the tree. */
117029    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
117030      if( rc==SQLITE_OK ){
117031        rc = reinsertNodeContent(pRtree, pLeaf);
117032      }
117033      pRtree->pDeleted = pLeaf->pNext;
117034      sqlite3_free(pLeaf);
117035    }
117036
117037    /* Release the reference to the root node. */
117038    if( rc==SQLITE_OK ){
117039      rc = nodeRelease(pRtree, pRoot);
117040    }else{
117041      nodeRelease(pRtree, pRoot);
117042    }
117043  }
117044
117045  /* If the azData[] array contains more than one element, elements
117046  ** (azData[2]..azData[argc-1]) contain a new record to insert into
117047  ** the r-tree structure.
117048  */
117049  if( rc==SQLITE_OK && nData>1 ){
117050    /* Insert a new record into the r-tree */
117051    RtreeCell cell;
117052    int ii;
117053    RtreeNode *pLeaf;
117054
117055    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
117056    assert( nData==(pRtree->nDim*2 + 3) );
117057    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
117058      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117059        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
117060        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
117061        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
117062          rc = SQLITE_CONSTRAINT;
117063          goto constraint;
117064        }
117065      }
117066    }else{
117067      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117068        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
117069        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
117070        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
117071          rc = SQLITE_CONSTRAINT;
117072          goto constraint;
117073        }
117074      }
117075    }
117076
117077    /* Figure out the rowid of the new row. */
117078    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
117079      rc = newRowid(pRtree, &cell.iRowid);
117080    }else{
117081      cell.iRowid = sqlite3_value_int64(azData[2]);
117082      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
117083      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
117084        sqlite3_reset(pRtree->pReadRowid);
117085        rc = SQLITE_CONSTRAINT;
117086        goto constraint;
117087      }
117088      rc = sqlite3_reset(pRtree->pReadRowid);
117089    }
117090    *pRowid = cell.iRowid;
117091
117092    if( rc==SQLITE_OK ){
117093      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
117094    }
117095    if( rc==SQLITE_OK ){
117096      int rc2;
117097      pRtree->iReinsertHeight = -1;
117098      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
117099      rc2 = nodeRelease(pRtree, pLeaf);
117100      if( rc==SQLITE_OK ){
117101        rc = rc2;
117102      }
117103    }
117104  }
117105
117106constraint:
117107  rtreeRelease(pRtree);
117108  return rc;
117109}
117110
117111/*
117112** The xRename method for rtree module virtual tables.
117113*/
117114static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
117115  Rtree *pRtree = (Rtree *)pVtab;
117116  int rc = SQLITE_NOMEM;
117117  char *zSql = sqlite3_mprintf(
117118    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
117119    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
117120    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
117121    , pRtree->zDb, pRtree->zName, zNewName
117122    , pRtree->zDb, pRtree->zName, zNewName
117123    , pRtree->zDb, pRtree->zName, zNewName
117124  );
117125  if( zSql ){
117126    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
117127    sqlite3_free(zSql);
117128  }
117129  return rc;
117130}
117131
117132static sqlite3_module rtreeModule = {
117133  0,                         /* iVersion */
117134  rtreeCreate,                /* xCreate - create a table */
117135  rtreeConnect,               /* xConnect - connect to an existing table */
117136  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
117137  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
117138  rtreeDestroy,               /* xDestroy - Drop a table */
117139  rtreeOpen,                  /* xOpen - open a cursor */
117140  rtreeClose,                 /* xClose - close a cursor */
117141  rtreeFilter,                /* xFilter - configure scan constraints */
117142  rtreeNext,                  /* xNext - advance a cursor */
117143  rtreeEof,                   /* xEof */
117144  rtreeColumn,                /* xColumn - read data */
117145  rtreeRowid,                 /* xRowid - read data */
117146  rtreeUpdate,                /* xUpdate - write data */
117147  0,                          /* xBegin - begin transaction */
117148  0,                          /* xSync - sync transaction */
117149  0,                          /* xCommit - commit transaction */
117150  0,                          /* xRollback - rollback transaction */
117151  0,                          /* xFindFunction - function overloading */
117152  rtreeRename                 /* xRename - rename the table */
117153};
117154
117155static int rtreeSqlInit(
117156  Rtree *pRtree,
117157  sqlite3 *db,
117158  const char *zDb,
117159  const char *zPrefix,
117160  int isCreate
117161){
117162  int rc = SQLITE_OK;
117163
117164  #define N_STATEMENT 9
117165  static const char *azSql[N_STATEMENT] = {
117166    /* Read and write the xxx_node table */
117167    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
117168    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
117169    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
117170
117171    /* Read and write the xxx_rowid table */
117172    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
117173    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
117174    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
117175
117176    /* Read and write the xxx_parent table */
117177    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
117178    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
117179    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
117180  };
117181  sqlite3_stmt **appStmt[N_STATEMENT];
117182  int i;
117183
117184  pRtree->db = db;
117185
117186  if( isCreate ){
117187    char *zCreate = sqlite3_mprintf(
117188"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
117189"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
117190"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
117191"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
117192      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
117193    );
117194    if( !zCreate ){
117195      return SQLITE_NOMEM;
117196    }
117197    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
117198    sqlite3_free(zCreate);
117199    if( rc!=SQLITE_OK ){
117200      return rc;
117201    }
117202  }
117203
117204  appStmt[0] = &pRtree->pReadNode;
117205  appStmt[1] = &pRtree->pWriteNode;
117206  appStmt[2] = &pRtree->pDeleteNode;
117207  appStmt[3] = &pRtree->pReadRowid;
117208  appStmt[4] = &pRtree->pWriteRowid;
117209  appStmt[5] = &pRtree->pDeleteRowid;
117210  appStmt[6] = &pRtree->pReadParent;
117211  appStmt[7] = &pRtree->pWriteParent;
117212  appStmt[8] = &pRtree->pDeleteParent;
117213
117214  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
117215    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
117216    if( zSql ){
117217      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
117218    }else{
117219      rc = SQLITE_NOMEM;
117220    }
117221    sqlite3_free(zSql);
117222  }
117223
117224  return rc;
117225}
117226
117227/*
117228** The second argument to this function contains the text of an SQL statement
117229** that returns a single integer value. The statement is compiled and executed
117230** using database connection db. If successful, the integer value returned
117231** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
117232** code is returned and the value of *piVal after returning is not defined.
117233*/
117234static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
117235  int rc = SQLITE_NOMEM;
117236  if( zSql ){
117237    sqlite3_stmt *pStmt = 0;
117238    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117239    if( rc==SQLITE_OK ){
117240      if( SQLITE_ROW==sqlite3_step(pStmt) ){
117241        *piVal = sqlite3_column_int(pStmt, 0);
117242      }
117243      rc = sqlite3_finalize(pStmt);
117244    }
117245  }
117246  return rc;
117247}
117248
117249/*
117250** This function is called from within the xConnect() or xCreate() method to
117251** determine the node-size used by the rtree table being created or connected
117252** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
117253** Otherwise, an SQLite error code is returned.
117254**
117255** If this function is being called as part of an xConnect(), then the rtree
117256** table already exists. In this case the node-size is determined by inspecting
117257** the root node of the tree.
117258**
117259** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
117260** This ensures that each node is stored on a single database page. If the
117261** database page-size is so large that more than RTREE_MAXCELLS entries
117262** would fit in a single node, use a smaller node-size.
117263*/
117264static int getNodeSize(
117265  sqlite3 *db,                    /* Database handle */
117266  Rtree *pRtree,                  /* Rtree handle */
117267  int isCreate                    /* True for xCreate, false for xConnect */
117268){
117269  int rc;
117270  char *zSql;
117271  if( isCreate ){
117272    int iPageSize;
117273    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
117274    rc = getIntFromStmt(db, zSql, &iPageSize);
117275    if( rc==SQLITE_OK ){
117276      pRtree->iNodeSize = iPageSize-64;
117277      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
117278        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
117279      }
117280    }
117281  }else{
117282    zSql = sqlite3_mprintf(
117283        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
117284        pRtree->zDb, pRtree->zName
117285    );
117286    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
117287  }
117288
117289  sqlite3_free(zSql);
117290  return rc;
117291}
117292
117293/*
117294** This function is the implementation of both the xConnect and xCreate
117295** methods of the r-tree virtual table.
117296**
117297**   argv[0]   -> module name
117298**   argv[1]   -> database name
117299**   argv[2]   -> table name
117300**   argv[...] -> column names...
117301*/
117302static int rtreeInit(
117303  sqlite3 *db,                        /* Database connection */
117304  void *pAux,                         /* One of the RTREE_COORD_* constants */
117305  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
117306  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
117307  char **pzErr,                       /* OUT: Error message, if any */
117308  int isCreate                        /* True for xCreate, false for xConnect */
117309){
117310  int rc = SQLITE_OK;
117311  Rtree *pRtree;
117312  int nDb;              /* Length of string argv[1] */
117313  int nName;            /* Length of string argv[2] */
117314  int eCoordType = (int)pAux;
117315
117316  const char *aErrMsg[] = {
117317    0,                                                    /* 0 */
117318    "Wrong number of columns for an rtree table",         /* 1 */
117319    "Too few columns for an rtree table",                 /* 2 */
117320    "Too many columns for an rtree table"                 /* 3 */
117321  };
117322
117323  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
117324  if( aErrMsg[iErr] ){
117325    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
117326    return SQLITE_ERROR;
117327  }
117328
117329  /* Allocate the sqlite3_vtab structure */
117330  nDb = strlen(argv[1]);
117331  nName = strlen(argv[2]);
117332  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
117333  if( !pRtree ){
117334    return SQLITE_NOMEM;
117335  }
117336  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
117337  pRtree->nBusy = 1;
117338  pRtree->base.pModule = &rtreeModule;
117339  pRtree->zDb = (char *)&pRtree[1];
117340  pRtree->zName = &pRtree->zDb[nDb+1];
117341  pRtree->nDim = (argc-4)/2;
117342  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
117343  pRtree->eCoordType = eCoordType;
117344  memcpy(pRtree->zDb, argv[1], nDb);
117345  memcpy(pRtree->zName, argv[2], nName);
117346
117347  /* Figure out the node size to use. */
117348  rc = getNodeSize(db, pRtree, isCreate);
117349
117350  /* Create/Connect to the underlying relational database schema. If
117351  ** that is successful, call sqlite3_declare_vtab() to configure
117352  ** the r-tree table schema.
117353  */
117354  if( rc==SQLITE_OK ){
117355    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
117356      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117357    }else{
117358      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
117359      char *zTmp;
117360      int ii;
117361      for(ii=4; zSql && ii<argc; ii++){
117362        zTmp = zSql;
117363        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
117364        sqlite3_free(zTmp);
117365      }
117366      if( zSql ){
117367        zTmp = zSql;
117368        zSql = sqlite3_mprintf("%s);", zTmp);
117369        sqlite3_free(zTmp);
117370      }
117371      if( !zSql ){
117372        rc = SQLITE_NOMEM;
117373      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
117374        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117375      }
117376      sqlite3_free(zSql);
117377    }
117378  }
117379
117380  if( rc==SQLITE_OK ){
117381    *ppVtab = (sqlite3_vtab *)pRtree;
117382  }else{
117383    rtreeRelease(pRtree);
117384  }
117385  return rc;
117386}
117387
117388
117389/*
117390** Implementation of a scalar function that decodes r-tree nodes to
117391** human readable strings. This can be used for debugging and analysis.
117392**
117393** The scalar function takes two arguments, a blob of data containing
117394** an r-tree node, and the number of dimensions the r-tree indexes.
117395** For a two-dimensional r-tree structure called "rt", to deserialize
117396** all nodes, a statement like:
117397**
117398**   SELECT rtreenode(2, data) FROM rt_node;
117399**
117400** The human readable string takes the form of a Tcl list with one
117401** entry for each cell in the r-tree node. Each entry is itself a
117402** list, containing the 8-byte rowid/pageno followed by the
117403** <num-dimension>*2 coordinates.
117404*/
117405static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117406  char *zText = 0;
117407  RtreeNode node;
117408  Rtree tree;
117409  int ii;
117410
117411  memset(&node, 0, sizeof(RtreeNode));
117412  memset(&tree, 0, sizeof(Rtree));
117413  tree.nDim = sqlite3_value_int(apArg[0]);
117414  tree.nBytesPerCell = 8 + 8 * tree.nDim;
117415  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
117416
117417  for(ii=0; ii<NCELL(&node); ii++){
117418    char zCell[512];
117419    int nCell = 0;
117420    RtreeCell cell;
117421    int jj;
117422
117423    nodeGetCell(&tree, &node, ii, &cell);
117424    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
117425    nCell = strlen(zCell);
117426    for(jj=0; jj<tree.nDim*2; jj++){
117427      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
117428      nCell = strlen(zCell);
117429    }
117430
117431    if( zText ){
117432      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
117433      sqlite3_free(zText);
117434      zText = zTextNew;
117435    }else{
117436      zText = sqlite3_mprintf("{%s}", zCell);
117437    }
117438  }
117439
117440  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
117441}
117442
117443static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117444  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
117445   || sqlite3_value_bytes(apArg[0])<2
117446  ){
117447    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
117448  }else{
117449    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
117450    sqlite3_result_int(ctx, readInt16(zBlob));
117451  }
117452}
117453
117454/*
117455** Register the r-tree module with database handle db. This creates the
117456** virtual table module "rtree" and the debugging/analysis scalar
117457** function "rtreenode".
117458*/
117459SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
117460  int rc = SQLITE_OK;
117461
117462  if( rc==SQLITE_OK ){
117463    int utf8 = SQLITE_UTF8;
117464    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
117465  }
117466  if( rc==SQLITE_OK ){
117467    int utf8 = SQLITE_UTF8;
117468    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
117469  }
117470  if( rc==SQLITE_OK ){
117471    void *c = (void *)RTREE_COORD_REAL32;
117472    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
117473  }
117474  if( rc==SQLITE_OK ){
117475    void *c = (void *)RTREE_COORD_INT32;
117476    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
117477  }
117478
117479  return rc;
117480}
117481
117482#if !SQLITE_CORE
117483SQLITE_API int sqlite3_extension_init(
117484  sqlite3 *db,
117485  char **pzErrMsg,
117486  const sqlite3_api_routines *pApi
117487){
117488  SQLITE_EXTENSION_INIT2(pApi)
117489  return sqlite3RtreeInit(db);
117490}
117491#endif
117492
117493#endif
117494
117495/************** End of rtree.c ***********************************************/
117496/************** Begin file icu.c *********************************************/
117497/*
117498** 2007 May 6
117499**
117500** The author disclaims copyright to this source code.  In place of
117501** a legal notice, here is a blessing:
117502**
117503**    May you do good and not evil.
117504**    May you find forgiveness for yourself and forgive others.
117505**    May you share freely, never taking more than you give.
117506**
117507*************************************************************************
117508** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
117509**
117510** This file implements an integration between the ICU library
117511** ("International Components for Unicode", an open-source library
117512** for handling unicode data) and SQLite. The integration uses
117513** ICU to provide the following to SQLite:
117514**
117515**   * An implementation of the SQL regexp() function (and hence REGEXP
117516**     operator) using the ICU uregex_XX() APIs.
117517**
117518**   * Implementations of the SQL scalar upper() and lower() functions
117519**     for case mapping.
117520**
117521**   * Integration of ICU and SQLite collation seqences.
117522**
117523**   * An implementation of the LIKE operator that uses ICU to
117524**     provide case-independent matching.
117525*/
117526
117527#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
117528
117529/* Include ICU headers */
117530#include <unicode/utypes.h>
117531#include <unicode/uregex.h>
117532#include <unicode/ustring.h>
117533#include <unicode/ucol.h>
117534
117535
117536#ifndef SQLITE_CORE
117537  SQLITE_EXTENSION_INIT1
117538#else
117539#endif
117540
117541/*
117542** Maximum length (in bytes) of the pattern in a LIKE or GLOB
117543** operator.
117544*/
117545#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
117546# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
117547#endif
117548
117549/*
117550** Version of sqlite3_free() that is always a function, never a macro.
117551*/
117552static void xFree(void *p){
117553  sqlite3_free(p);
117554}
117555
117556/*
117557** Compare two UTF-8 strings for equality where the first string is
117558** a "LIKE" expression. Return true (1) if they are the same and
117559** false (0) if they are different.
117560*/
117561static int icuLikeCompare(
117562  const uint8_t *zPattern,   /* LIKE pattern */
117563  const uint8_t *zString,    /* The UTF-8 string to compare against */
117564  const UChar32 uEsc         /* The escape character */
117565){
117566  static const int MATCH_ONE = (UChar32)'_';
117567  static const int MATCH_ALL = (UChar32)'%';
117568
117569  int iPattern = 0;       /* Current byte index in zPattern */
117570  int iString = 0;        /* Current byte index in zString */
117571
117572  int prevEscape = 0;     /* True if the previous character was uEsc */
117573
117574  while( zPattern[iPattern]!=0 ){
117575
117576    /* Read (and consume) the next character from the input pattern. */
117577    UChar32 uPattern;
117578    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
117579    assert(uPattern!=0);
117580
117581    /* There are now 4 possibilities:
117582    **
117583    **     1. uPattern is an unescaped match-all character "%",
117584    **     2. uPattern is an unescaped match-one character "_",
117585    **     3. uPattern is an unescaped escape character, or
117586    **     4. uPattern is to be handled as an ordinary character
117587    */
117588    if( !prevEscape && uPattern==MATCH_ALL ){
117589      /* Case 1. */
117590      uint8_t c;
117591
117592      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
117593      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
117594      ** test string.
117595      */
117596      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
117597        if( c==MATCH_ONE ){
117598          if( zString[iString]==0 ) return 0;
117599          U8_FWD_1_UNSAFE(zString, iString);
117600        }
117601        iPattern++;
117602      }
117603
117604      if( zPattern[iPattern]==0 ) return 1;
117605
117606      while( zString[iString] ){
117607        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
117608          return 1;
117609        }
117610        U8_FWD_1_UNSAFE(zString, iString);
117611      }
117612      return 0;
117613
117614    }else if( !prevEscape && uPattern==MATCH_ONE ){
117615      /* Case 2. */
117616      if( zString[iString]==0 ) return 0;
117617      U8_FWD_1_UNSAFE(zString, iString);
117618
117619    }else if( !prevEscape && uPattern==uEsc){
117620      /* Case 3. */
117621      prevEscape = 1;
117622
117623    }else{
117624      /* Case 4. */
117625      UChar32 uString;
117626      U8_NEXT_UNSAFE(zString, iString, uString);
117627      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
117628      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
117629      if( uString!=uPattern ){
117630        return 0;
117631      }
117632      prevEscape = 0;
117633    }
117634  }
117635
117636  return zString[iString]==0;
117637}
117638
117639/*
117640** Implementation of the like() SQL function.  This function implements
117641** the build-in LIKE operator.  The first argument to the function is the
117642** pattern and the second argument is the string.  So, the SQL statements:
117643**
117644**       A LIKE B
117645**
117646** is implemented as like(B, A). If there is an escape character E,
117647**
117648**       A LIKE B ESCAPE E
117649**
117650** is mapped to like(B, A, E).
117651*/
117652static void icuLikeFunc(
117653  sqlite3_context *context,
117654  int argc,
117655  sqlite3_value **argv
117656){
117657  const unsigned char *zA = sqlite3_value_text(argv[0]);
117658  const unsigned char *zB = sqlite3_value_text(argv[1]);
117659  UChar32 uEsc = 0;
117660
117661  /* Limit the length of the LIKE or GLOB pattern to avoid problems
117662  ** of deep recursion and N*N behavior in patternCompare().
117663  */
117664  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
117665    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
117666    return;
117667  }
117668
117669
117670  if( argc==3 ){
117671    /* The escape character string must consist of a single UTF-8 character.
117672    ** Otherwise, return an error.
117673    */
117674    int nE= sqlite3_value_bytes(argv[2]);
117675    const unsigned char *zE = sqlite3_value_text(argv[2]);
117676    int i = 0;
117677    if( zE==0 ) return;
117678    U8_NEXT(zE, i, nE, uEsc);
117679    if( i!=nE){
117680      sqlite3_result_error(context,
117681          "ESCAPE expression must be a single character", -1);
117682      return;
117683    }
117684  }
117685
117686  if( zA && zB ){
117687    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
117688  }
117689}
117690
117691/*
117692** This function is called when an ICU function called from within
117693** the implementation of an SQL scalar function returns an error.
117694**
117695** The scalar function context passed as the first argument is
117696** loaded with an error message based on the following two args.
117697*/
117698static void icuFunctionError(
117699  sqlite3_context *pCtx,       /* SQLite scalar function context */
117700  const char *zName,           /* Name of ICU function that failed */
117701  UErrorCode e                 /* Error code returned by ICU function */
117702){
117703  char zBuf[128];
117704  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
117705  zBuf[127] = '\0';
117706  sqlite3_result_error(pCtx, zBuf, -1);
117707}
117708
117709/*
117710** Function to delete compiled regexp objects. Registered as
117711** a destructor function with sqlite3_set_auxdata().
117712*/
117713static void icuRegexpDelete(void *p){
117714  URegularExpression *pExpr = (URegularExpression *)p;
117715  uregex_close(pExpr);
117716}
117717
117718/*
117719** Implementation of SQLite REGEXP operator. This scalar function takes
117720** two arguments. The first is a regular expression pattern to compile
117721** the second is a string to match against that pattern. If either
117722** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
117723** is 1 if the string matches the pattern, or 0 otherwise.
117724**
117725** SQLite maps the regexp() function to the regexp() operator such
117726** that the following two are equivalent:
117727**
117728**     zString REGEXP zPattern
117729**     regexp(zPattern, zString)
117730**
117731** Uses the following ICU regexp APIs:
117732**
117733**     uregex_open()
117734**     uregex_matches()
117735**     uregex_close()
117736*/
117737static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
117738  UErrorCode status = U_ZERO_ERROR;
117739  URegularExpression *pExpr;
117740  UBool res;
117741  const UChar *zString = sqlite3_value_text16(apArg[1]);
117742
117743  /* If the left hand side of the regexp operator is NULL,
117744  ** then the result is also NULL.
117745  */
117746  if( !zString ){
117747    return;
117748  }
117749
117750  pExpr = sqlite3_get_auxdata(p, 0);
117751  if( !pExpr ){
117752    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
117753    if( !zPattern ){
117754      return;
117755    }
117756    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
117757
117758    if( U_SUCCESS(status) ){
117759      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
117760    }else{
117761      assert(!pExpr);
117762      icuFunctionError(p, "uregex_open", status);
117763      return;
117764    }
117765  }
117766
117767  /* Configure the text that the regular expression operates on. */
117768  uregex_setText(pExpr, zString, -1, &status);
117769  if( !U_SUCCESS(status) ){
117770    icuFunctionError(p, "uregex_setText", status);
117771    return;
117772  }
117773
117774  /* Attempt the match */
117775  res = uregex_matches(pExpr, 0, &status);
117776  if( !U_SUCCESS(status) ){
117777    icuFunctionError(p, "uregex_matches", status);
117778    return;
117779  }
117780
117781  /* Set the text that the regular expression operates on to a NULL
117782  ** pointer. This is not really necessary, but it is tidier than
117783  ** leaving the regular expression object configured with an invalid
117784  ** pointer after this function returns.
117785  */
117786  uregex_setText(pExpr, 0, 0, &status);
117787
117788  /* Return 1 or 0. */
117789  sqlite3_result_int(p, res ? 1 : 0);
117790}
117791
117792/*
117793** Implementations of scalar functions for case mapping - upper() and
117794** lower(). Function upper() converts its input to upper-case (ABC).
117795** Function lower() converts to lower-case (abc).
117796**
117797** ICU provides two types of case mapping, "general" case mapping and
117798** "language specific". Refer to ICU documentation for the differences
117799** between the two.
117800**
117801** To utilise "general" case mapping, the upper() or lower() scalar
117802** functions are invoked with one argument:
117803**
117804**     upper('ABC') -> 'abc'
117805**     lower('abc') -> 'ABC'
117806**
117807** To access ICU "language specific" case mapping, upper() or lower()
117808** should be invoked with two arguments. The second argument is the name
117809** of the locale to use. Passing an empty string ("") or SQL NULL value
117810** as the second argument is the same as invoking the 1 argument version
117811** of upper() or lower().
117812**
117813**     lower('I', 'en_us') -> 'i'
117814**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
117815**
117816** http://www.icu-project.org/userguide/posix.html#case_mappings
117817*/
117818static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
117819  const UChar *zInput;
117820  UChar *zOutput;
117821  int nInput;
117822  int nOutput;
117823
117824  UErrorCode status = U_ZERO_ERROR;
117825  const char *zLocale = 0;
117826
117827  assert(nArg==1 || nArg==2);
117828  if( nArg==2 ){
117829    zLocale = (const char *)sqlite3_value_text(apArg[1]);
117830  }
117831
117832  zInput = sqlite3_value_text16(apArg[0]);
117833  if( !zInput ){
117834    return;
117835  }
117836  nInput = sqlite3_value_bytes16(apArg[0]);
117837
117838  nOutput = nInput * 2 + 2;
117839  zOutput = sqlite3_malloc(nOutput);
117840  if( !zOutput ){
117841    return;
117842  }
117843
117844  if( sqlite3_user_data(p) ){
117845    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
117846  }else{
117847    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
117848  }
117849
117850  if( !U_SUCCESS(status) ){
117851    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
117852    return;
117853  }
117854
117855  sqlite3_result_text16(p, zOutput, -1, xFree);
117856}
117857
117858/*
117859** Collation sequence destructor function. The pCtx argument points to
117860** a UCollator structure previously allocated using ucol_open().
117861*/
117862static void icuCollationDel(void *pCtx){
117863  UCollator *p = (UCollator *)pCtx;
117864  ucol_close(p);
117865}
117866
117867/*
117868** Collation sequence comparison function. The pCtx argument points to
117869** a UCollator structure previously allocated using ucol_open().
117870*/
117871static int icuCollationColl(
117872  void *pCtx,
117873  int nLeft,
117874  const void *zLeft,
117875  int nRight,
117876  const void *zRight
117877){
117878  UCollationResult res;
117879  UCollator *p = (UCollator *)pCtx;
117880  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
117881  switch( res ){
117882    case UCOL_LESS:    return -1;
117883    case UCOL_GREATER: return +1;
117884    case UCOL_EQUAL:   return 0;
117885  }
117886  assert(!"Unexpected return value from ucol_strcoll()");
117887  return 0;
117888}
117889
117890/*
117891** Implementation of the scalar function icu_load_collation().
117892**
117893** This scalar function is used to add ICU collation based collation
117894** types to an SQLite database connection. It is intended to be called
117895** as follows:
117896**
117897**     SELECT icu_load_collation(<locale>, <collation-name>);
117898**
117899** Where <locale> is a string containing an ICU locale identifier (i.e.
117900** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
117901** collation sequence to create.
117902*/
117903static void icuLoadCollation(
117904  sqlite3_context *p,
117905  int nArg,
117906  sqlite3_value **apArg
117907){
117908  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
117909  UErrorCode status = U_ZERO_ERROR;
117910  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
117911  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
117912  UCollator *pUCollator;    /* ICU library collation object */
117913  int rc;                   /* Return code from sqlite3_create_collation_x() */
117914
117915  assert(nArg==2);
117916  zLocale = (const char *)sqlite3_value_text(apArg[0]);
117917  zName = (const char *)sqlite3_value_text(apArg[1]);
117918
117919  if( !zLocale || !zName ){
117920    return;
117921  }
117922
117923  pUCollator = ucol_open(zLocale, &status);
117924  if( !U_SUCCESS(status) ){
117925    icuFunctionError(p, "ucol_open", status);
117926    return;
117927  }
117928  assert(p);
117929
117930  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
117931      icuCollationColl, icuCollationDel
117932  );
117933  if( rc!=SQLITE_OK ){
117934    ucol_close(pUCollator);
117935    sqlite3_result_error(p, "Error registering collation function", -1);
117936  }
117937}
117938
117939/*
117940** Register the ICU extension functions with database db.
117941*/
117942SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
117943  struct IcuScalar {
117944    const char *zName;                        /* Function name */
117945    int nArg;                                 /* Number of arguments */
117946    int enc;                                  /* Optimal text encoding */
117947    void *pContext;                           /* sqlite3_user_data() context */
117948    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
117949  } scalars[] = {
117950    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
117951
117952    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
117953    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
117954    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
117955    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
117956
117957    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
117958    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
117959    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
117960    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
117961
117962    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
117963    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
117964
117965    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
117966  };
117967
117968  int rc = SQLITE_OK;
117969  int i;
117970
117971  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
117972    struct IcuScalar *p = &scalars[i];
117973    rc = sqlite3_create_function(
117974        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
117975    );
117976  }
117977
117978  return rc;
117979}
117980
117981#if !SQLITE_CORE
117982SQLITE_API int sqlite3_extension_init(
117983  sqlite3 *db,
117984  char **pzErrMsg,
117985  const sqlite3_api_routines *pApi
117986){
117987  SQLITE_EXTENSION_INIT2(pApi)
117988  return sqlite3IcuInit(db);
117989}
117990#endif
117991
117992#endif
117993
117994/************** End of icu.c *************************************************/
117995/************** Begin file fts3_icu.c ****************************************/
117996/*
117997** 2007 June 22
117998**
117999** The author disclaims copyright to this source code.  In place of
118000** a legal notice, here is a blessing:
118001**
118002**    May you do good and not evil.
118003**    May you find forgiveness for yourself and forgive others.
118004**    May you share freely, never taking more than you give.
118005**
118006*************************************************************************
118007** This file implements a tokenizer for fts3 based on the ICU library.
118008**
118009** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
118010*/
118011
118012#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118013#ifdef SQLITE_ENABLE_ICU
118014
118015
118016#include <unicode/ubrk.h>
118017#include <unicode/utf16.h>
118018
118019typedef struct IcuTokenizer IcuTokenizer;
118020typedef struct IcuCursor IcuCursor;
118021
118022struct IcuTokenizer {
118023  sqlite3_tokenizer base;
118024  char *zLocale;
118025};
118026
118027struct IcuCursor {
118028  sqlite3_tokenizer_cursor base;
118029
118030  UBreakIterator *pIter;      /* ICU break-iterator object */
118031  int nChar;                  /* Number of UChar elements in pInput */
118032  UChar *aChar;               /* Copy of input using utf-16 encoding */
118033  int *aOffset;               /* Offsets of each character in utf-8 input */
118034
118035  int nBuffer;
118036  char *zBuffer;
118037
118038  int iToken;
118039};
118040
118041/*
118042** Create a new tokenizer instance.
118043*/
118044static int icuCreate(
118045  int argc,                            /* Number of entries in argv[] */
118046  const char * const *argv,            /* Tokenizer creation arguments */
118047  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
118048){
118049  IcuTokenizer *p;
118050  int n = 0;
118051
118052  if( argc>0 ){
118053    n = strlen(argv[0])+1;
118054  }
118055  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
118056  if( !p ){
118057    return SQLITE_NOMEM;
118058  }
118059  memset(p, 0, sizeof(IcuTokenizer));
118060
118061  if( n ){
118062    p->zLocale = (char *)&p[1];
118063    memcpy(p->zLocale, argv[0], n);
118064  }
118065
118066  *ppTokenizer = (sqlite3_tokenizer *)p;
118067
118068  return SQLITE_OK;
118069}
118070
118071/*
118072** Destroy a tokenizer
118073*/
118074static int icuDestroy(sqlite3_tokenizer *pTokenizer){
118075  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118076  sqlite3_free(p);
118077  return SQLITE_OK;
118078}
118079
118080/*
118081** Prepare to begin tokenizing a particular string.  The input
118082** string to be tokenized is pInput[0..nBytes-1].  A cursor
118083** used to incrementally tokenize this string is returned in
118084** *ppCursor.
118085*/
118086static int icuOpen(
118087  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
118088  const char *zInput,                    /* Input string */
118089  int nInput,                            /* Length of zInput in bytes */
118090  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
118091){
118092  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118093  IcuCursor *pCsr;
118094
118095  const int32_t opt = U_FOLD_CASE_DEFAULT;
118096  UErrorCode status = U_ZERO_ERROR;
118097  int nChar;
118098
118099  UChar32 c;
118100  int iInput = 0;
118101  int iOut = 0;
118102
118103  *ppCursor = 0;
118104
118105  if( nInput<0 ){
118106    nInput = strlen(zInput);
118107  }
118108  nChar = nInput+1;
118109  pCsr = (IcuCursor *)sqlite3_malloc(
118110      sizeof(IcuCursor) +                /* IcuCursor */
118111      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
118112      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
118113  );
118114  if( !pCsr ){
118115    return SQLITE_NOMEM;
118116  }
118117  memset(pCsr, 0, sizeof(IcuCursor));
118118  pCsr->aChar = (UChar *)&pCsr[1];
118119  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
118120
118121  pCsr->aOffset[iOut] = iInput;
118122  U8_NEXT(zInput, iInput, nInput, c);
118123  while( c>0 ){
118124    int isError = 0;
118125    c = u_foldCase(c, opt);
118126    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
118127    if( isError ){
118128      sqlite3_free(pCsr);
118129      return SQLITE_ERROR;
118130    }
118131    pCsr->aOffset[iOut] = iInput;
118132
118133    if( iInput<nInput ){
118134      U8_NEXT(zInput, iInput, nInput, c);
118135    }else{
118136      c = 0;
118137    }
118138  }
118139
118140  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
118141  if( !U_SUCCESS(status) ){
118142    sqlite3_free(pCsr);
118143    return SQLITE_ERROR;
118144  }
118145  pCsr->nChar = iOut;
118146
118147  ubrk_first(pCsr->pIter);
118148  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
118149  return SQLITE_OK;
118150}
118151
118152/*
118153** Close a tokenization cursor previously opened by a call to icuOpen().
118154*/
118155static int icuClose(sqlite3_tokenizer_cursor *pCursor){
118156  IcuCursor *pCsr = (IcuCursor *)pCursor;
118157  ubrk_close(pCsr->pIter);
118158  sqlite3_free(pCsr->zBuffer);
118159  sqlite3_free(pCsr);
118160  return SQLITE_OK;
118161}
118162
118163/*
118164** Extract the next token from a tokenization cursor.
118165*/
118166static int icuNext(
118167  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
118168  const char **ppToken,               /* OUT: *ppToken is the token text */
118169  int *pnBytes,                       /* OUT: Number of bytes in token */
118170  int *piStartOffset,                 /* OUT: Starting offset of token */
118171  int *piEndOffset,                   /* OUT: Ending offset of token */
118172  int *piPosition                     /* OUT: Position integer of token */
118173){
118174  IcuCursor *pCsr = (IcuCursor *)pCursor;
118175
118176  int iStart = 0;
118177  int iEnd = 0;
118178  int nByte = 0;
118179
118180  while( iStart==iEnd ){
118181    UChar32 c;
118182
118183    iStart = ubrk_current(pCsr->pIter);
118184    iEnd = ubrk_next(pCsr->pIter);
118185    if( iEnd==UBRK_DONE ){
118186      return SQLITE_DONE;
118187    }
118188
118189    while( iStart<iEnd ){
118190      int iWhite = iStart;
118191      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
118192      if( u_isspace(c) ){
118193        iStart = iWhite;
118194      }else{
118195        break;
118196      }
118197    }
118198    assert(iStart<=iEnd);
118199  }
118200
118201  do {
118202    UErrorCode status = U_ZERO_ERROR;
118203    if( nByte ){
118204      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
118205      if( !zNew ){
118206        return SQLITE_NOMEM;
118207      }
118208      pCsr->zBuffer = zNew;
118209      pCsr->nBuffer = nByte;
118210    }
118211
118212    u_strToUTF8(
118213        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
118214        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
118215        &status                                  /* Output success/failure */
118216    );
118217  } while( nByte>pCsr->nBuffer );
118218
118219  *ppToken = pCsr->zBuffer;
118220  *pnBytes = nByte;
118221  *piStartOffset = pCsr->aOffset[iStart];
118222  *piEndOffset = pCsr->aOffset[iEnd];
118223  *piPosition = pCsr->iToken++;
118224
118225  return SQLITE_OK;
118226}
118227
118228/*
118229** The set of routines that implement the simple tokenizer
118230*/
118231static const sqlite3_tokenizer_module icuTokenizerModule = {
118232  0,                           /* iVersion */
118233  icuCreate,                   /* xCreate  */
118234  icuDestroy,                  /* xCreate  */
118235  icuOpen,                     /* xOpen    */
118236  icuClose,                    /* xClose   */
118237  icuNext,                     /* xNext    */
118238};
118239
118240/*
118241** Set *ppModule to point at the implementation of the ICU tokenizer.
118242*/
118243SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
118244  sqlite3_tokenizer_module const**ppModule
118245){
118246  *ppModule = &icuTokenizerModule;
118247}
118248
118249#endif /* defined(SQLITE_ENABLE_ICU) */
118250#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118251
118252/************** End of fts3_icu.c ********************************************/
118253